babylon.2.1-alpha.debug.js 1.3 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014
  1. var __extends = this.__extends || function (d, b) {
  2. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  3. function __() { this.constructor = d; }
  4. __.prototype = b.prototype;
  5. d.prototype = new __();
  6. };var BABYLON;
  7. (function (BABYLON) {
  8. var Color3 = (function () {
  9. function Color3(r, g, b) {
  10. if (r === void 0) { r = 0; }
  11. if (g === void 0) { g = 0; }
  12. if (b === void 0) { b = 0; }
  13. this.r = r;
  14. this.g = g;
  15. this.b = b;
  16. }
  17. Color3.prototype.toString = function () {
  18. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  19. };
  20. // Operators
  21. Color3.prototype.toArray = function (array, index) {
  22. if (index === undefined) {
  23. index = 0;
  24. }
  25. array[index] = this.r;
  26. array[index + 1] = this.g;
  27. array[index + 2] = this.b;
  28. return this;
  29. };
  30. Color3.prototype.toColor4 = function (alpha) {
  31. if (alpha === void 0) { alpha = 1; }
  32. return new Color4(this.r, this.g, this.b, alpha);
  33. };
  34. Color3.prototype.asArray = function () {
  35. var result = [];
  36. this.toArray(result, 0);
  37. return result;
  38. };
  39. Color3.prototype.toLuminance = function () {
  40. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  41. };
  42. Color3.prototype.multiply = function (otherColor) {
  43. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  44. };
  45. Color3.prototype.multiplyToRef = function (otherColor, result) {
  46. result.r = this.r * otherColor.r;
  47. result.g = this.g * otherColor.g;
  48. result.b = this.b * otherColor.b;
  49. return this;
  50. };
  51. Color3.prototype.equals = function (otherColor) {
  52. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  53. };
  54. Color3.prototype.scale = function (scale) {
  55. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  56. };
  57. Color3.prototype.scaleToRef = function (scale, result) {
  58. result.r = this.r * scale;
  59. result.g = this.g * scale;
  60. result.b = this.b * scale;
  61. return this;
  62. };
  63. Color3.prototype.add = function (otherColor) {
  64. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  65. };
  66. Color3.prototype.addToRef = function (otherColor, result) {
  67. result.r = this.r + otherColor.r;
  68. result.g = this.g + otherColor.g;
  69. result.b = this.b + otherColor.b;
  70. return this;
  71. };
  72. Color3.prototype.subtract = function (otherColor) {
  73. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  74. };
  75. Color3.prototype.subtractToRef = function (otherColor, result) {
  76. result.r = this.r - otherColor.r;
  77. result.g = this.g - otherColor.g;
  78. result.b = this.b - otherColor.b;
  79. return this;
  80. };
  81. Color3.prototype.clone = function () {
  82. return new Color3(this.r, this.g, this.b);
  83. };
  84. Color3.prototype.copyFrom = function (source) {
  85. this.r = source.r;
  86. this.g = source.g;
  87. this.b = source.b;
  88. return this;
  89. };
  90. Color3.prototype.copyFromFloats = function (r, g, b) {
  91. this.r = r;
  92. this.g = g;
  93. this.b = b;
  94. return this;
  95. };
  96. // Statics
  97. Color3.FromArray = function (array, offset) {
  98. if (offset === void 0) { offset = 0; }
  99. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  100. };
  101. Color3.FromInts = function (r, g, b) {
  102. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  103. };
  104. Color3.Lerp = function (start, end, amount) {
  105. var r = start.r + ((end.r - start.r) * amount);
  106. var g = start.g + ((end.g - start.g) * amount);
  107. var b = start.b + ((end.b - start.b) * amount);
  108. return new Color3(r, g, b);
  109. };
  110. Color3.Red = function () {
  111. return new Color3(1, 0, 0);
  112. };
  113. Color3.Green = function () {
  114. return new Color3(0, 1, 0);
  115. };
  116. Color3.Blue = function () {
  117. return new Color3(0, 0, 1);
  118. };
  119. Color3.Black = function () {
  120. return new Color3(0, 0, 0);
  121. };
  122. Color3.White = function () {
  123. return new Color3(1, 1, 1);
  124. };
  125. Color3.Purple = function () {
  126. return new Color3(0.5, 0, 0.5);
  127. };
  128. Color3.Magenta = function () {
  129. return new Color3(1, 0, 1);
  130. };
  131. Color3.Yellow = function () {
  132. return new Color3(1, 1, 0);
  133. };
  134. Color3.Gray = function () {
  135. return new Color3(0.5, 0.5, 0.5);
  136. };
  137. return Color3;
  138. })();
  139. BABYLON.Color3 = Color3;
  140. var Color4 = (function () {
  141. function Color4(r, g, b, a) {
  142. this.r = r;
  143. this.g = g;
  144. this.b = b;
  145. this.a = a;
  146. }
  147. // Operators
  148. Color4.prototype.addInPlace = function (right) {
  149. this.r += right.r;
  150. this.g += right.g;
  151. this.b += right.b;
  152. this.a += right.a;
  153. return this;
  154. };
  155. Color4.prototype.asArray = function () {
  156. var result = [];
  157. this.toArray(result, 0);
  158. return result;
  159. };
  160. Color4.prototype.toArray = function (array, index) {
  161. if (index === undefined) {
  162. index = 0;
  163. }
  164. array[index] = this.r;
  165. array[index + 1] = this.g;
  166. array[index + 2] = this.b;
  167. array[index + 3] = this.a;
  168. return this;
  169. };
  170. Color4.prototype.add = function (right) {
  171. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  172. };
  173. Color4.prototype.subtract = function (right) {
  174. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  175. };
  176. Color4.prototype.subtractToRef = function (right, result) {
  177. result.r = this.r - right.r;
  178. result.g = this.g - right.g;
  179. result.b = this.b - right.b;
  180. result.a = this.a - right.a;
  181. return this;
  182. };
  183. Color4.prototype.scale = function (scale) {
  184. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  185. };
  186. Color4.prototype.scaleToRef = function (scale, result) {
  187. result.r = this.r * scale;
  188. result.g = this.g * scale;
  189. result.b = this.b * scale;
  190. result.a = this.a * scale;
  191. return this;
  192. };
  193. Color4.prototype.toString = function () {
  194. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  195. };
  196. Color4.prototype.clone = function () {
  197. return new Color4(this.r, this.g, this.b, this.a);
  198. };
  199. Color4.prototype.copyFrom = function (source) {
  200. this.r = source.r;
  201. this.g = source.g;
  202. this.b = source.b;
  203. this.a = source.a;
  204. return this;
  205. };
  206. // Statics
  207. Color4.Lerp = function (left, right, amount) {
  208. var result = new Color4(0, 0, 0, 0);
  209. Color4.LerpToRef(left, right, amount, result);
  210. return result;
  211. };
  212. Color4.LerpToRef = function (left, right, amount, result) {
  213. result.r = left.r + (right.r - left.r) * amount;
  214. result.g = left.g + (right.g - left.g) * amount;
  215. result.b = left.b + (right.b - left.b) * amount;
  216. result.a = left.a + (right.a - left.a) * amount;
  217. };
  218. Color4.FromArray = function (array, offset) {
  219. if (offset === void 0) { offset = 0; }
  220. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  221. };
  222. Color4.FromInts = function (r, g, b, a) {
  223. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  224. };
  225. return Color4;
  226. })();
  227. BABYLON.Color4 = Color4;
  228. var Vector2 = (function () {
  229. function Vector2(x, y) {
  230. this.x = x;
  231. this.y = y;
  232. }
  233. Vector2.prototype.toString = function () {
  234. return "{X: " + this.x + " Y:" + this.y + "}";
  235. };
  236. // Operators
  237. Vector2.prototype.toArray = function (array, index) {
  238. if (index === void 0) { index = 0; }
  239. array[index] = this.x;
  240. array[index + 1] = this.y;
  241. return this;
  242. };
  243. Vector2.prototype.asArray = function () {
  244. var result = [];
  245. this.toArray(result, 0);
  246. return result;
  247. };
  248. Vector2.prototype.copyFrom = function (source) {
  249. this.x = source.x;
  250. this.y = source.y;
  251. return this;
  252. };
  253. Vector2.prototype.copyFromFloats = function (x, y) {
  254. this.x = x;
  255. this.y = y;
  256. return this;
  257. };
  258. Vector2.prototype.add = function (otherVector) {
  259. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  260. };
  261. Vector2.prototype.addVector3 = function (otherVector) {
  262. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  263. };
  264. Vector2.prototype.subtract = function (otherVector) {
  265. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  266. };
  267. Vector2.prototype.subtractInPlace = function (otherVector) {
  268. this.x -= otherVector.x;
  269. this.y -= otherVector.y;
  270. return this;
  271. };
  272. Vector2.prototype.multiplyInPlace = function (otherVector) {
  273. this.x *= otherVector.x;
  274. this.y *= otherVector.y;
  275. return this;
  276. };
  277. Vector2.prototype.multiply = function (otherVector) {
  278. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  279. };
  280. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  281. result.x = this.x * otherVector.x;
  282. result.y = this.y * otherVector.y;
  283. return this;
  284. };
  285. Vector2.prototype.multiplyByFloats = function (x, y) {
  286. return new Vector2(this.x * x, this.y * y);
  287. };
  288. Vector2.prototype.divide = function (otherVector) {
  289. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  290. };
  291. Vector2.prototype.divideToRef = function (otherVector, result) {
  292. result.x = this.x / otherVector.x;
  293. result.y = this.y / otherVector.y;
  294. return this;
  295. };
  296. Vector2.prototype.negate = function () {
  297. return new Vector2(-this.x, -this.y);
  298. };
  299. Vector2.prototype.scaleInPlace = function (scale) {
  300. this.x *= scale;
  301. this.y *= scale;
  302. return this;
  303. };
  304. Vector2.prototype.scale = function (scale) {
  305. return new Vector2(this.x * scale, this.y * scale);
  306. };
  307. Vector2.prototype.equals = function (otherVector) {
  308. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  309. };
  310. // Properties
  311. Vector2.prototype.length = function () {
  312. return Math.sqrt(this.x * this.x + this.y * this.y);
  313. };
  314. Vector2.prototype.lengthSquared = function () {
  315. return (this.x * this.x + this.y * this.y);
  316. };
  317. // Methods
  318. Vector2.prototype.normalize = function () {
  319. var len = this.length();
  320. if (len === 0)
  321. return this;
  322. var num = 1.0 / len;
  323. this.x *= num;
  324. this.y *= num;
  325. return this;
  326. };
  327. Vector2.prototype.clone = function () {
  328. return new Vector2(this.x, this.y);
  329. };
  330. // Statics
  331. Vector2.Zero = function () {
  332. return new Vector2(0, 0);
  333. };
  334. Vector2.FromArray = function (array, offset) {
  335. if (offset === void 0) { offset = 0; }
  336. return new Vector2(array[offset], array[offset + 1]);
  337. };
  338. Vector2.FromArrayToRef = function (array, offset, result) {
  339. result.x = array[offset];
  340. result.y = array[offset + 1];
  341. };
  342. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  343. var squared = amount * amount;
  344. var cubed = amount * squared;
  345. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) + (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) + ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  346. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) + (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) + ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  347. return new Vector2(x, y);
  348. };
  349. Vector2.Clamp = function (value, min, max) {
  350. var x = value.x;
  351. x = (x > max.x) ? max.x : x;
  352. x = (x < min.x) ? min.x : x;
  353. var y = value.y;
  354. y = (y > max.y) ? max.y : y;
  355. y = (y < min.y) ? min.y : y;
  356. return new Vector2(x, y);
  357. };
  358. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  359. var squared = amount * amount;
  360. var cubed = amount * squared;
  361. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  362. var part2 = (-2.0 * cubed) + (3.0 * squared);
  363. var part3 = (cubed - (2.0 * squared)) + amount;
  364. var part4 = cubed - squared;
  365. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  366. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  367. return new Vector2(x, y);
  368. };
  369. Vector2.Lerp = function (start, end, amount) {
  370. var x = start.x + ((end.x - start.x) * amount);
  371. var y = start.y + ((end.y - start.y) * amount);
  372. return new Vector2(x, y);
  373. };
  374. Vector2.Dot = function (left, right) {
  375. return left.x * right.x + left.y * right.y;
  376. };
  377. Vector2.Normalize = function (vector) {
  378. var newVector = vector.clone();
  379. newVector.normalize();
  380. return newVector;
  381. };
  382. Vector2.Minimize = function (left, right) {
  383. var x = (left.x < right.x) ? left.x : right.x;
  384. var y = (left.y < right.y) ? left.y : right.y;
  385. return new Vector2(x, y);
  386. };
  387. Vector2.Maximize = function (left, right) {
  388. var x = (left.x > right.x) ? left.x : right.x;
  389. var y = (left.y > right.y) ? left.y : right.y;
  390. return new Vector2(x, y);
  391. };
  392. Vector2.Transform = function (vector, transformation) {
  393. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]);
  394. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]);
  395. return new Vector2(x, y);
  396. };
  397. Vector2.Distance = function (value1, value2) {
  398. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  399. };
  400. Vector2.DistanceSquared = function (value1, value2) {
  401. var x = value1.x - value2.x;
  402. var y = value1.y - value2.y;
  403. return (x * x) + (y * y);
  404. };
  405. return Vector2;
  406. })();
  407. BABYLON.Vector2 = Vector2;
  408. var Vector3 = (function () {
  409. function Vector3(x, y, z) {
  410. this.x = x;
  411. this.y = y;
  412. this.z = z;
  413. }
  414. Vector3.prototype.toString = function () {
  415. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  416. };
  417. // Operators
  418. Vector3.prototype.asArray = function () {
  419. var result = [];
  420. this.toArray(result, 0);
  421. return result;
  422. };
  423. Vector3.prototype.toArray = function (array, index) {
  424. if (index === void 0) { index = 0; }
  425. array[index] = this.x;
  426. array[index + 1] = this.y;
  427. array[index + 2] = this.z;
  428. return this;
  429. };
  430. Vector3.prototype.toQuaternion = function () {
  431. var result = new Quaternion(0, 0, 0, 1);
  432. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  433. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  434. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  435. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  436. var cosy = Math.cos(this.y * 0.5);
  437. var siny = Math.sin(this.y * 0.5);
  438. result.x = coszMinusx * siny;
  439. result.y = -sinzMinusx * siny;
  440. result.z = sinxPlusz * cosy;
  441. result.w = cosxPlusz * cosy;
  442. return result;
  443. };
  444. Vector3.prototype.addInPlace = function (otherVector) {
  445. this.x += otherVector.x;
  446. this.y += otherVector.y;
  447. this.z += otherVector.z;
  448. return this;
  449. };
  450. Vector3.prototype.add = function (otherVector) {
  451. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  452. };
  453. Vector3.prototype.addToRef = function (otherVector, result) {
  454. result.x = this.x + otherVector.x;
  455. result.y = this.y + otherVector.y;
  456. result.z = this.z + otherVector.z;
  457. return this;
  458. };
  459. Vector3.prototype.subtractInPlace = function (otherVector) {
  460. this.x -= otherVector.x;
  461. this.y -= otherVector.y;
  462. this.z -= otherVector.z;
  463. return this;
  464. };
  465. Vector3.prototype.subtract = function (otherVector) {
  466. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  467. };
  468. Vector3.prototype.subtractToRef = function (otherVector, result) {
  469. result.x = this.x - otherVector.x;
  470. result.y = this.y - otherVector.y;
  471. result.z = this.z - otherVector.z;
  472. return this;
  473. };
  474. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  475. return new Vector3(this.x - x, this.y - y, this.z - z);
  476. };
  477. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  478. result.x = this.x - x;
  479. result.y = this.y - y;
  480. result.z = this.z - z;
  481. return this;
  482. };
  483. Vector3.prototype.negate = function () {
  484. return new Vector3(-this.x, -this.y, -this.z);
  485. };
  486. Vector3.prototype.scaleInPlace = function (scale) {
  487. this.x *= scale;
  488. this.y *= scale;
  489. this.z *= scale;
  490. return this;
  491. };
  492. Vector3.prototype.scale = function (scale) {
  493. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  494. };
  495. Vector3.prototype.scaleToRef = function (scale, result) {
  496. result.x = this.x * scale;
  497. result.y = this.y * scale;
  498. result.z = this.z * scale;
  499. };
  500. Vector3.prototype.equals = function (otherVector) {
  501. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  502. };
  503. Vector3.prototype.equalsWithEpsilon = function (otherVector) {
  504. return Math.abs(this.x - otherVector.x) < BABYLON.Engine.Epsilon && Math.abs(this.y - otherVector.y) < BABYLON.Engine.Epsilon && Math.abs(this.z - otherVector.z) < BABYLON.Engine.Epsilon;
  505. };
  506. Vector3.prototype.equalsToFloats = function (x, y, z) {
  507. return this.x === x && this.y === y && this.z === z;
  508. };
  509. Vector3.prototype.multiplyInPlace = function (otherVector) {
  510. this.x *= otherVector.x;
  511. this.y *= otherVector.y;
  512. this.z *= otherVector.z;
  513. return this;
  514. };
  515. Vector3.prototype.multiply = function (otherVector) {
  516. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  517. };
  518. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  519. result.x = this.x * otherVector.x;
  520. result.y = this.y * otherVector.y;
  521. result.z = this.z * otherVector.z;
  522. return this;
  523. };
  524. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  525. return new Vector3(this.x * x, this.y * y, this.z * z);
  526. };
  527. Vector3.prototype.divide = function (otherVector) {
  528. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  529. };
  530. Vector3.prototype.divideToRef = function (otherVector, result) {
  531. result.x = this.x / otherVector.x;
  532. result.y = this.y / otherVector.y;
  533. result.z = this.z / otherVector.z;
  534. return this;
  535. };
  536. Vector3.prototype.MinimizeInPlace = function (other) {
  537. if (other.x < this.x)
  538. this.x = other.x;
  539. if (other.y < this.y)
  540. this.y = other.y;
  541. if (other.z < this.z)
  542. this.z = other.z;
  543. return this;
  544. };
  545. Vector3.prototype.MaximizeInPlace = function (other) {
  546. if (other.x > this.x)
  547. this.x = other.x;
  548. if (other.y > this.y)
  549. this.y = other.y;
  550. if (other.z > this.z)
  551. this.z = other.z;
  552. return this;
  553. };
  554. // Properties
  555. Vector3.prototype.length = function () {
  556. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  557. };
  558. Vector3.prototype.lengthSquared = function () {
  559. return (this.x * this.x + this.y * this.y + this.z * this.z);
  560. };
  561. // Methods
  562. Vector3.prototype.normalize = function () {
  563. var len = this.length();
  564. if (len === 0)
  565. return this;
  566. var num = 1.0 / len;
  567. this.x *= num;
  568. this.y *= num;
  569. this.z *= num;
  570. return this;
  571. };
  572. Vector3.prototype.clone = function () {
  573. return new Vector3(this.x, this.y, this.z);
  574. };
  575. Vector3.prototype.copyFrom = function (source) {
  576. this.x = source.x;
  577. this.y = source.y;
  578. this.z = source.z;
  579. return this;
  580. };
  581. Vector3.prototype.copyFromFloats = function (x, y, z) {
  582. this.x = x;
  583. this.y = y;
  584. this.z = z;
  585. return this;
  586. };
  587. // Statics
  588. Vector3.FromArray = function (array, offset) {
  589. if (!offset) {
  590. offset = 0;
  591. }
  592. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  593. };
  594. Vector3.FromArrayToRef = function (array, offset, result) {
  595. result.x = array[offset];
  596. result.y = array[offset + 1];
  597. result.z = array[offset + 2];
  598. };
  599. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  600. result.x = array[offset];
  601. result.y = array[offset + 1];
  602. result.z = array[offset + 2];
  603. };
  604. Vector3.FromFloatsToRef = function (x, y, z, result) {
  605. result.x = x;
  606. result.y = y;
  607. result.z = z;
  608. };
  609. Vector3.Zero = function () {
  610. return new Vector3(0, 0, 0);
  611. };
  612. Vector3.Up = function () {
  613. return new Vector3(0, 1.0, 0);
  614. };
  615. Vector3.TransformCoordinates = function (vector, transformation) {
  616. var result = Vector3.Zero();
  617. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  618. return result;
  619. };
  620. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  621. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  622. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  623. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  624. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  625. result.x = x / w;
  626. result.y = y / w;
  627. result.z = z / w;
  628. };
  629. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  630. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  631. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  632. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  633. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  634. result.x = rx / rw;
  635. result.y = ry / rw;
  636. result.z = rz / rw;
  637. };
  638. Vector3.TransformNormal = function (vector, transformation) {
  639. var result = Vector3.Zero();
  640. Vector3.TransformNormalToRef(vector, transformation, result);
  641. return result;
  642. };
  643. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  644. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  645. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  646. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  647. };
  648. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  649. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  650. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  651. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  652. };
  653. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  654. var squared = amount * amount;
  655. var cubed = amount * squared;
  656. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) + (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) + ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  657. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) + (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) + ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  658. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) + (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) + ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  659. return new Vector3(x, y, z);
  660. };
  661. Vector3.Clamp = function (value, min, max) {
  662. var x = value.x;
  663. x = (x > max.x) ? max.x : x;
  664. x = (x < min.x) ? min.x : x;
  665. var y = value.y;
  666. y = (y > max.y) ? max.y : y;
  667. y = (y < min.y) ? min.y : y;
  668. var z = value.z;
  669. z = (z > max.z) ? max.z : z;
  670. z = (z < min.z) ? min.z : z;
  671. return new Vector3(x, y, z);
  672. };
  673. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  674. var squared = amount * amount;
  675. var cubed = amount * squared;
  676. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  677. var part2 = (-2.0 * cubed) + (3.0 * squared);
  678. var part3 = (cubed - (2.0 * squared)) + amount;
  679. var part4 = cubed - squared;
  680. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  681. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  682. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  683. return new Vector3(x, y, z);
  684. };
  685. Vector3.Lerp = function (start, end, amount) {
  686. var x = start.x + ((end.x - start.x) * amount);
  687. var y = start.y + ((end.y - start.y) * amount);
  688. var z = start.z + ((end.z - start.z) * amount);
  689. return new Vector3(x, y, z);
  690. };
  691. Vector3.Dot = function (left, right) {
  692. return (left.x * right.x + left.y * right.y + left.z * right.z);
  693. };
  694. Vector3.Cross = function (left, right) {
  695. var result = Vector3.Zero();
  696. Vector3.CrossToRef(left, right, result);
  697. return result;
  698. };
  699. Vector3.CrossToRef = function (left, right, result) {
  700. result.x = left.y * right.z - left.z * right.y;
  701. result.y = left.z * right.x - left.x * right.z;
  702. result.z = left.x * right.y - left.y * right.x;
  703. };
  704. Vector3.Normalize = function (vector) {
  705. var result = Vector3.Zero();
  706. Vector3.NormalizeToRef(vector, result);
  707. return result;
  708. };
  709. Vector3.NormalizeToRef = function (vector, result) {
  710. result.copyFrom(vector);
  711. result.normalize();
  712. };
  713. Vector3.Project = function (vector, world, transform, viewport) {
  714. var cw = viewport.width;
  715. var ch = viewport.height;
  716. var cx = viewport.x;
  717. var cy = viewport.y;
  718. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 1, 0, cx + cw / 2.0, ch / 2.0 + cy, 0, 1);
  719. var finalMatrix = world.multiply(transform).multiply(viewportMatrix);
  720. return Vector3.TransformCoordinates(vector, finalMatrix);
  721. };
  722. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  723. var matrix = world.multiply(transform);
  724. matrix.invert();
  725. source.x = source.x / viewportWidth * 2 - 1;
  726. source.y = -(source.y / viewportHeight * 2 - 1);
  727. var vector = Vector3.TransformCoordinates(source, matrix);
  728. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  729. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  730. vector = vector.scale(1.0 / num);
  731. }
  732. return vector;
  733. };
  734. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  735. var matrix = world.multiply(view).multiply(projection);
  736. matrix.invert();
  737. source.x = source.x / viewportWidth * 2 - 1;
  738. source.y = -(source.y / viewportHeight * 2 - 1);
  739. var vector = Vector3.TransformCoordinates(source, matrix);
  740. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  741. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  742. vector = vector.scale(1.0 / num);
  743. }
  744. return vector;
  745. };
  746. Vector3.Minimize = function (left, right) {
  747. var min = left.clone();
  748. min.MinimizeInPlace(right);
  749. return min;
  750. };
  751. Vector3.Maximize = function (left, right) {
  752. var max = left.clone();
  753. max.MaximizeInPlace(right);
  754. return max;
  755. };
  756. Vector3.Distance = function (value1, value2) {
  757. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  758. };
  759. Vector3.DistanceSquared = function (value1, value2) {
  760. var x = value1.x - value2.x;
  761. var y = value1.y - value2.y;
  762. var z = value1.z - value2.z;
  763. return (x * x) + (y * y) + (z * z);
  764. };
  765. Vector3.Center = function (value1, value2) {
  766. var center = value1.add(value2);
  767. center.scaleInPlace(0.5);
  768. return center;
  769. };
  770. return Vector3;
  771. })();
  772. BABYLON.Vector3 = Vector3;
  773. //Vector4 class created for EulerAngle class conversion to Quaternion
  774. var Vector4 = (function () {
  775. function Vector4(x, y, z, w) {
  776. this.x = x;
  777. this.y = y;
  778. this.z = z;
  779. this.w = w;
  780. }
  781. Vector4.prototype.toString = function () {
  782. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  783. };
  784. // Operators
  785. Vector4.prototype.asArray = function () {
  786. var result = [];
  787. this.toArray(result, 0);
  788. return result;
  789. };
  790. Vector4.prototype.toArray = function (array, index) {
  791. if (index === undefined) {
  792. index = 0;
  793. }
  794. array[index] = this.x;
  795. array[index + 1] = this.y;
  796. array[index + 2] = this.z;
  797. array[index + 3] = this.w;
  798. return this;
  799. };
  800. Vector4.prototype.addInPlace = function (otherVector) {
  801. this.x += otherVector.x;
  802. this.y += otherVector.y;
  803. this.z += otherVector.z;
  804. this.w += otherVector.w;
  805. return this;
  806. };
  807. Vector4.prototype.add = function (otherVector) {
  808. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  809. };
  810. Vector4.prototype.addToRef = function (otherVector, result) {
  811. result.x = this.x + otherVector.x;
  812. result.y = this.y + otherVector.y;
  813. result.z = this.z + otherVector.z;
  814. result.w = this.w + otherVector.w;
  815. return this;
  816. };
  817. Vector4.prototype.subtractInPlace = function (otherVector) {
  818. this.x -= otherVector.x;
  819. this.y -= otherVector.y;
  820. this.z -= otherVector.z;
  821. this.w -= otherVector.w;
  822. return this;
  823. };
  824. Vector4.prototype.subtract = function (otherVector) {
  825. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  826. };
  827. Vector4.prototype.subtractToRef = function (otherVector, result) {
  828. result.x = this.x - otherVector.x;
  829. result.y = this.y - otherVector.y;
  830. result.z = this.z - otherVector.z;
  831. result.w = this.w - otherVector.w;
  832. return this;
  833. };
  834. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  835. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  836. };
  837. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  838. result.x = this.x - x;
  839. result.y = this.y - y;
  840. result.z = this.z - z;
  841. result.w = this.w - w;
  842. return this;
  843. };
  844. Vector4.prototype.negate = function () {
  845. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  846. };
  847. Vector4.prototype.scaleInPlace = function (scale) {
  848. this.x *= scale;
  849. this.y *= scale;
  850. this.z *= scale;
  851. this.w *= scale;
  852. return this;
  853. };
  854. Vector4.prototype.scale = function (scale) {
  855. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  856. };
  857. Vector4.prototype.scaleToRef = function (scale, result) {
  858. result.x = this.x * scale;
  859. result.y = this.y * scale;
  860. result.z = this.z * scale;
  861. result.w = this.w * scale;
  862. };
  863. Vector4.prototype.equals = function (otherVector) {
  864. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  865. };
  866. Vector4.prototype.equalsWithEpsilon = function (otherVector) {
  867. return Math.abs(this.x - otherVector.x) < BABYLON.Engine.Epsilon && Math.abs(this.y - otherVector.y) < BABYLON.Engine.Epsilon && Math.abs(this.z - otherVector.z) < BABYLON.Engine.Epsilon && Math.abs(this.w - otherVector.w) < BABYLON.Engine.Epsilon;
  868. };
  869. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  870. return this.x === x && this.y === y && this.z === z && this.w === w;
  871. };
  872. Vector4.prototype.multiplyInPlace = function (otherVector) {
  873. this.x *= otherVector.x;
  874. this.y *= otherVector.y;
  875. this.z *= otherVector.z;
  876. this.w *= otherVector.w;
  877. return this;
  878. };
  879. Vector4.prototype.multiply = function (otherVector) {
  880. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  881. };
  882. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  883. result.x = this.x * otherVector.x;
  884. result.y = this.y * otherVector.y;
  885. result.z = this.z * otherVector.z;
  886. result.w = this.w * otherVector.w;
  887. return this;
  888. };
  889. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  890. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  891. };
  892. Vector4.prototype.divide = function (otherVector) {
  893. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  894. };
  895. Vector4.prototype.divideToRef = function (otherVector, result) {
  896. result.x = this.x / otherVector.x;
  897. result.y = this.y / otherVector.y;
  898. result.z = this.z / otherVector.z;
  899. result.w = this.w / otherVector.w;
  900. return this;
  901. };
  902. Vector4.prototype.MinimizeInPlace = function (other) {
  903. if (other.x < this.x)
  904. this.x = other.x;
  905. if (other.y < this.y)
  906. this.y = other.y;
  907. if (other.z < this.z)
  908. this.z = other.z;
  909. if (other.w < this.w)
  910. this.w = other.w;
  911. return this;
  912. };
  913. Vector4.prototype.MaximizeInPlace = function (other) {
  914. if (other.x > this.x)
  915. this.x = other.x;
  916. if (other.y > this.y)
  917. this.y = other.y;
  918. if (other.z > this.z)
  919. this.z = other.z;
  920. if (other.w > this.w)
  921. this.w = other.w;
  922. return this;
  923. };
  924. // Properties
  925. Vector4.prototype.length = function () {
  926. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  927. };
  928. Vector4.prototype.lengthSquared = function () {
  929. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  930. };
  931. // Methods
  932. Vector4.prototype.normalize = function () {
  933. var len = this.length();
  934. if (len === 0)
  935. return this;
  936. var num = 1.0 / len;
  937. this.x *= num;
  938. this.y *= num;
  939. this.z *= num;
  940. this.w *= num;
  941. return this;
  942. };
  943. Vector4.prototype.clone = function () {
  944. return new Vector4(this.x, this.y, this.z, this.w);
  945. };
  946. Vector4.prototype.copyFrom = function (source) {
  947. this.x = source.x;
  948. this.y = source.y;
  949. this.z = source.z;
  950. this.w = source.w;
  951. return this;
  952. };
  953. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  954. this.x = x;
  955. this.y = y;
  956. this.z = z;
  957. this.w = w;
  958. return this;
  959. };
  960. // Statics
  961. Vector4.FromArray = function (array, offset) {
  962. if (!offset) {
  963. offset = 0;
  964. }
  965. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  966. };
  967. Vector4.FromArrayToRef = function (array, offset, result) {
  968. result.x = array[offset];
  969. result.y = array[offset + 1];
  970. result.z = array[offset + 2];
  971. result.w = array[offset + 3];
  972. };
  973. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  974. result.x = array[offset];
  975. result.y = array[offset + 1];
  976. result.z = array[offset + 2];
  977. result.w = array[offset + 3];
  978. };
  979. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  980. result.x = x;
  981. result.y = y;
  982. result.z = z;
  983. result.w = w;
  984. };
  985. Vector4.Zero = function () {
  986. return new Vector4(0, 0, 0, 0);
  987. };
  988. Vector4.Normalize = function (vector) {
  989. var result = Vector4.Zero();
  990. Vector4.NormalizeToRef(vector, result);
  991. return result;
  992. };
  993. Vector4.NormalizeToRef = function (vector, result) {
  994. result.copyFrom(vector);
  995. result.normalize();
  996. };
  997. Vector4.Minimize = function (left, right) {
  998. var min = left.clone();
  999. min.MinimizeInPlace(right);
  1000. return min;
  1001. };
  1002. Vector4.Maximize = function (left, right) {
  1003. var max = left.clone();
  1004. max.MaximizeInPlace(right);
  1005. return max;
  1006. };
  1007. Vector4.Distance = function (value1, value2) {
  1008. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  1009. };
  1010. Vector4.DistanceSquared = function (value1, value2) {
  1011. var x = value1.x - value2.x;
  1012. var y = value1.y - value2.y;
  1013. var z = value1.z - value2.z;
  1014. var w = value1.w - value2.w;
  1015. return (x * x) + (y * y) + (z * z) + (w * w);
  1016. };
  1017. Vector4.Center = function (value1, value2) {
  1018. var center = value1.add(value2);
  1019. center.scaleInPlace(0.5);
  1020. return center;
  1021. };
  1022. return Vector4;
  1023. })();
  1024. BABYLON.Vector4 = Vector4;
  1025. var Quaternion = (function () {
  1026. function Quaternion(x, y, z, w) {
  1027. if (x === void 0) { x = 0; }
  1028. if (y === void 0) { y = 0; }
  1029. if (z === void 0) { z = 0; }
  1030. if (w === void 0) { w = 1; }
  1031. this.x = x;
  1032. this.y = y;
  1033. this.z = z;
  1034. this.w = w;
  1035. }
  1036. Quaternion.prototype.toString = function () {
  1037. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1038. };
  1039. Quaternion.prototype.asArray = function () {
  1040. return [this.x, this.y, this.z, this.w];
  1041. };
  1042. Quaternion.prototype.equals = function (otherQuaternion) {
  1043. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1044. };
  1045. Quaternion.prototype.clone = function () {
  1046. return new Quaternion(this.x, this.y, this.z, this.w);
  1047. };
  1048. Quaternion.prototype.copyFrom = function (other) {
  1049. this.x = other.x;
  1050. this.y = other.y;
  1051. this.z = other.z;
  1052. this.w = other.w;
  1053. return this;
  1054. };
  1055. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1056. this.x = x;
  1057. this.y = y;
  1058. this.z = z;
  1059. this.w = w;
  1060. return this;
  1061. };
  1062. Quaternion.prototype.add = function (other) {
  1063. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1064. };
  1065. Quaternion.prototype.subtract = function (other) {
  1066. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1067. };
  1068. Quaternion.prototype.scale = function (value) {
  1069. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1070. };
  1071. Quaternion.prototype.multiply = function (q1) {
  1072. var result = new Quaternion(0, 0, 0, 1.0);
  1073. this.multiplyToRef(q1, result);
  1074. return result;
  1075. };
  1076. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1077. result.x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1078. result.y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1079. result.z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1080. result.w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1081. return this;
  1082. };
  1083. Quaternion.prototype.length = function () {
  1084. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1085. };
  1086. Quaternion.prototype.normalize = function () {
  1087. var length = 1.0 / this.length();
  1088. this.x *= length;
  1089. this.y *= length;
  1090. this.z *= length;
  1091. this.w *= length;
  1092. return this;
  1093. };
  1094. Quaternion.prototype.toEulerAngles = function () {
  1095. var result = Vector3.Zero();
  1096. this.toEulerAnglesToRef(result);
  1097. return result;
  1098. };
  1099. Quaternion.prototype.toEulerAnglesToRef = function (result) {
  1100. //result is an EulerAngles in the in the z-x-z convention
  1101. var qx = this.x;
  1102. var qy = this.y;
  1103. var qz = this.z;
  1104. var qw = this.w;
  1105. var qxy = qx * qy;
  1106. var qxz = qx * qz;
  1107. var qwy = qw * qy;
  1108. var qwz = qw * qz;
  1109. var qwx = qw * qx;
  1110. var qyz = qy * qz;
  1111. var sqx = qx * qx;
  1112. var sqy = qy * qy;
  1113. var determinant = sqx + sqy;
  1114. if (determinant !== 0.000 && determinant !== 1.000) {
  1115. result.x = Math.atan2(qxz + qwy, qwx - qyz);
  1116. result.y = Math.acos(1 - 2 * determinant);
  1117. result.z = Math.atan2(qxz - qwy, qwx + qyz);
  1118. }
  1119. else {
  1120. if (determinant === 0.0) {
  1121. result.x = 0.0;
  1122. result.y = 0.0;
  1123. result.z = Math.atan2(qxy - qwz, 0.5 - sqy - qz * qz); //actually, degeneracy gives us choice with x+z=Math.atan2(qxy-qwz,0.5-sqy-qz*qz)
  1124. }
  1125. else {
  1126. result.x = Math.atan2(qxy - qwz, 0.5 - sqy - qz * qz); //actually, degeneracy gives us choice with x-z=Math.atan2(qxy-qwz,0.5-sqy-qz*qz)
  1127. result.y = Math.PI;
  1128. result.z = 0.0;
  1129. }
  1130. }
  1131. return this;
  1132. };
  1133. Quaternion.prototype.toRotationMatrix = function (result) {
  1134. var xx = this.x * this.x;
  1135. var yy = this.y * this.y;
  1136. var zz = this.z * this.z;
  1137. var xy = this.x * this.y;
  1138. var zw = this.z * this.w;
  1139. var zx = this.z * this.x;
  1140. var yw = this.y * this.w;
  1141. var yz = this.y * this.z;
  1142. var xw = this.x * this.w;
  1143. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1144. result.m[1] = 2.0 * (xy + zw);
  1145. result.m[2] = 2.0 * (zx - yw);
  1146. result.m[3] = 0;
  1147. result.m[4] = 2.0 * (xy - zw);
  1148. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1149. result.m[6] = 2.0 * (yz + xw);
  1150. result.m[7] = 0;
  1151. result.m[8] = 2.0 * (zx + yw);
  1152. result.m[9] = 2.0 * (yz - xw);
  1153. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1154. result.m[11] = 0;
  1155. result.m[12] = 0;
  1156. result.m[13] = 0;
  1157. result.m[14] = 0;
  1158. result.m[15] = 1.0;
  1159. return this;
  1160. };
  1161. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1162. Quaternion.FromRotationMatrixToRef(matrix, this);
  1163. return this;
  1164. };
  1165. // Statics
  1166. Quaternion.FromRotationMatrix = function (matrix) {
  1167. var result = new Quaternion();
  1168. Quaternion.FromRotationMatrixToRef(matrix, result);
  1169. return result;
  1170. };
  1171. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1172. var data = matrix.m;
  1173. var m11 = data[0], m12 = data[4], m13 = data[8];
  1174. var m21 = data[1], m22 = data[5], m23 = data[9];
  1175. var m31 = data[2], m32 = data[6], m33 = data[10];
  1176. var trace = m11 + m22 + m33;
  1177. var s;
  1178. if (trace > 0) {
  1179. s = 0.5 / Math.sqrt(trace + 1.0);
  1180. result.w = 0.25 / s;
  1181. result.x = (m32 - m23) * s;
  1182. result.y = (m13 - m31) * s;
  1183. result.z = (m21 - m12) * s;
  1184. }
  1185. else if (m11 > m22 && m11 > m33) {
  1186. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1187. result.w = (m32 - m23) / s;
  1188. result.x = 0.25 * s;
  1189. result.y = (m12 + m21) / s;
  1190. result.z = (m13 + m31) / s;
  1191. }
  1192. else if (m22 > m33) {
  1193. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1194. result.w = (m13 - m31) / s;
  1195. result.x = (m12 + m21) / s;
  1196. result.y = 0.25 * s;
  1197. result.z = (m23 + m32) / s;
  1198. }
  1199. else {
  1200. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1201. result.w = (m21 - m12) / s;
  1202. result.x = (m13 + m31) / s;
  1203. result.y = (m23 + m32) / s;
  1204. result.z = 0.25 * s;
  1205. }
  1206. };
  1207. Quaternion.Inverse = function (q) {
  1208. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1209. };
  1210. Quaternion.Identity = function () {
  1211. return new Quaternion(0, 0, 0, 1);
  1212. };
  1213. Quaternion.RotationAxis = function (axis, angle) {
  1214. var result = new Quaternion();
  1215. var sin = Math.sin(angle / 2);
  1216. result.w = Math.cos(angle / 2);
  1217. result.x = axis.x * sin;
  1218. result.y = axis.y * sin;
  1219. result.z = axis.z * sin;
  1220. return result;
  1221. };
  1222. Quaternion.FromArray = function (array, offset) {
  1223. if (!offset) {
  1224. offset = 0;
  1225. }
  1226. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1227. };
  1228. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1229. var result = new Quaternion();
  1230. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1231. return result;
  1232. };
  1233. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1234. //produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1235. var halfRoll = roll * 0.5;
  1236. var halfPitch = pitch * 0.5;
  1237. var halfYaw = yaw * 0.5;
  1238. var sinRoll = Math.sin(halfRoll);
  1239. var cosRoll = Math.cos(halfRoll);
  1240. var sinPitch = Math.sin(halfPitch);
  1241. var cosPitch = Math.cos(halfPitch);
  1242. var sinYaw = Math.sin(halfYaw);
  1243. var cosYaw = Math.cos(halfYaw);
  1244. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1245. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1246. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1247. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1248. };
  1249. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1250. var result = new Quaternion();
  1251. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1252. return result;
  1253. };
  1254. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1255. //produces a quaternion from Euler angles in the z-x-z orientation
  1256. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1257. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1258. var halfBeta = beta * 0.5;
  1259. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1260. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1261. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1262. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1263. };
  1264. Quaternion.Slerp = function (left, right, amount) {
  1265. var num2;
  1266. var num3;
  1267. var num = amount;
  1268. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1269. var flag = false;
  1270. if (num4 < 0) {
  1271. flag = true;
  1272. num4 = -num4;
  1273. }
  1274. if (num4 > 0.999999) {
  1275. num3 = 1 - num;
  1276. num2 = flag ? -num : num;
  1277. }
  1278. else {
  1279. var num5 = Math.acos(num4);
  1280. var num6 = (1.0 / Math.sin(num5));
  1281. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1282. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1283. }
  1284. return new Quaternion((num3 * left.x) + (num2 * right.x), (num3 * left.y) + (num2 * right.y), (num3 * left.z) + (num2 * right.z), (num3 * left.w) + (num2 * right.w));
  1285. };
  1286. return Quaternion;
  1287. })();
  1288. BABYLON.Quaternion = Quaternion;
  1289. var Matrix = (function () {
  1290. function Matrix() {
  1291. this.m = new Float32Array(16);
  1292. }
  1293. // Properties
  1294. Matrix.prototype.isIdentity = function () {
  1295. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1296. return false;
  1297. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 || this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 || this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 || this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  1298. return false;
  1299. return true;
  1300. };
  1301. Matrix.prototype.determinant = function () {
  1302. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1303. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1304. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1305. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1306. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1307. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1308. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) - (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) - (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  1309. };
  1310. // Methods
  1311. Matrix.prototype.toArray = function () {
  1312. return this.m;
  1313. };
  1314. Matrix.prototype.asArray = function () {
  1315. return this.toArray();
  1316. };
  1317. Matrix.prototype.invert = function () {
  1318. this.invertToRef(this);
  1319. return this;
  1320. };
  1321. Matrix.prototype.invertToRef = function (other) {
  1322. var l1 = this.m[0];
  1323. var l2 = this.m[1];
  1324. var l3 = this.m[2];
  1325. var l4 = this.m[3];
  1326. var l5 = this.m[4];
  1327. var l6 = this.m[5];
  1328. var l7 = this.m[6];
  1329. var l8 = this.m[7];
  1330. var l9 = this.m[8];
  1331. var l10 = this.m[9];
  1332. var l11 = this.m[10];
  1333. var l12 = this.m[11];
  1334. var l13 = this.m[12];
  1335. var l14 = this.m[13];
  1336. var l15 = this.m[14];
  1337. var l16 = this.m[15];
  1338. var l17 = (l11 * l16) - (l12 * l15);
  1339. var l18 = (l10 * l16) - (l12 * l14);
  1340. var l19 = (l10 * l15) - (l11 * l14);
  1341. var l20 = (l9 * l16) - (l12 * l13);
  1342. var l21 = (l9 * l15) - (l11 * l13);
  1343. var l22 = (l9 * l14) - (l10 * l13);
  1344. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1345. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1346. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1347. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1348. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1349. var l28 = (l7 * l16) - (l8 * l15);
  1350. var l29 = (l6 * l16) - (l8 * l14);
  1351. var l30 = (l6 * l15) - (l7 * l14);
  1352. var l31 = (l5 * l16) - (l8 * l13);
  1353. var l32 = (l5 * l15) - (l7 * l13);
  1354. var l33 = (l5 * l14) - (l6 * l13);
  1355. var l34 = (l7 * l12) - (l8 * l11);
  1356. var l35 = (l6 * l12) - (l8 * l10);
  1357. var l36 = (l6 * l11) - (l7 * l10);
  1358. var l37 = (l5 * l12) - (l8 * l9);
  1359. var l38 = (l5 * l11) - (l7 * l9);
  1360. var l39 = (l5 * l10) - (l6 * l9);
  1361. other.m[0] = l23 * l27;
  1362. other.m[4] = l24 * l27;
  1363. other.m[8] = l25 * l27;
  1364. other.m[12] = l26 * l27;
  1365. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1366. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1367. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1368. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1369. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1370. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1371. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1372. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1373. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1374. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1375. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1376. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1377. return this;
  1378. };
  1379. Matrix.prototype.setTranslation = function (vector3) {
  1380. this.m[12] = vector3.x;
  1381. this.m[13] = vector3.y;
  1382. this.m[14] = vector3.z;
  1383. return this;
  1384. };
  1385. Matrix.prototype.multiply = function (other) {
  1386. var result = new Matrix();
  1387. this.multiplyToRef(other, result);
  1388. return result;
  1389. };
  1390. Matrix.prototype.copyFrom = function (other) {
  1391. for (var index = 0; index < 16; index++) {
  1392. this.m[index] = other.m[index];
  1393. }
  1394. return this;
  1395. };
  1396. Matrix.prototype.copyToArray = function (array, offset) {
  1397. if (offset === void 0) { offset = 0; }
  1398. for (var index = 0; index < 16; index++) {
  1399. array[offset + index] = this.m[index];
  1400. }
  1401. return this;
  1402. };
  1403. Matrix.prototype.multiplyToRef = function (other, result) {
  1404. this.multiplyToArray(other, result.m, 0);
  1405. return this;
  1406. };
  1407. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1408. var tm0 = this.m[0];
  1409. var tm1 = this.m[1];
  1410. var tm2 = this.m[2];
  1411. var tm3 = this.m[3];
  1412. var tm4 = this.m[4];
  1413. var tm5 = this.m[5];
  1414. var tm6 = this.m[6];
  1415. var tm7 = this.m[7];
  1416. var tm8 = this.m[8];
  1417. var tm9 = this.m[9];
  1418. var tm10 = this.m[10];
  1419. var tm11 = this.m[11];
  1420. var tm12 = this.m[12];
  1421. var tm13 = this.m[13];
  1422. var tm14 = this.m[14];
  1423. var tm15 = this.m[15];
  1424. var om0 = other.m[0];
  1425. var om1 = other.m[1];
  1426. var om2 = other.m[2];
  1427. var om3 = other.m[3];
  1428. var om4 = other.m[4];
  1429. var om5 = other.m[5];
  1430. var om6 = other.m[6];
  1431. var om7 = other.m[7];
  1432. var om8 = other.m[8];
  1433. var om9 = other.m[9];
  1434. var om10 = other.m[10];
  1435. var om11 = other.m[11];
  1436. var om12 = other.m[12];
  1437. var om13 = other.m[13];
  1438. var om14 = other.m[14];
  1439. var om15 = other.m[15];
  1440. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1441. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1442. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1443. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1444. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1445. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1446. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1447. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1448. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1449. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1450. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1451. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1452. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1453. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1454. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1455. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1456. return this;
  1457. };
  1458. Matrix.prototype.equals = function (value) {
  1459. return value && (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] && this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] && this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] && this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1460. };
  1461. Matrix.prototype.clone = function () {
  1462. 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]);
  1463. };
  1464. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1465. translation.x = this.m[12];
  1466. translation.y = this.m[13];
  1467. translation.z = this.m[14];
  1468. var xs = BABYLON.Tools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1469. var ys = BABYLON.Tools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1470. var zs = BABYLON.Tools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1471. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1472. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1473. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1474. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1475. rotation.x = 0;
  1476. rotation.y = 0;
  1477. rotation.z = 0;
  1478. rotation.w = 1;
  1479. return false;
  1480. }
  1481. var rotationMatrix = Matrix.FromValues(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);
  1482. Quaternion.FromRotationMatrixToRef(rotationMatrix, rotation);
  1483. return true;
  1484. };
  1485. // Statics
  1486. Matrix.FromArray = function (array, offset) {
  1487. var result = new Matrix();
  1488. if (!offset) {
  1489. offset = 0;
  1490. }
  1491. Matrix.FromArrayToRef(array, offset, result);
  1492. return result;
  1493. };
  1494. Matrix.FromArrayToRef = function (array, offset, result) {
  1495. for (var index = 0; index < 16; index++) {
  1496. result.m[index] = array[index + offset];
  1497. }
  1498. };
  1499. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1500. result.m[0] = initialM11;
  1501. result.m[1] = initialM12;
  1502. result.m[2] = initialM13;
  1503. result.m[3] = initialM14;
  1504. result.m[4] = initialM21;
  1505. result.m[5] = initialM22;
  1506. result.m[6] = initialM23;
  1507. result.m[7] = initialM24;
  1508. result.m[8] = initialM31;
  1509. result.m[9] = initialM32;
  1510. result.m[10] = initialM33;
  1511. result.m[11] = initialM34;
  1512. result.m[12] = initialM41;
  1513. result.m[13] = initialM42;
  1514. result.m[14] = initialM43;
  1515. result.m[15] = initialM44;
  1516. };
  1517. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1518. var result = new Matrix();
  1519. result.m[0] = initialM11;
  1520. result.m[1] = initialM12;
  1521. result.m[2] = initialM13;
  1522. result.m[3] = initialM14;
  1523. result.m[4] = initialM21;
  1524. result.m[5] = initialM22;
  1525. result.m[6] = initialM23;
  1526. result.m[7] = initialM24;
  1527. result.m[8] = initialM31;
  1528. result.m[9] = initialM32;
  1529. result.m[10] = initialM33;
  1530. result.m[11] = initialM34;
  1531. result.m[12] = initialM41;
  1532. result.m[13] = initialM42;
  1533. result.m[14] = initialM43;
  1534. result.m[15] = initialM44;
  1535. return result;
  1536. };
  1537. Matrix.Compose = function (scale, rotation, translation) {
  1538. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  1539. var rotationMatrix = Matrix.Identity();
  1540. rotation.toRotationMatrix(rotationMatrix);
  1541. result = result.multiply(rotationMatrix);
  1542. result.setTranslation(translation);
  1543. return result;
  1544. };
  1545. Matrix.Identity = function () {
  1546. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1547. };
  1548. Matrix.IdentityToRef = function (result) {
  1549. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1550. };
  1551. Matrix.Zero = function () {
  1552. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1553. };
  1554. Matrix.RotationX = function (angle) {
  1555. var result = new Matrix();
  1556. Matrix.RotationXToRef(angle, result);
  1557. return result;
  1558. };
  1559. Matrix.Invert = function (source) {
  1560. var result = new Matrix();
  1561. source.invertToRef(result);
  1562. return result;
  1563. };
  1564. Matrix.RotationXToRef = function (angle, result) {
  1565. var s = Math.sin(angle);
  1566. var c = Math.cos(angle);
  1567. result.m[0] = 1.0;
  1568. result.m[15] = 1.0;
  1569. result.m[5] = c;
  1570. result.m[10] = c;
  1571. result.m[9] = -s;
  1572. result.m[6] = s;
  1573. result.m[1] = 0;
  1574. result.m[2] = 0;
  1575. result.m[3] = 0;
  1576. result.m[4] = 0;
  1577. result.m[7] = 0;
  1578. result.m[8] = 0;
  1579. result.m[11] = 0;
  1580. result.m[12] = 0;
  1581. result.m[13] = 0;
  1582. result.m[14] = 0;
  1583. };
  1584. Matrix.RotationY = function (angle) {
  1585. var result = new Matrix();
  1586. Matrix.RotationYToRef(angle, result);
  1587. return result;
  1588. };
  1589. Matrix.RotationYToRef = function (angle, result) {
  1590. var s = Math.sin(angle);
  1591. var c = Math.cos(angle);
  1592. result.m[5] = 1.0;
  1593. result.m[15] = 1.0;
  1594. result.m[0] = c;
  1595. result.m[2] = -s;
  1596. result.m[8] = s;
  1597. result.m[10] = c;
  1598. result.m[1] = 0;
  1599. result.m[3] = 0;
  1600. result.m[4] = 0;
  1601. result.m[6] = 0;
  1602. result.m[7] = 0;
  1603. result.m[9] = 0;
  1604. result.m[11] = 0;
  1605. result.m[12] = 0;
  1606. result.m[13] = 0;
  1607. result.m[14] = 0;
  1608. };
  1609. Matrix.RotationZ = function (angle) {
  1610. var result = new Matrix();
  1611. Matrix.RotationZToRef(angle, result);
  1612. return result;
  1613. };
  1614. Matrix.RotationZToRef = function (angle, result) {
  1615. var s = Math.sin(angle);
  1616. var c = Math.cos(angle);
  1617. result.m[10] = 1.0;
  1618. result.m[15] = 1.0;
  1619. result.m[0] = c;
  1620. result.m[1] = s;
  1621. result.m[4] = -s;
  1622. result.m[5] = c;
  1623. result.m[2] = 0;
  1624. result.m[3] = 0;
  1625. result.m[6] = 0;
  1626. result.m[7] = 0;
  1627. result.m[8] = 0;
  1628. result.m[9] = 0;
  1629. result.m[11] = 0;
  1630. result.m[12] = 0;
  1631. result.m[13] = 0;
  1632. result.m[14] = 0;
  1633. };
  1634. Matrix.RotationAxis = function (axis, angle) {
  1635. var s = Math.sin(-angle);
  1636. var c = Math.cos(-angle);
  1637. var c1 = 1 - c;
  1638. axis.normalize();
  1639. var result = Matrix.Zero();
  1640. result.m[0] = (axis.x * axis.x) * c1 + c;
  1641. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1642. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1643. result.m[3] = 0.0;
  1644. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1645. result.m[5] = (axis.y * axis.y) * c1 + c;
  1646. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  1647. result.m[7] = 0.0;
  1648. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  1649. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  1650. result.m[10] = (axis.z * axis.z) * c1 + c;
  1651. result.m[11] = 0.0;
  1652. result.m[15] = 1.0;
  1653. return result;
  1654. };
  1655. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1656. var result = new Matrix();
  1657. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1658. return result;
  1659. };
  1660. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1661. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  1662. this._tempQuaternion.toRotationMatrix(result);
  1663. };
  1664. Matrix.Scaling = function (x, y, z) {
  1665. var result = Matrix.Zero();
  1666. Matrix.ScalingToRef(x, y, z, result);
  1667. return result;
  1668. };
  1669. Matrix.ScalingToRef = function (x, y, z, result) {
  1670. result.m[0] = x;
  1671. result.m[1] = 0;
  1672. result.m[2] = 0;
  1673. result.m[3] = 0;
  1674. result.m[4] = 0;
  1675. result.m[5] = y;
  1676. result.m[6] = 0;
  1677. result.m[7] = 0;
  1678. result.m[8] = 0;
  1679. result.m[9] = 0;
  1680. result.m[10] = z;
  1681. result.m[11] = 0;
  1682. result.m[12] = 0;
  1683. result.m[13] = 0;
  1684. result.m[14] = 0;
  1685. result.m[15] = 1.0;
  1686. };
  1687. Matrix.Translation = function (x, y, z) {
  1688. var result = Matrix.Identity();
  1689. Matrix.TranslationToRef(x, y, z, result);
  1690. return result;
  1691. };
  1692. Matrix.TranslationToRef = function (x, y, z, result) {
  1693. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  1694. };
  1695. Matrix.LookAtLH = function (eye, target, up) {
  1696. var result = Matrix.Zero();
  1697. Matrix.LookAtLHToRef(eye, target, up, result);
  1698. return result;
  1699. };
  1700. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  1701. // Z axis
  1702. target.subtractToRef(eye, this._zAxis);
  1703. this._zAxis.normalize();
  1704. // X axis
  1705. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  1706. this._xAxis.normalize();
  1707. // Y axis
  1708. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  1709. this._yAxis.normalize();
  1710. // Eye angles
  1711. var ex = -Vector3.Dot(this._xAxis, eye);
  1712. var ey = -Vector3.Dot(this._yAxis, eye);
  1713. var ez = -Vector3.Dot(this._zAxis, eye);
  1714. 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);
  1715. };
  1716. Matrix.OrthoLH = function (width, height, znear, zfar) {
  1717. var hw = 2.0 / width;
  1718. var hh = 2.0 / height;
  1719. var id = 1.0 / (zfar - znear);
  1720. var nid = znear / (znear - zfar);
  1721. return Matrix.FromValues(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1);
  1722. };
  1723. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  1724. var matrix = Matrix.Zero();
  1725. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  1726. return matrix;
  1727. };
  1728. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  1729. result.m[0] = 2.0 / (right - left);
  1730. result.m[1] = result.m[2] = result.m[3] = 0;
  1731. result.m[5] = 2.0 / (top - bottom);
  1732. result.m[4] = result.m[6] = result.m[7] = 0;
  1733. result.m[10] = -1.0 / (znear - zfar);
  1734. result.m[8] = result.m[9] = result.m[11] = 0;
  1735. result.m[12] = (left + right) / (left - right);
  1736. result.m[13] = (top + bottom) / (bottom - top);
  1737. result.m[14] = znear / (znear - zfar);
  1738. result.m[15] = 1.0;
  1739. };
  1740. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  1741. var matrix = Matrix.Zero();
  1742. matrix.m[0] = (2.0 * znear) / width;
  1743. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  1744. matrix.m[5] = (2.0 * znear) / height;
  1745. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  1746. matrix.m[10] = -zfar / (znear - zfar);
  1747. matrix.m[8] = matrix.m[9] = 0.0;
  1748. matrix.m[11] = 1.0;
  1749. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  1750. matrix.m[14] = (znear * zfar) / (znear - zfar);
  1751. return matrix;
  1752. };
  1753. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  1754. var matrix = Matrix.Zero();
  1755. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  1756. return matrix;
  1757. };
  1758. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, fovMode) {
  1759. if (fovMode === void 0) { fovMode = BABYLON.Camera.FOVMODE_VERTICAL_FIXED; }
  1760. var tan = 1.0 / (Math.tan(fov * 0.5));
  1761. var v_fixed = (fovMode === BABYLON.Camera.FOVMODE_VERTICAL_FIXED);
  1762. if (v_fixed) {
  1763. result.m[0] = tan / aspect;
  1764. }
  1765. else {
  1766. result.m[0] = tan;
  1767. }
  1768. result.m[1] = result.m[2] = result.m[3] = 0.0;
  1769. if (v_fixed) {
  1770. result.m[5] = tan;
  1771. }
  1772. else {
  1773. result.m[5] = tan * aspect;
  1774. }
  1775. result.m[4] = result.m[6] = result.m[7] = 0.0;
  1776. result.m[8] = result.m[9] = 0.0;
  1777. result.m[10] = -zfar / (znear - zfar);
  1778. result.m[11] = 1.0;
  1779. result.m[12] = result.m[13] = result.m[15] = 0.0;
  1780. result.m[14] = (znear * zfar) / (znear - zfar);
  1781. };
  1782. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  1783. var cw = viewport.width;
  1784. var ch = viewport.height;
  1785. var cx = viewport.x;
  1786. var cy = viewport.y;
  1787. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, zmax - zmin, 0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);
  1788. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  1789. };
  1790. Matrix.Transpose = function (matrix) {
  1791. var result = new Matrix();
  1792. result.m[0] = matrix.m[0];
  1793. result.m[1] = matrix.m[4];
  1794. result.m[2] = matrix.m[8];
  1795. result.m[3] = matrix.m[12];
  1796. result.m[4] = matrix.m[1];
  1797. result.m[5] = matrix.m[5];
  1798. result.m[6] = matrix.m[9];
  1799. result.m[7] = matrix.m[13];
  1800. result.m[8] = matrix.m[2];
  1801. result.m[9] = matrix.m[6];
  1802. result.m[10] = matrix.m[10];
  1803. result.m[11] = matrix.m[14];
  1804. result.m[12] = matrix.m[3];
  1805. result.m[13] = matrix.m[7];
  1806. result.m[14] = matrix.m[11];
  1807. result.m[15] = matrix.m[15];
  1808. return result;
  1809. };
  1810. Matrix.Reflection = function (plane) {
  1811. var matrix = new Matrix();
  1812. Matrix.ReflectionToRef(plane, matrix);
  1813. return matrix;
  1814. };
  1815. Matrix.ReflectionToRef = function (plane, result) {
  1816. plane.normalize();
  1817. var x = plane.normal.x;
  1818. var y = plane.normal.y;
  1819. var z = plane.normal.z;
  1820. var temp = -2 * x;
  1821. var temp2 = -2 * y;
  1822. var temp3 = -2 * z;
  1823. result.m[0] = (temp * x) + 1;
  1824. result.m[1] = temp2 * x;
  1825. result.m[2] = temp3 * x;
  1826. result.m[3] = 0.0;
  1827. result.m[4] = temp * y;
  1828. result.m[5] = (temp2 * y) + 1;
  1829. result.m[6] = temp3 * y;
  1830. result.m[7] = 0.0;
  1831. result.m[8] = temp * z;
  1832. result.m[9] = temp2 * z;
  1833. result.m[10] = (temp3 * z) + 1;
  1834. result.m[11] = 0.0;
  1835. result.m[12] = temp * plane.d;
  1836. result.m[13] = temp2 * plane.d;
  1837. result.m[14] = temp3 * plane.d;
  1838. result.m[15] = 1.0;
  1839. };
  1840. Matrix._tempQuaternion = new Quaternion();
  1841. Matrix._xAxis = Vector3.Zero();
  1842. Matrix._yAxis = Vector3.Zero();
  1843. Matrix._zAxis = Vector3.Zero();
  1844. return Matrix;
  1845. })();
  1846. BABYLON.Matrix = Matrix;
  1847. var Plane = (function () {
  1848. function Plane(a, b, c, d) {
  1849. this.normal = new Vector3(a, b, c);
  1850. this.d = d;
  1851. }
  1852. Plane.prototype.asArray = function () {
  1853. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  1854. };
  1855. // Methods
  1856. Plane.prototype.clone = function () {
  1857. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  1858. };
  1859. Plane.prototype.normalize = function () {
  1860. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  1861. var magnitude = 0;
  1862. if (norm !== 0) {
  1863. magnitude = 1.0 / norm;
  1864. }
  1865. this.normal.x *= magnitude;
  1866. this.normal.y *= magnitude;
  1867. this.normal.z *= magnitude;
  1868. this.d *= magnitude;
  1869. return this;
  1870. };
  1871. Plane.prototype.transform = function (transformation) {
  1872. var transposedMatrix = Matrix.Transpose(transformation);
  1873. var x = this.normal.x;
  1874. var y = this.normal.y;
  1875. var z = this.normal.z;
  1876. var d = this.d;
  1877. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  1878. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  1879. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  1880. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  1881. return new Plane(normalX, normalY, normalZ, finalD);
  1882. };
  1883. Plane.prototype.dotCoordinate = function (point) {
  1884. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  1885. };
  1886. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  1887. var x1 = point2.x - point1.x;
  1888. var y1 = point2.y - point1.y;
  1889. var z1 = point2.z - point1.z;
  1890. var x2 = point3.x - point1.x;
  1891. var y2 = point3.y - point1.y;
  1892. var z2 = point3.z - point1.z;
  1893. var yz = (y1 * z2) - (z1 * y2);
  1894. var xz = (z1 * x2) - (x1 * z2);
  1895. var xy = (x1 * y2) - (y1 * x2);
  1896. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  1897. var invPyth;
  1898. if (pyth !== 0) {
  1899. invPyth = 1.0 / pyth;
  1900. }
  1901. else {
  1902. invPyth = 0;
  1903. }
  1904. this.normal.x = yz * invPyth;
  1905. this.normal.y = xz * invPyth;
  1906. this.normal.z = xy * invPyth;
  1907. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  1908. return this;
  1909. };
  1910. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  1911. var dot = Vector3.Dot(this.normal, direction);
  1912. return (dot <= epsilon);
  1913. };
  1914. Plane.prototype.signedDistanceTo = function (point) {
  1915. return Vector3.Dot(point, this.normal) + this.d;
  1916. };
  1917. // Statics
  1918. Plane.FromArray = function (array) {
  1919. return new Plane(array[0], array[1], array[2], array[3]);
  1920. };
  1921. Plane.FromPoints = function (point1, point2, point3) {
  1922. var result = new Plane(0, 0, 0, 0);
  1923. result.copyFromPoints(point1, point2, point3);
  1924. return result;
  1925. };
  1926. Plane.FromPositionAndNormal = function (origin, normal) {
  1927. var result = new Plane(0, 0, 0, 0);
  1928. normal.normalize();
  1929. result.normal = normal;
  1930. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  1931. return result;
  1932. };
  1933. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  1934. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  1935. return Vector3.Dot(point, normal) + d;
  1936. };
  1937. return Plane;
  1938. })();
  1939. BABYLON.Plane = Plane;
  1940. var Viewport = (function () {
  1941. function Viewport(x, y, width, height) {
  1942. this.x = x;
  1943. this.y = y;
  1944. this.width = width;
  1945. this.height = height;
  1946. }
  1947. Viewport.prototype.toGlobal = function (engine) {
  1948. var width = engine.getRenderWidth();
  1949. var height = engine.getRenderHeight();
  1950. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  1951. };
  1952. return Viewport;
  1953. })();
  1954. BABYLON.Viewport = Viewport;
  1955. var Frustum = (function () {
  1956. function Frustum() {
  1957. }
  1958. Frustum.GetPlanes = function (transform) {
  1959. var frustumPlanes = [];
  1960. for (var index = 0; index < 6; index++) {
  1961. frustumPlanes.push(new Plane(0, 0, 0, 0));
  1962. }
  1963. Frustum.GetPlanesToRef(transform, frustumPlanes);
  1964. return frustumPlanes;
  1965. };
  1966. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  1967. // Near
  1968. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  1969. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  1970. frustumPlanes[0].normal.z = transform.m[10] + transform.m[10];
  1971. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  1972. frustumPlanes[0].normalize();
  1973. // Far
  1974. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  1975. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  1976. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  1977. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  1978. frustumPlanes[1].normalize();
  1979. // Left
  1980. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  1981. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  1982. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  1983. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  1984. frustumPlanes[2].normalize();
  1985. // Right
  1986. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  1987. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  1988. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  1989. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  1990. frustumPlanes[3].normalize();
  1991. // Top
  1992. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  1993. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  1994. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  1995. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  1996. frustumPlanes[4].normalize();
  1997. // Bottom
  1998. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  1999. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2000. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2001. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2002. frustumPlanes[5].normalize();
  2003. };
  2004. return Frustum;
  2005. })();
  2006. BABYLON.Frustum = Frustum;
  2007. var Ray = (function () {
  2008. function Ray(origin, direction, length) {
  2009. if (length === void 0) { length = Number.MAX_VALUE; }
  2010. this.origin = origin;
  2011. this.direction = direction;
  2012. this.length = length;
  2013. }
  2014. // Methods
  2015. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  2016. var d = 0.0;
  2017. var maxValue = Number.MAX_VALUE;
  2018. if (Math.abs(this.direction.x) < 0.0000001) {
  2019. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  2020. return false;
  2021. }
  2022. }
  2023. else {
  2024. var inv = 1.0 / this.direction.x;
  2025. var min = (minimum.x - this.origin.x) * inv;
  2026. var max = (maximum.x - this.origin.x) * inv;
  2027. if (max === -Infinity) {
  2028. max = Infinity;
  2029. }
  2030. if (min > max) {
  2031. var temp = min;
  2032. min = max;
  2033. max = temp;
  2034. }
  2035. d = Math.max(min, d);
  2036. maxValue = Math.min(max, maxValue);
  2037. if (d > maxValue) {
  2038. return false;
  2039. }
  2040. }
  2041. if (Math.abs(this.direction.y) < 0.0000001) {
  2042. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  2043. return false;
  2044. }
  2045. }
  2046. else {
  2047. inv = 1.0 / this.direction.y;
  2048. min = (minimum.y - this.origin.y) * inv;
  2049. max = (maximum.y - this.origin.y) * inv;
  2050. if (max === -Infinity) {
  2051. max = Infinity;
  2052. }
  2053. if (min > max) {
  2054. temp = min;
  2055. min = max;
  2056. max = temp;
  2057. }
  2058. d = Math.max(min, d);
  2059. maxValue = Math.min(max, maxValue);
  2060. if (d > maxValue) {
  2061. return false;
  2062. }
  2063. }
  2064. if (Math.abs(this.direction.z) < 0.0000001) {
  2065. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  2066. return false;
  2067. }
  2068. }
  2069. else {
  2070. inv = 1.0 / this.direction.z;
  2071. min = (minimum.z - this.origin.z) * inv;
  2072. max = (maximum.z - this.origin.z) * inv;
  2073. if (max === -Infinity) {
  2074. max = Infinity;
  2075. }
  2076. if (min > max) {
  2077. temp = min;
  2078. min = max;
  2079. max = temp;
  2080. }
  2081. d = Math.max(min, d);
  2082. maxValue = Math.min(max, maxValue);
  2083. if (d > maxValue) {
  2084. return false;
  2085. }
  2086. }
  2087. return true;
  2088. };
  2089. Ray.prototype.intersectsBox = function (box) {
  2090. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  2091. };
  2092. Ray.prototype.intersectsSphere = function (sphere) {
  2093. var x = sphere.center.x - this.origin.x;
  2094. var y = sphere.center.y - this.origin.y;
  2095. var z = sphere.center.z - this.origin.z;
  2096. var pyth = (x * x) + (y * y) + (z * z);
  2097. var rr = sphere.radius * sphere.radius;
  2098. if (pyth <= rr) {
  2099. return true;
  2100. }
  2101. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  2102. if (dot < 0.0) {
  2103. return false;
  2104. }
  2105. var temp = pyth - (dot * dot);
  2106. return temp <= rr;
  2107. };
  2108. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  2109. if (!this._edge1) {
  2110. this._edge1 = Vector3.Zero();
  2111. this._edge2 = Vector3.Zero();
  2112. this._pvec = Vector3.Zero();
  2113. this._tvec = Vector3.Zero();
  2114. this._qvec = Vector3.Zero();
  2115. }
  2116. vertex1.subtractToRef(vertex0, this._edge1);
  2117. vertex2.subtractToRef(vertex0, this._edge2);
  2118. Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  2119. var det = Vector3.Dot(this._edge1, this._pvec);
  2120. if (det === 0) {
  2121. return null;
  2122. }
  2123. var invdet = 1 / det;
  2124. this.origin.subtractToRef(vertex0, this._tvec);
  2125. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  2126. if (bu < 0 || bu > 1.0) {
  2127. return null;
  2128. }
  2129. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  2130. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  2131. if (bv < 0 || bu + bv > 1.0) {
  2132. return null;
  2133. }
  2134. //check if the distance is longer than the predefined length.
  2135. var distance = Vector3.Dot(this._edge2, this._qvec) * invdet;
  2136. if (distance > this.length) {
  2137. return null;
  2138. }
  2139. return new BABYLON.IntersectionInfo(bu, bv, distance);
  2140. };
  2141. // Statics
  2142. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  2143. var start = Vector3.Unproject(new Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  2144. var end = Vector3.Unproject(new Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  2145. var direction = end.subtract(start);
  2146. direction.normalize();
  2147. return new Ray(start, direction);
  2148. };
  2149. /**
  2150. * Function will create a new transformed ray starting from origin and ending at the end point. Ray's length will be set, and ray will be
  2151. * transformed to the given world matrix.
  2152. * @param origin The origin point
  2153. * @param end The end point
  2154. * @param world a matrix to transform the ray to. Default is the identity matrix.
  2155. */
  2156. Ray.CreateNewFromTo = function (origin, end, world) {
  2157. if (world === void 0) { world = Matrix.Identity(); }
  2158. var direction = end.subtract(origin);
  2159. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  2160. direction.normalize();
  2161. return Ray.Transform(new Ray(origin, direction, length), world);
  2162. };
  2163. Ray.Transform = function (ray, matrix) {
  2164. var newOrigin = Vector3.TransformCoordinates(ray.origin, matrix);
  2165. var newDirection = Vector3.TransformNormal(ray.direction, matrix);
  2166. return new Ray(newOrigin, newDirection, ray.length);
  2167. };
  2168. return Ray;
  2169. })();
  2170. BABYLON.Ray = Ray;
  2171. (function (Space) {
  2172. Space[Space["LOCAL"] = 0] = "LOCAL";
  2173. Space[Space["WORLD"] = 1] = "WORLD";
  2174. })(BABYLON.Space || (BABYLON.Space = {}));
  2175. var Space = BABYLON.Space;
  2176. var Axis = (function () {
  2177. function Axis() {
  2178. }
  2179. Axis.X = new Vector3(1, 0, 0);
  2180. Axis.Y = new Vector3(0, 1, 0);
  2181. Axis.Z = new Vector3(0, 0, 1);
  2182. return Axis;
  2183. })();
  2184. BABYLON.Axis = Axis;
  2185. ;
  2186. var BezierCurve = (function () {
  2187. function BezierCurve() {
  2188. }
  2189. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2190. // Extract X (which is equal to time here)
  2191. var f0 = 1 - 3 * x2 + 3 * x1;
  2192. var f1 = 3 * x2 - 6 * x1;
  2193. var f2 = 3 * x1;
  2194. var refinedT = t;
  2195. for (var i = 0; i < 5; i++) {
  2196. var refinedT2 = refinedT * refinedT;
  2197. var refinedT3 = refinedT2 * refinedT;
  2198. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2199. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2200. refinedT -= (x - t) * slope;
  2201. refinedT = Math.min(1, Math.max(0, refinedT));
  2202. }
  2203. // Resolve cubic bezier for the given x
  2204. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 + 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 + Math.pow(refinedT, 3);
  2205. };
  2206. return BezierCurve;
  2207. })();
  2208. BABYLON.BezierCurve = BezierCurve;
  2209. (function (Orientation) {
  2210. Orientation[Orientation["CW"] = 0] = "CW";
  2211. Orientation[Orientation["CCW"] = 1] = "CCW";
  2212. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2213. var Orientation = BABYLON.Orientation;
  2214. var Angle = (function () {
  2215. function Angle(radians) {
  2216. var _this = this;
  2217. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2218. this.radians = function () { return _this._radians; };
  2219. this._radians = radians;
  2220. if (this._radians < 0)
  2221. this._radians += (2 * Math.PI);
  2222. }
  2223. Angle.BetweenTwoPoints = function (a, b) {
  2224. var delta = b.subtract(a);
  2225. var theta = Math.atan2(delta.y, delta.x);
  2226. return new Angle(theta);
  2227. };
  2228. Angle.FromRadians = function (radians) {
  2229. return new Angle(radians);
  2230. };
  2231. Angle.FromDegrees = function (degrees) {
  2232. return new Angle(degrees * Math.PI / 180);
  2233. };
  2234. return Angle;
  2235. })();
  2236. BABYLON.Angle = Angle;
  2237. var Arc2 = (function () {
  2238. function Arc2(startPoint, midPoint, endPoint) {
  2239. this.startPoint = startPoint;
  2240. this.midPoint = midPoint;
  2241. this.endPoint = endPoint;
  2242. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2243. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2244. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2245. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2246. 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);
  2247. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2248. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2249. var a1 = this.startAngle.degrees();
  2250. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2251. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2252. // angles correction
  2253. if (a2 - a1 > +180.0)
  2254. a2 -= 360.0;
  2255. if (a2 - a1 < -180.0)
  2256. a2 += 360.0;
  2257. if (a3 - a2 > +180.0)
  2258. a3 -= 360.0;
  2259. if (a3 - a2 < -180.0)
  2260. a3 += 360.0;
  2261. this.orientation = (a2 - a1) < 0 ? 0 /* CW */ : 1 /* CCW */;
  2262. this.angle = Angle.FromDegrees(this.orientation === 0 /* CW */ ? a1 - a3 : a3 - a1);
  2263. }
  2264. return Arc2;
  2265. })();
  2266. BABYLON.Arc2 = Arc2;
  2267. var PathCursor = (function () {
  2268. function PathCursor(path) {
  2269. this.path = path;
  2270. this._onchange = new Array();
  2271. this.value = 0;
  2272. this.animations = new Array();
  2273. }
  2274. PathCursor.prototype.getPoint = function () {
  2275. var point = this.path.getPointAtLengthPosition(this.value);
  2276. return new Vector3(point.x, 0, point.y);
  2277. };
  2278. PathCursor.prototype.moveAhead = function (step) {
  2279. if (step === void 0) { step = 0.002; }
  2280. this.move(step);
  2281. return this;
  2282. };
  2283. PathCursor.prototype.moveBack = function (step) {
  2284. if (step === void 0) { step = 0.002; }
  2285. this.move(-step);
  2286. return this;
  2287. };
  2288. PathCursor.prototype.move = function (step) {
  2289. if (Math.abs(step) > 1) {
  2290. throw "step size should be less than 1.";
  2291. }
  2292. this.value += step;
  2293. this.ensureLimits();
  2294. this.raiseOnChange();
  2295. return this;
  2296. };
  2297. PathCursor.prototype.ensureLimits = function () {
  2298. while (this.value > 1) {
  2299. this.value -= 1;
  2300. }
  2301. while (this.value < 0) {
  2302. this.value += 1;
  2303. }
  2304. return this;
  2305. };
  2306. // used by animation engine
  2307. PathCursor.prototype.markAsDirty = function (propertyName) {
  2308. this.ensureLimits();
  2309. this.raiseOnChange();
  2310. return this;
  2311. };
  2312. PathCursor.prototype.raiseOnChange = function () {
  2313. var _this = this;
  2314. this._onchange.forEach(function (f) { return f(_this); });
  2315. return this;
  2316. };
  2317. PathCursor.prototype.onchange = function (f) {
  2318. this._onchange.push(f);
  2319. return this;
  2320. };
  2321. return PathCursor;
  2322. })();
  2323. BABYLON.PathCursor = PathCursor;
  2324. var Path2 = (function () {
  2325. function Path2(x, y) {
  2326. this._points = [];
  2327. this._length = 0;
  2328. this.closed = false;
  2329. this._points.push(new Vector2(x, y));
  2330. }
  2331. Path2.prototype.addLineTo = function (x, y) {
  2332. if (closed) {
  2333. BABYLON.Tools.Error("cannot add lines to closed paths");
  2334. return this;
  2335. }
  2336. var newPoint = new Vector2(x, y);
  2337. var previousPoint = this._points[this._points.length - 1];
  2338. this._points.push(newPoint);
  2339. this._length += newPoint.subtract(previousPoint).length();
  2340. return this;
  2341. };
  2342. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2343. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2344. if (closed) {
  2345. BABYLON.Tools.Error("cannot add arcs to closed paths");
  2346. return this;
  2347. }
  2348. var startPoint = this._points[this._points.length - 1];
  2349. var midPoint = new Vector2(midX, midY);
  2350. var endPoint = new Vector2(endX, endY);
  2351. var arc = new Arc2(startPoint, midPoint, endPoint);
  2352. var increment = arc.angle.radians() / numberOfSegments;
  2353. if (arc.orientation === 0 /* CW */)
  2354. increment *= -1;
  2355. var currentAngle = arc.startAngle.radians() + increment;
  2356. for (var i = 0; i < numberOfSegments; i++) {
  2357. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2358. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2359. this.addLineTo(x, y);
  2360. currentAngle += increment;
  2361. }
  2362. return this;
  2363. };
  2364. Path2.prototype.close = function () {
  2365. this.closed = true;
  2366. return this;
  2367. };
  2368. Path2.prototype.length = function () {
  2369. var result = this._length;
  2370. if (!this.closed) {
  2371. var lastPoint = this._points[this._points.length - 1];
  2372. var firstPoint = this._points[0];
  2373. result += (firstPoint.subtract(lastPoint).length());
  2374. }
  2375. return result;
  2376. };
  2377. Path2.prototype.getPoints = function () {
  2378. return this._points;
  2379. };
  2380. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2381. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2382. BABYLON.Tools.Error("normalized length position should be between 0 and 1.");
  2383. return Vector2.Zero();
  2384. }
  2385. var lengthPosition = normalizedLengthPosition * this.length();
  2386. var previousOffset = 0;
  2387. for (var i = 0; i < this._points.length; i++) {
  2388. var j = (i + 1) % this._points.length;
  2389. var a = this._points[i];
  2390. var b = this._points[j];
  2391. var bToA = b.subtract(a);
  2392. var nextOffset = (bToA.length() + previousOffset);
  2393. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2394. var dir = bToA.normalize();
  2395. var localOffset = lengthPosition - previousOffset;
  2396. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2397. }
  2398. previousOffset = nextOffset;
  2399. }
  2400. BABYLON.Tools.Error("internal error");
  2401. return Vector2.Zero();
  2402. };
  2403. Path2.StartingAt = function (x, y) {
  2404. return new Path2(x, y);
  2405. };
  2406. return Path2;
  2407. })();
  2408. BABYLON.Path2 = Path2;
  2409. })(BABYLON || (BABYLON = {}));
  2410. //# sourceMappingURL=babylon.math.js.mapvar BABYLON;
  2411. (function (BABYLON) {
  2412. // Screenshots
  2413. var screenshotCanvas;
  2414. var cloneValue = function (source, destinationObject) {
  2415. if (!source)
  2416. return null;
  2417. if (source instanceof BABYLON.Mesh) {
  2418. return null;
  2419. }
  2420. if (source instanceof BABYLON.SubMesh) {
  2421. return source.clone(destinationObject);
  2422. }
  2423. else if (source.clone) {
  2424. return source.clone();
  2425. }
  2426. return null;
  2427. };
  2428. var Tools = (function () {
  2429. function Tools() {
  2430. }
  2431. Tools.GetFilename = function (path) {
  2432. var index = path.lastIndexOf("/");
  2433. if (index < 0)
  2434. return path;
  2435. return path.substring(index + 1);
  2436. };
  2437. Tools.GetDOMTextContent = function (element) {
  2438. var result = "";
  2439. var child = element.firstChild;
  2440. while (child) {
  2441. if (child.nodeType === 3) {
  2442. result += child.textContent;
  2443. }
  2444. child = child.nextSibling;
  2445. }
  2446. return result;
  2447. };
  2448. Tools.ToDegrees = function (angle) {
  2449. return angle * 180 / Math.PI;
  2450. };
  2451. Tools.ToRadians = function (angle) {
  2452. return angle * Math.PI / 180;
  2453. };
  2454. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  2455. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  2456. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  2457. for (var index = indexStart; index < indexStart + indexCount; index++) {
  2458. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  2459. minimum = BABYLON.Vector3.Minimize(current, minimum);
  2460. maximum = BABYLON.Vector3.Maximize(current, maximum);
  2461. }
  2462. return {
  2463. minimum: minimum,
  2464. maximum: maximum
  2465. };
  2466. };
  2467. Tools.ExtractMinAndMax = function (positions, start, count) {
  2468. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  2469. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  2470. for (var index = start; index < start + count; index++) {
  2471. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  2472. minimum = BABYLON.Vector3.Minimize(current, minimum);
  2473. maximum = BABYLON.Vector3.Maximize(current, maximum);
  2474. }
  2475. return {
  2476. minimum: minimum,
  2477. maximum: maximum
  2478. };
  2479. };
  2480. Tools.MakeArray = function (obj, allowsNullUndefined) {
  2481. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  2482. return undefined;
  2483. return Array.isArray(obj) ? obj : [obj];
  2484. };
  2485. // Misc.
  2486. Tools.GetPointerPrefix = function () {
  2487. var eventPrefix = "pointer";
  2488. // Check if hand.js is referenced or if the browser natively supports pointer events
  2489. if (!navigator.pointerEnabled) {
  2490. eventPrefix = "mouse";
  2491. }
  2492. return eventPrefix;
  2493. };
  2494. Tools.QueueNewFrame = function (func) {
  2495. if (window.requestAnimationFrame)
  2496. window.requestAnimationFrame(func);
  2497. else if (window.msRequestAnimationFrame)
  2498. window.msRequestAnimationFrame(func);
  2499. else if (window.webkitRequestAnimationFrame)
  2500. window.webkitRequestAnimationFrame(func);
  2501. else if (window.mozRequestAnimationFrame)
  2502. window.mozRequestAnimationFrame(func);
  2503. else if (window.oRequestAnimationFrame)
  2504. window.oRequestAnimationFrame(func);
  2505. else {
  2506. window.setTimeout(func, 16);
  2507. }
  2508. };
  2509. Tools.RequestFullscreen = function (element) {
  2510. if (element.requestFullscreen)
  2511. element.requestFullscreen();
  2512. else if (element.msRequestFullscreen)
  2513. element.msRequestFullscreen();
  2514. else if (element.webkitRequestFullscreen)
  2515. element.webkitRequestFullscreen();
  2516. else if (element.mozRequestFullScreen)
  2517. element.mozRequestFullScreen();
  2518. };
  2519. Tools.ExitFullscreen = function () {
  2520. if (document.exitFullscreen) {
  2521. document.exitFullscreen();
  2522. }
  2523. else if (document.mozCancelFullScreen) {
  2524. document.mozCancelFullScreen();
  2525. }
  2526. else if (document.webkitCancelFullScreen) {
  2527. document.webkitCancelFullScreen();
  2528. }
  2529. else if (document.msCancelFullScreen) {
  2530. document.msCancelFullScreen();
  2531. }
  2532. };
  2533. // External files
  2534. Tools.CleanUrl = function (url) {
  2535. url = url.replace(/#/mg, "%23");
  2536. return url;
  2537. };
  2538. Tools.LoadImage = function (url, onload, onerror, database) {
  2539. url = Tools.CleanUrl(url);
  2540. var img = new Image();
  2541. if (url.substr(0, 5) !== "data:")
  2542. img.crossOrigin = 'anonymous';
  2543. img.onload = function () {
  2544. onload(img);
  2545. };
  2546. img.onerror = function (err) {
  2547. onerror(img, err);
  2548. };
  2549. var noIndexedDB = function () {
  2550. img.src = url;
  2551. };
  2552. var loadFromIndexedDB = function () {
  2553. database.loadImageFromDB(url, img);
  2554. };
  2555. //ANY database to do!
  2556. if (database && database.enableTexturesOffline && BABYLON.Database.isUASupportingBlobStorage) {
  2557. database.openAsync(loadFromIndexedDB, noIndexedDB);
  2558. }
  2559. else {
  2560. if (url.indexOf("file:") === -1) {
  2561. noIndexedDB();
  2562. }
  2563. else {
  2564. try {
  2565. var textureName = url.substring(5);
  2566. var blobURL;
  2567. try {
  2568. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  2569. }
  2570. catch (ex) {
  2571. // Chrome doesn't support oneTimeOnly parameter
  2572. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  2573. }
  2574. img.src = blobURL;
  2575. }
  2576. catch (e) {
  2577. Tools.Log("Error while trying to load texture: " + textureName);
  2578. img.src = null;
  2579. }
  2580. }
  2581. }
  2582. return img;
  2583. };
  2584. //ANY
  2585. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  2586. url = Tools.CleanUrl(url);
  2587. var noIndexedDB = function () {
  2588. var request = new XMLHttpRequest();
  2589. var loadUrl = Tools.BaseUrl + url;
  2590. request.open('GET', loadUrl, true);
  2591. if (useArrayBuffer) {
  2592. request.responseType = "arraybuffer";
  2593. }
  2594. request.onprogress = progressCallBack;
  2595. request.onreadystatechange = function () {
  2596. if (request.readyState === 4) {
  2597. if (request.status === 200 || Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  2598. callback(!useArrayBuffer ? request.responseText : request.response);
  2599. }
  2600. else {
  2601. if (onError) {
  2602. onError();
  2603. }
  2604. else {
  2605. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  2606. }
  2607. }
  2608. }
  2609. };
  2610. request.send(null);
  2611. };
  2612. var loadFromIndexedDB = function () {
  2613. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  2614. };
  2615. if (url.indexOf("file:") !== -1) {
  2616. var fileName = url.substring(5);
  2617. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  2618. }
  2619. else {
  2620. // Caching all files
  2621. if (database && database.enableSceneOffline) {
  2622. database.openAsync(loadFromIndexedDB, noIndexedDB);
  2623. }
  2624. else {
  2625. noIndexedDB();
  2626. }
  2627. }
  2628. };
  2629. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  2630. var reader = new FileReader();
  2631. reader.onload = function (e) {
  2632. callback(e.target.result);
  2633. };
  2634. reader.onprogress = progressCallback;
  2635. reader.readAsDataURL(fileToLoad);
  2636. };
  2637. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  2638. var reader = new FileReader();
  2639. reader.onload = function (e) {
  2640. callback(e.target.result);
  2641. };
  2642. reader.onprogress = progressCallBack;
  2643. if (!useArrayBuffer) {
  2644. // Asynchronous read
  2645. reader.readAsText(fileToLoad);
  2646. }
  2647. else {
  2648. reader.readAsArrayBuffer(fileToLoad);
  2649. }
  2650. };
  2651. // Misc.
  2652. Tools.Clamp = function (value, min, max) {
  2653. if (min === void 0) { min = 0; }
  2654. if (max === void 0) { max = 1; }
  2655. return Math.min(max, Math.max(min, value));
  2656. };
  2657. // Returns -1 when value is a negative number and
  2658. // +1 when value is a positive number.
  2659. Tools.Sign = function (value) {
  2660. value = +value; // convert to a number
  2661. if (value === 0 || isNaN(value))
  2662. return value;
  2663. return value > 0 ? 1 : -1;
  2664. };
  2665. Tools.Format = function (value, decimals) {
  2666. if (decimals === void 0) { decimals = 2; }
  2667. return value.toFixed(decimals);
  2668. };
  2669. Tools.CheckExtends = function (v, min, max) {
  2670. if (v.x < min.x)
  2671. min.x = v.x;
  2672. if (v.y < min.y)
  2673. min.y = v.y;
  2674. if (v.z < min.z)
  2675. min.z = v.z;
  2676. if (v.x > max.x)
  2677. max.x = v.x;
  2678. if (v.y > max.y)
  2679. max.y = v.y;
  2680. if (v.z > max.z)
  2681. max.z = v.z;
  2682. };
  2683. Tools.WithinEpsilon = function (a, b, epsilon) {
  2684. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  2685. var num = a - b;
  2686. return -epsilon <= num && num <= epsilon;
  2687. };
  2688. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  2689. for (var prop in source) {
  2690. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  2691. continue;
  2692. }
  2693. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  2694. continue;
  2695. }
  2696. var sourceValue = source[prop];
  2697. var typeOfSourceValue = typeof sourceValue;
  2698. if (typeOfSourceValue === "function") {
  2699. continue;
  2700. }
  2701. if (typeOfSourceValue === "object") {
  2702. if (sourceValue instanceof Array) {
  2703. destination[prop] = [];
  2704. if (sourceValue.length > 0) {
  2705. if (typeof sourceValue[0] == "object") {
  2706. for (var index = 0; index < sourceValue.length; index++) {
  2707. var clonedValue = cloneValue(sourceValue[index], destination);
  2708. if (destination[prop].indexOf(clonedValue) === -1) {
  2709. destination[prop].push(clonedValue);
  2710. }
  2711. }
  2712. }
  2713. else {
  2714. destination[prop] = sourceValue.slice(0);
  2715. }
  2716. }
  2717. }
  2718. else {
  2719. destination[prop] = cloneValue(sourceValue, destination);
  2720. }
  2721. }
  2722. else {
  2723. destination[prop] = sourceValue;
  2724. }
  2725. }
  2726. };
  2727. Tools.IsEmpty = function (obj) {
  2728. for (var i in obj) {
  2729. return false;
  2730. }
  2731. return true;
  2732. };
  2733. Tools.RegisterTopRootEvents = function (events) {
  2734. for (var index = 0; index < events.length; index++) {
  2735. var event = events[index];
  2736. window.addEventListener(event.name, event.handler, false);
  2737. try {
  2738. if (window.parent) {
  2739. window.parent.addEventListener(event.name, event.handler, false);
  2740. }
  2741. }
  2742. catch (e) {
  2743. }
  2744. }
  2745. };
  2746. Tools.UnregisterTopRootEvents = function (events) {
  2747. for (var index = 0; index < events.length; index++) {
  2748. var event = events[index];
  2749. window.removeEventListener(event.name, event.handler);
  2750. try {
  2751. if (window.parent) {
  2752. window.parent.removeEventListener(event.name, event.handler);
  2753. }
  2754. }
  2755. catch (e) {
  2756. }
  2757. }
  2758. };
  2759. Tools.CreateScreenshot = function (engine, camera, size) {
  2760. var width;
  2761. var height;
  2762. var scene = camera.getScene();
  2763. var previousCamera = null;
  2764. if (scene.activeCamera !== camera) {
  2765. previousCamera = scene.activeCamera;
  2766. scene.activeCamera = camera;
  2767. }
  2768. //If a precision value is specified
  2769. if (size.precision) {
  2770. width = Math.round(engine.getRenderWidth() * size.precision);
  2771. height = Math.round(width / engine.getAspectRatio(camera));
  2772. size = { width: width, height: height };
  2773. }
  2774. else if (size.width && size.height) {
  2775. width = size.width;
  2776. height = size.height;
  2777. }
  2778. else if (size.width && !size.height) {
  2779. width = size.width;
  2780. height = Math.round(width / engine.getAspectRatio(camera));
  2781. size = { width: width, height: height };
  2782. }
  2783. else if (size.height && !size.width) {
  2784. height = size.height;
  2785. width = Math.round(height * engine.getAspectRatio(camera));
  2786. size = { width: width, height: height };
  2787. }
  2788. else if (!isNaN(size)) {
  2789. height = size;
  2790. width = size;
  2791. }
  2792. else {
  2793. Tools.Error("Invalid 'size' parameter !");
  2794. return;
  2795. }
  2796. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  2797. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  2798. texture.renderList = scene.meshes;
  2799. texture.onAfterRender = function () {
  2800. // Read the contents of the framebuffer
  2801. var numberOfChannelsByLine = width * 4;
  2802. var halfHeight = height / 2;
  2803. //Reading datas from WebGL
  2804. var data = engine.readPixels(0, 0, width, height);
  2805. for (var i = 0; i < halfHeight; i++) {
  2806. for (var j = 0; j < numberOfChannelsByLine; j++) {
  2807. var currentCell = j + i * numberOfChannelsByLine;
  2808. var targetLine = height - i - 1;
  2809. var targetCell = j + targetLine * numberOfChannelsByLine;
  2810. var temp = data[currentCell];
  2811. data[currentCell] = data[targetCell];
  2812. data[targetCell] = temp;
  2813. }
  2814. }
  2815. // Create a 2D canvas to store the result
  2816. if (!screenshotCanvas) {
  2817. screenshotCanvas = document.createElement('canvas');
  2818. }
  2819. screenshotCanvas.width = width;
  2820. screenshotCanvas.height = height;
  2821. var context = screenshotCanvas.getContext('2d');
  2822. // Copy the pixels to a 2D canvas
  2823. var imageData = context.createImageData(width, height);
  2824. imageData.data.set(data);
  2825. context.putImageData(imageData, 0, 0);
  2826. var base64Image = screenshotCanvas.toDataURL();
  2827. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  2828. if (("download" in document.createElement("a"))) {
  2829. var a = window.document.createElement("a");
  2830. a.href = base64Image;
  2831. var date = new Date();
  2832. var stringDate = date.getFullYear() + "/" + date.getMonth() + "/" + date.getDate() + "-" + date.getHours() + ":" + date.getMinutes();
  2833. a.setAttribute("download", "screenshot-" + stringDate + ".png");
  2834. window.document.body.appendChild(a);
  2835. a.addEventListener("click", function () {
  2836. a.parentElement.removeChild(a);
  2837. });
  2838. a.click();
  2839. }
  2840. else {
  2841. var newWindow = window.open("");
  2842. var img = newWindow.document.createElement("img");
  2843. img.src = base64Image;
  2844. newWindow.document.body.appendChild(img);
  2845. }
  2846. };
  2847. scene.incrementRenderId();
  2848. texture.render(true);
  2849. texture.dispose();
  2850. if (previousCamera) {
  2851. scene.activeCamera = previousCamera;
  2852. }
  2853. };
  2854. // XHR response validator for local file scenario
  2855. Tools.ValidateXHRData = function (xhr, dataType) {
  2856. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  2857. if (dataType === void 0) { dataType = 7; }
  2858. try {
  2859. if (dataType & 1) {
  2860. if (xhr.responseText && xhr.responseText.length > 0) {
  2861. return true;
  2862. }
  2863. else if (dataType === 1) {
  2864. return false;
  2865. }
  2866. }
  2867. if (dataType & 2) {
  2868. // Check header width and height since there is no "TGA" magic number
  2869. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  2870. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  2871. return true;
  2872. }
  2873. else if (dataType === 2) {
  2874. return false;
  2875. }
  2876. }
  2877. if (dataType & 4) {
  2878. // Check for the "DDS" magic number
  2879. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  2880. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  2881. return true;
  2882. }
  2883. else {
  2884. return false;
  2885. }
  2886. }
  2887. }
  2888. catch (e) {
  2889. }
  2890. return false;
  2891. };
  2892. Object.defineProperty(Tools, "NoneLogLevel", {
  2893. get: function () {
  2894. return Tools._NoneLogLevel;
  2895. },
  2896. enumerable: true,
  2897. configurable: true
  2898. });
  2899. Object.defineProperty(Tools, "MessageLogLevel", {
  2900. get: function () {
  2901. return Tools._MessageLogLevel;
  2902. },
  2903. enumerable: true,
  2904. configurable: true
  2905. });
  2906. Object.defineProperty(Tools, "WarningLogLevel", {
  2907. get: function () {
  2908. return Tools._WarningLogLevel;
  2909. },
  2910. enumerable: true,
  2911. configurable: true
  2912. });
  2913. Object.defineProperty(Tools, "ErrorLogLevel", {
  2914. get: function () {
  2915. return Tools._ErrorLogLevel;
  2916. },
  2917. enumerable: true,
  2918. configurable: true
  2919. });
  2920. Object.defineProperty(Tools, "AllLogLevel", {
  2921. get: function () {
  2922. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  2923. },
  2924. enumerable: true,
  2925. configurable: true
  2926. });
  2927. Tools._AddLogEntry = function (entry) {
  2928. Tools._LogCache = entry + Tools._LogCache;
  2929. if (Tools.OnNewCacheEntry) {
  2930. Tools.OnNewCacheEntry(entry);
  2931. }
  2932. };
  2933. Tools._FormatMessage = function (message) {
  2934. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  2935. var date = new Date();
  2936. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  2937. };
  2938. Tools._LogDisabled = function (message) {
  2939. // nothing to do
  2940. };
  2941. Tools._LogEnabled = function (message) {
  2942. var formattedMessage = Tools._FormatMessage(message);
  2943. console.log("BJS - " + formattedMessage);
  2944. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  2945. Tools._AddLogEntry(entry);
  2946. };
  2947. Tools._WarnDisabled = function (message) {
  2948. // nothing to do
  2949. };
  2950. Tools._WarnEnabled = function (message) {
  2951. var formattedMessage = Tools._FormatMessage(message);
  2952. console.warn("BJS - " + formattedMessage);
  2953. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  2954. Tools._AddLogEntry(entry);
  2955. };
  2956. Tools._ErrorDisabled = function (message) {
  2957. // nothing to do
  2958. };
  2959. Tools._ErrorEnabled = function (message) {
  2960. var formattedMessage = Tools._FormatMessage(message);
  2961. console.error("BJS - " + formattedMessage);
  2962. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  2963. Tools._AddLogEntry(entry);
  2964. };
  2965. Object.defineProperty(Tools, "LogCache", {
  2966. get: function () {
  2967. return Tools._LogCache;
  2968. },
  2969. enumerable: true,
  2970. configurable: true
  2971. });
  2972. Object.defineProperty(Tools, "LogLevels", {
  2973. set: function (level) {
  2974. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  2975. Tools.Log = Tools._LogEnabled;
  2976. }
  2977. else {
  2978. Tools.Log = Tools._LogDisabled;
  2979. }
  2980. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  2981. Tools.Warn = Tools._WarnEnabled;
  2982. }
  2983. else {
  2984. Tools.Warn = Tools._WarnDisabled;
  2985. }
  2986. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  2987. Tools.Error = Tools._ErrorEnabled;
  2988. }
  2989. else {
  2990. Tools.Error = Tools._ErrorDisabled;
  2991. }
  2992. },
  2993. enumerable: true,
  2994. configurable: true
  2995. });
  2996. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  2997. get: function () {
  2998. return Tools._PerformanceNoneLogLevel;
  2999. },
  3000. enumerable: true,
  3001. configurable: true
  3002. });
  3003. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  3004. get: function () {
  3005. return Tools._PerformanceUserMarkLogLevel;
  3006. },
  3007. enumerable: true,
  3008. configurable: true
  3009. });
  3010. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  3011. get: function () {
  3012. return Tools._PerformanceConsoleLogLevel;
  3013. },
  3014. enumerable: true,
  3015. configurable: true
  3016. });
  3017. Object.defineProperty(Tools, "PerformanceLogLevel", {
  3018. set: function (level) {
  3019. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  3020. Tools.StartPerformanceCounter = Tools._StartUserMark;
  3021. Tools.EndPerformanceCounter = Tools._EndUserMark;
  3022. return;
  3023. }
  3024. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  3025. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  3026. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  3027. return;
  3028. }
  3029. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  3030. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  3031. },
  3032. enumerable: true,
  3033. configurable: true
  3034. });
  3035. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  3036. };
  3037. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  3038. };
  3039. Tools._StartUserMark = function (counterName, condition) {
  3040. if (condition === void 0) { condition = true; }
  3041. if (!condition || !Tools._performance.mark) {
  3042. return;
  3043. }
  3044. Tools._performance.mark(counterName + "-Begin");
  3045. };
  3046. Tools._EndUserMark = function (counterName, condition) {
  3047. if (condition === void 0) { condition = true; }
  3048. if (!condition || !Tools._performance.mark) {
  3049. return;
  3050. }
  3051. Tools._performance.mark(counterName + "-End");
  3052. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  3053. };
  3054. Tools._StartPerformanceConsole = function (counterName, condition) {
  3055. if (condition === void 0) { condition = true; }
  3056. if (!condition) {
  3057. return;
  3058. }
  3059. Tools._StartUserMark(counterName, condition);
  3060. if (console.time) {
  3061. console.time(counterName);
  3062. }
  3063. };
  3064. Tools._EndPerformanceConsole = function (counterName, condition) {
  3065. if (condition === void 0) { condition = true; }
  3066. if (!condition) {
  3067. return;
  3068. }
  3069. Tools._EndUserMark(counterName, condition);
  3070. if (console.time) {
  3071. console.timeEnd(counterName);
  3072. }
  3073. };
  3074. Object.defineProperty(Tools, "Now", {
  3075. get: function () {
  3076. if (window.performance && window.performance.now) {
  3077. return window.performance.now();
  3078. }
  3079. return new Date().getTime();
  3080. },
  3081. enumerable: true,
  3082. configurable: true
  3083. });
  3084. // Deprecated
  3085. Tools.GetFps = function () {
  3086. Tools.Warn("Tools.GetFps() is deprecated. Please use engine.getFps() instead");
  3087. return 0;
  3088. };
  3089. Tools.BaseUrl = "";
  3090. Tools.GetExponantOfTwo = function (value, max) {
  3091. var count = 1;
  3092. do {
  3093. count *= 2;
  3094. } while (count < value);
  3095. if (count > max)
  3096. count = max;
  3097. return count;
  3098. };
  3099. // Logs
  3100. Tools._NoneLogLevel = 0;
  3101. Tools._MessageLogLevel = 1;
  3102. Tools._WarningLogLevel = 2;
  3103. Tools._ErrorLogLevel = 4;
  3104. Tools._LogCache = "";
  3105. Tools.Log = Tools._LogEnabled;
  3106. Tools.Warn = Tools._WarnEnabled;
  3107. Tools.Error = Tools._ErrorEnabled;
  3108. // Performances
  3109. Tools._PerformanceNoneLogLevel = 0;
  3110. Tools._PerformanceUserMarkLogLevel = 1;
  3111. Tools._PerformanceConsoleLogLevel = 2;
  3112. Tools._performance = window.performance;
  3113. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  3114. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  3115. return Tools;
  3116. })();
  3117. BABYLON.Tools = Tools;
  3118. /**
  3119. * An implementation of a loop for asynchronous functions.
  3120. */
  3121. var AsyncLoop = (function () {
  3122. /**
  3123. * Constroctor.
  3124. * @param iterations the number of iterations.
  3125. * @param _fn the function to run each iteration
  3126. * @param _successCallback the callback that will be called upon succesful execution
  3127. * @param offset starting offset.
  3128. */
  3129. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  3130. if (offset === void 0) { offset = 0; }
  3131. this.iterations = iterations;
  3132. this._fn = _fn;
  3133. this._successCallback = _successCallback;
  3134. this.index = offset - 1;
  3135. this._done = false;
  3136. }
  3137. /**
  3138. * Execute the next iteration. Must be called after the last iteration was finished.
  3139. */
  3140. AsyncLoop.prototype.executeNext = function () {
  3141. if (!this._done) {
  3142. if (this.index + 1 < this.iterations) {
  3143. ++this.index;
  3144. this._fn(this);
  3145. }
  3146. else {
  3147. this.breakLoop();
  3148. }
  3149. }
  3150. };
  3151. /**
  3152. * Break the loop and run the success callback.
  3153. */
  3154. AsyncLoop.prototype.breakLoop = function () {
  3155. this._done = true;
  3156. this._successCallback();
  3157. };
  3158. /**
  3159. * Helper function
  3160. */
  3161. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  3162. if (offset === void 0) { offset = 0; }
  3163. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  3164. loop.executeNext();
  3165. return loop;
  3166. };
  3167. /**
  3168. * A for-loop that will run a given number of iterations synchronous and the rest async.
  3169. * @param iterations total number of iterations
  3170. * @param syncedIterations number of synchronous iterations in each async iteration.
  3171. * @param fn the function to call each iteration.
  3172. * @param callback a success call back that will be called when iterating stops.
  3173. * @param breakFunction a break condition (optional)
  3174. * @param timeout timeout settings for the setTimeout function. default - 0.
  3175. * @constructor
  3176. */
  3177. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  3178. if (timeout === void 0) { timeout = 0; }
  3179. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  3180. if (breakFunction && breakFunction())
  3181. loop.breakLoop();
  3182. else {
  3183. setTimeout(function () {
  3184. for (var i = 0; i < syncedIterations; ++i) {
  3185. var iteration = (loop.index * syncedIterations) + i;
  3186. if (iteration >= iterations)
  3187. break;
  3188. fn(iteration);
  3189. if (breakFunction && breakFunction()) {
  3190. loop.breakLoop();
  3191. break;
  3192. }
  3193. }
  3194. loop.executeNext();
  3195. }, timeout);
  3196. }
  3197. }, callback);
  3198. };
  3199. return AsyncLoop;
  3200. })();
  3201. BABYLON.AsyncLoop = AsyncLoop;
  3202. })(BABYLON || (BABYLON = {}));
  3203. //# sourceMappingURL=babylon.tools.js.mapvar BABYLON;
  3204. (function (BABYLON) {
  3205. var _DepthCullingState = (function () {
  3206. function _DepthCullingState() {
  3207. this._isDepthTestDirty = false;
  3208. this._isDepthMaskDirty = false;
  3209. this._isDepthFuncDirty = false;
  3210. this._isCullFaceDirty = false;
  3211. this._isCullDirty = false;
  3212. }
  3213. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  3214. get: function () {
  3215. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty;
  3216. },
  3217. enumerable: true,
  3218. configurable: true
  3219. });
  3220. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  3221. get: function () {
  3222. return this._cullFace;
  3223. },
  3224. set: function (value) {
  3225. if (this._cullFace === value) {
  3226. return;
  3227. }
  3228. this._cullFace = value;
  3229. this._isCullFaceDirty = true;
  3230. },
  3231. enumerable: true,
  3232. configurable: true
  3233. });
  3234. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  3235. get: function () {
  3236. return this._cull;
  3237. },
  3238. set: function (value) {
  3239. if (this._cull === value) {
  3240. return;
  3241. }
  3242. this._cull = value;
  3243. this._isCullDirty = true;
  3244. },
  3245. enumerable: true,
  3246. configurable: true
  3247. });
  3248. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  3249. get: function () {
  3250. return this._depthFunc;
  3251. },
  3252. set: function (value) {
  3253. if (this._depthFunc === value) {
  3254. return;
  3255. }
  3256. this._depthFunc = value;
  3257. this._isDepthFuncDirty = true;
  3258. },
  3259. enumerable: true,
  3260. configurable: true
  3261. });
  3262. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  3263. get: function () {
  3264. return this._depthMask;
  3265. },
  3266. set: function (value) {
  3267. if (this._depthMask === value) {
  3268. return;
  3269. }
  3270. this._depthMask = value;
  3271. this._isDepthMaskDirty = true;
  3272. },
  3273. enumerable: true,
  3274. configurable: true
  3275. });
  3276. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  3277. get: function () {
  3278. return this._depthTest;
  3279. },
  3280. set: function (value) {
  3281. if (this._depthTest === value) {
  3282. return;
  3283. }
  3284. this._depthTest = value;
  3285. this._isDepthTestDirty = true;
  3286. },
  3287. enumerable: true,
  3288. configurable: true
  3289. });
  3290. _DepthCullingState.prototype.reset = function () {
  3291. this._depthMask = true;
  3292. this._depthTest = true;
  3293. this._depthFunc = null;
  3294. this._cull = null;
  3295. this._cullFace = null;
  3296. this._isDepthTestDirty = true;
  3297. this._isDepthMaskDirty = true;
  3298. this._isDepthFuncDirty = false;
  3299. this._isCullFaceDirty = false;
  3300. this._isCullDirty = false;
  3301. };
  3302. _DepthCullingState.prototype.apply = function (gl) {
  3303. if (!this.isDirty) {
  3304. return;
  3305. }
  3306. // Cull
  3307. if (this._isCullDirty) {
  3308. if (this.cull) {
  3309. gl.enable(gl.CULL_FACE);
  3310. }
  3311. else {
  3312. gl.disable(gl.CULL_FACE);
  3313. }
  3314. this._isCullDirty = false;
  3315. }
  3316. // Cull face
  3317. if (this._isCullFaceDirty) {
  3318. gl.cullFace(this.cullFace);
  3319. this._isCullFaceDirty = false;
  3320. }
  3321. // Depth mask
  3322. if (this._isDepthMaskDirty) {
  3323. gl.depthMask(this.depthMask);
  3324. this._isDepthMaskDirty = false;
  3325. }
  3326. // Depth test
  3327. if (this._isDepthTestDirty) {
  3328. if (this.depthTest) {
  3329. gl.enable(gl.DEPTH_TEST);
  3330. }
  3331. else {
  3332. gl.disable(gl.DEPTH_TEST);
  3333. }
  3334. this._isDepthTestDirty = false;
  3335. }
  3336. // Depth func
  3337. if (this._isDepthFuncDirty) {
  3338. gl.depthFunc(this.depthFunc);
  3339. this._isDepthFuncDirty = false;
  3340. }
  3341. };
  3342. return _DepthCullingState;
  3343. })();
  3344. BABYLON._DepthCullingState = _DepthCullingState;
  3345. var _AlphaState = (function () {
  3346. function _AlphaState() {
  3347. this._isAlphaBlendDirty = false;
  3348. this._isBlendFunctionParametersDirty = false;
  3349. this._alphaBlend = false;
  3350. this._blendFunctionParameters = new Array(4);
  3351. }
  3352. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  3353. get: function () {
  3354. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  3355. },
  3356. enumerable: true,
  3357. configurable: true
  3358. });
  3359. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  3360. get: function () {
  3361. return this._alphaBlend;
  3362. },
  3363. set: function (value) {
  3364. if (this._alphaBlend === value) {
  3365. return;
  3366. }
  3367. this._alphaBlend = value;
  3368. this._isAlphaBlendDirty = true;
  3369. },
  3370. enumerable: true,
  3371. configurable: true
  3372. });
  3373. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  3374. if (this._blendFunctionParameters[0] === value0 && this._blendFunctionParameters[1] === value1 && this._blendFunctionParameters[2] === value2 && this._blendFunctionParameters[3] === value3) {
  3375. return;
  3376. }
  3377. this._blendFunctionParameters[0] = value0;
  3378. this._blendFunctionParameters[1] = value1;
  3379. this._blendFunctionParameters[2] = value2;
  3380. this._blendFunctionParameters[3] = value3;
  3381. this._isBlendFunctionParametersDirty = true;
  3382. };
  3383. _AlphaState.prototype.reset = function () {
  3384. this._alphaBlend = false;
  3385. this._blendFunctionParameters[0] = null;
  3386. this._blendFunctionParameters[1] = null;
  3387. this._blendFunctionParameters[2] = null;
  3388. this._blendFunctionParameters[3] = null;
  3389. this._isAlphaBlendDirty = true;
  3390. this._isBlendFunctionParametersDirty = false;
  3391. };
  3392. _AlphaState.prototype.apply = function (gl) {
  3393. if (!this.isDirty) {
  3394. return;
  3395. }
  3396. // Alpha blend
  3397. if (this._isAlphaBlendDirty) {
  3398. if (this._alphaBlend) {
  3399. gl.enable(gl.BLEND);
  3400. }
  3401. else {
  3402. gl.disable(gl.BLEND);
  3403. }
  3404. this._isAlphaBlendDirty = false;
  3405. }
  3406. // Alpha function
  3407. if (this._isBlendFunctionParametersDirty) {
  3408. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  3409. this._isBlendFunctionParametersDirty = false;
  3410. }
  3411. };
  3412. return _AlphaState;
  3413. })();
  3414. BABYLON._AlphaState = _AlphaState;
  3415. var compileShader = function (gl, source, type, defines) {
  3416. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  3417. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  3418. gl.compileShader(shader);
  3419. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  3420. throw new Error(gl.getShaderInfoLog(shader));
  3421. }
  3422. return shader;
  3423. };
  3424. var getWebGLTextureType = function (gl, type) {
  3425. var textureType = gl.UNSIGNED_BYTE;
  3426. if (type === Engine.TEXTURETYPE_FLOAT)
  3427. textureType = gl.FLOAT;
  3428. return textureType;
  3429. };
  3430. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  3431. var magFilter = gl.NEAREST;
  3432. var minFilter = gl.NEAREST;
  3433. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  3434. magFilter = gl.LINEAR;
  3435. if (generateMipMaps) {
  3436. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  3437. }
  3438. else {
  3439. minFilter = gl.LINEAR;
  3440. }
  3441. }
  3442. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  3443. magFilter = gl.LINEAR;
  3444. if (generateMipMaps) {
  3445. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  3446. }
  3447. else {
  3448. minFilter = gl.LINEAR;
  3449. }
  3450. }
  3451. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  3452. magFilter = gl.NEAREST;
  3453. if (generateMipMaps) {
  3454. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  3455. }
  3456. else {
  3457. minFilter = gl.NEAREST;
  3458. }
  3459. }
  3460. return {
  3461. min: minFilter,
  3462. mag: magFilter
  3463. };
  3464. };
  3465. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  3466. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  3467. var engine = scene.getEngine();
  3468. var potWidth = BABYLON.Tools.GetExponantOfTwo(width, engine.getCaps().maxTextureSize);
  3469. var potHeight = BABYLON.Tools.GetExponantOfTwo(height, engine.getCaps().maxTextureSize);
  3470. gl.bindTexture(gl.TEXTURE_2D, texture);
  3471. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  3472. processFunction(potWidth, potHeight);
  3473. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  3474. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  3475. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  3476. if (!noMipmap && !isCompressed) {
  3477. gl.generateMipmap(gl.TEXTURE_2D);
  3478. }
  3479. gl.bindTexture(gl.TEXTURE_2D, null);
  3480. engine._activeTexturesCache = [];
  3481. texture._baseWidth = width;
  3482. texture._baseHeight = height;
  3483. texture._width = potWidth;
  3484. texture._height = potHeight;
  3485. texture.isReady = true;
  3486. texture.samplingMode = samplingMode;
  3487. scene._removePendingData(texture);
  3488. };
  3489. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  3490. var onload = function () {
  3491. loadedImages[index] = img;
  3492. loadedImages._internalCount++;
  3493. scene._removePendingData(img);
  3494. if (loadedImages._internalCount === 6) {
  3495. onfinish(loadedImages);
  3496. }
  3497. };
  3498. var onerror = function () {
  3499. scene._removePendingData(img);
  3500. };
  3501. var img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  3502. scene._addPendingData(img);
  3503. };
  3504. var cascadeLoad = function (rootUrl, scene, onfinish, extensions) {
  3505. var loadedImages = [];
  3506. loadedImages._internalCount = 0;
  3507. for (var index = 0; index < 6; index++) {
  3508. partialLoad(rootUrl + extensions[index], index, loadedImages, scene, onfinish);
  3509. }
  3510. };
  3511. var EngineCapabilities = (function () {
  3512. function EngineCapabilities() {
  3513. }
  3514. return EngineCapabilities;
  3515. })();
  3516. BABYLON.EngineCapabilities = EngineCapabilities;
  3517. /**
  3518. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  3519. */
  3520. var Engine = (function () {
  3521. /**
  3522. * @constructor
  3523. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  3524. * @param {boolean} [antialias] - enable antialias
  3525. * @param options - further options to be sent to the getContext function
  3526. */
  3527. function Engine(canvas, antialias, options) {
  3528. var _this = this;
  3529. // Public members
  3530. this.isFullscreen = false;
  3531. this.isPointerLock = false;
  3532. this.cullBackFaces = true;
  3533. this.renderEvenInBackground = true;
  3534. this.scenes = new Array();
  3535. this._windowIsBackground = false;
  3536. this._loadingDivBackgroundColor = "black";
  3537. this._drawCalls = 0;
  3538. this._renderingQueueLaunched = false;
  3539. this._activeRenderLoops = [];
  3540. // FPS
  3541. this.fpsRange = 60;
  3542. this.previousFramesDuration = [];
  3543. this.fps = 60;
  3544. this.deltaTime = 0;
  3545. // States
  3546. this._depthCullingState = new _DepthCullingState();
  3547. this._alphaState = new _AlphaState();
  3548. this._alphaMode = Engine.ALPHA_DISABLE;
  3549. // Cache
  3550. this._loadedTexturesCache = new Array();
  3551. this._activeTexturesCache = new Array();
  3552. this._compiledEffects = {};
  3553. this._uintIndicesCurrentlySet = false;
  3554. this._renderingCanvas = canvas;
  3555. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  3556. options = options || {};
  3557. options.antialias = antialias;
  3558. try {
  3559. this._gl = canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options);
  3560. }
  3561. catch (e) {
  3562. throw new Error("WebGL not supported");
  3563. }
  3564. if (!this._gl) {
  3565. throw new Error("WebGL not supported");
  3566. }
  3567. this._onBlur = function () {
  3568. _this._windowIsBackground = true;
  3569. };
  3570. this._onFocus = function () {
  3571. _this._windowIsBackground = false;
  3572. };
  3573. window.addEventListener("blur", this._onBlur);
  3574. window.addEventListener("focus", this._onFocus);
  3575. // Textures
  3576. this._workingCanvas = document.createElement("canvas");
  3577. this._workingContext = this._workingCanvas.getContext("2d");
  3578. // Viewport
  3579. this._hardwareScalingLevel = 1.0 / (window.devicePixelRatio || 1.0);
  3580. this.resize();
  3581. // Caps
  3582. this._caps = new EngineCapabilities();
  3583. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  3584. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  3585. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  3586. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  3587. // Infos
  3588. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  3589. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  3590. if (rendererInfo != null) {
  3591. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  3592. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  3593. }
  3594. if (!this._glVendor) {
  3595. this._glVendor = "Unknown vendor";
  3596. }
  3597. if (!this._glRenderer) {
  3598. this._glRenderer = "Unknown renderer";
  3599. }
  3600. // Extensions
  3601. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  3602. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  3603. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  3604. 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');
  3605. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  3606. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  3607. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  3608. // Depth buffer
  3609. this.setDepthBuffer(true);
  3610. this.setDepthFunctionToLessOrEqual();
  3611. this.setDepthWrite(true);
  3612. // Fullscreen
  3613. this._onFullscreenChange = function () {
  3614. if (document.fullscreen !== undefined) {
  3615. _this.isFullscreen = document.fullscreen;
  3616. }
  3617. else if (document.mozFullScreen !== undefined) {
  3618. _this.isFullscreen = document.mozFullScreen;
  3619. }
  3620. else if (document.webkitIsFullScreen !== undefined) {
  3621. _this.isFullscreen = document.webkitIsFullScreen;
  3622. }
  3623. else if (document.msIsFullScreen !== undefined) {
  3624. _this.isFullscreen = document.msIsFullScreen;
  3625. }
  3626. // Pointer lock
  3627. if (_this.isFullscreen && _this._pointerLockRequested) {
  3628. canvas.requestPointerLock = canvas.requestPointerLock || canvas.msRequestPointerLock || canvas.mozRequestPointerLock || canvas.webkitRequestPointerLock;
  3629. if (canvas.requestPointerLock) {
  3630. canvas.requestPointerLock();
  3631. }
  3632. }
  3633. };
  3634. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  3635. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  3636. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  3637. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  3638. // Pointer lock
  3639. this._onPointerLockChange = function () {
  3640. _this.isPointerLock = (document.mozPointerLockElement === canvas || document.webkitPointerLockElement === canvas || document.msPointerLockElement === canvas || document.pointerLockElement === canvas);
  3641. };
  3642. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  3643. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  3644. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  3645. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  3646. if (!Engine.audioEngine) {
  3647. Engine.audioEngine = new BABYLON.AudioEngine();
  3648. }
  3649. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  3650. }
  3651. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  3652. get: function () {
  3653. return Engine._ALPHA_DISABLE;
  3654. },
  3655. enumerable: true,
  3656. configurable: true
  3657. });
  3658. Object.defineProperty(Engine, "ALPHA_ADD", {
  3659. get: function () {
  3660. return Engine._ALPHA_ADD;
  3661. },
  3662. enumerable: true,
  3663. configurable: true
  3664. });
  3665. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  3666. get: function () {
  3667. return Engine._ALPHA_COMBINE;
  3668. },
  3669. enumerable: true,
  3670. configurable: true
  3671. });
  3672. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  3673. get: function () {
  3674. return Engine._DELAYLOADSTATE_NONE;
  3675. },
  3676. enumerable: true,
  3677. configurable: true
  3678. });
  3679. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  3680. get: function () {
  3681. return Engine._DELAYLOADSTATE_LOADED;
  3682. },
  3683. enumerable: true,
  3684. configurable: true
  3685. });
  3686. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  3687. get: function () {
  3688. return Engine._DELAYLOADSTATE_LOADING;
  3689. },
  3690. enumerable: true,
  3691. configurable: true
  3692. });
  3693. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  3694. get: function () {
  3695. return Engine._DELAYLOADSTATE_NOTLOADED;
  3696. },
  3697. enumerable: true,
  3698. configurable: true
  3699. });
  3700. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  3701. get: function () {
  3702. return Engine._TEXTUREFORMAT_ALPHA;
  3703. },
  3704. enumerable: true,
  3705. configurable: true
  3706. });
  3707. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  3708. get: function () {
  3709. return Engine._TEXTUREFORMAT_LUMINANCE;
  3710. },
  3711. enumerable: true,
  3712. configurable: true
  3713. });
  3714. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  3715. get: function () {
  3716. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  3717. },
  3718. enumerable: true,
  3719. configurable: true
  3720. });
  3721. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  3722. get: function () {
  3723. return Engine._TEXTUREFORMAT_RGB;
  3724. },
  3725. enumerable: true,
  3726. configurable: true
  3727. });
  3728. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  3729. get: function () {
  3730. return Engine._TEXTUREFORMAT_RGBA;
  3731. },
  3732. enumerable: true,
  3733. configurable: true
  3734. });
  3735. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  3736. get: function () {
  3737. return Engine._TEXTURETYPE_UNSIGNED_INT;
  3738. },
  3739. enumerable: true,
  3740. configurable: true
  3741. });
  3742. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  3743. get: function () {
  3744. return Engine._TEXTURETYPE_FLOAT;
  3745. },
  3746. enumerable: true,
  3747. configurable: true
  3748. });
  3749. Object.defineProperty(Engine, "Version", {
  3750. get: function () {
  3751. return "2.0.0";
  3752. },
  3753. enumerable: true,
  3754. configurable: true
  3755. });
  3756. Engine.prototype.getGlInfo = function () {
  3757. return {
  3758. vendor: this._glVendor,
  3759. renderer: this._glRenderer,
  3760. version: this._glVersion
  3761. };
  3762. };
  3763. Engine.prototype.getAspectRatio = function (camera) {
  3764. var viewport = camera.viewport;
  3765. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  3766. };
  3767. Engine.prototype.getRenderWidth = function () {
  3768. if (this._currentRenderTarget) {
  3769. return this._currentRenderTarget._width;
  3770. }
  3771. return this._renderingCanvas.width;
  3772. };
  3773. Engine.prototype.getRenderHeight = function () {
  3774. if (this._currentRenderTarget) {
  3775. return this._currentRenderTarget._height;
  3776. }
  3777. return this._renderingCanvas.height;
  3778. };
  3779. Engine.prototype.getRenderingCanvas = function () {
  3780. return this._renderingCanvas;
  3781. };
  3782. Engine.prototype.getRenderingCanvasClientRect = function () {
  3783. return this._renderingCanvas.getBoundingClientRect();
  3784. };
  3785. Engine.prototype.setHardwareScalingLevel = function (level) {
  3786. this._hardwareScalingLevel = level;
  3787. this.resize();
  3788. };
  3789. Engine.prototype.getHardwareScalingLevel = function () {
  3790. return this._hardwareScalingLevel;
  3791. };
  3792. Engine.prototype.getLoadedTexturesCache = function () {
  3793. return this._loadedTexturesCache;
  3794. };
  3795. Engine.prototype.getCaps = function () {
  3796. return this._caps;
  3797. };
  3798. Object.defineProperty(Engine.prototype, "drawCalls", {
  3799. get: function () {
  3800. return this._drawCalls;
  3801. },
  3802. enumerable: true,
  3803. configurable: true
  3804. });
  3805. // Methods
  3806. Engine.prototype.resetDrawCalls = function () {
  3807. this._drawCalls = 0;
  3808. };
  3809. Engine.prototype.setDepthFunctionToGreater = function () {
  3810. this._depthCullingState.depthFunc = this._gl.GREATER;
  3811. };
  3812. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  3813. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  3814. };
  3815. Engine.prototype.setDepthFunctionToLess = function () {
  3816. this._depthCullingState.depthFunc = this._gl.LESS;
  3817. };
  3818. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  3819. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  3820. };
  3821. /**
  3822. * stop executing a render loop function and remove it from the execution array
  3823. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  3824. */
  3825. Engine.prototype.stopRenderLoop = function (renderFunction) {
  3826. if (!renderFunction) {
  3827. this._activeRenderLoops = [];
  3828. return;
  3829. }
  3830. var index = this._activeRenderLoops.indexOf(renderFunction);
  3831. if (index >= 0) {
  3832. this._activeRenderLoops.splice(index, 1);
  3833. }
  3834. };
  3835. Engine.prototype._renderLoop = function () {
  3836. var _this = this;
  3837. var shouldRender = true;
  3838. if (!this.renderEvenInBackground && this._windowIsBackground) {
  3839. shouldRender = false;
  3840. }
  3841. if (shouldRender) {
  3842. // Start new frame
  3843. this.beginFrame();
  3844. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  3845. var renderFunction = this._activeRenderLoops[index];
  3846. renderFunction();
  3847. }
  3848. // Present
  3849. this.endFrame();
  3850. }
  3851. if (this._activeRenderLoops.length > 0) {
  3852. // Register new frame
  3853. BABYLON.Tools.QueueNewFrame(function () {
  3854. _this._renderLoop();
  3855. });
  3856. }
  3857. else {
  3858. this._renderingQueueLaunched = false;
  3859. }
  3860. };
  3861. /**
  3862. * Register and execute a render loop. The engine can have more than one render function.
  3863. * @param {Function} renderFunction - the function to continuesly execute starting the next render loop.
  3864. * @example
  3865. * engine.runRenderLoop(function () {
  3866. * scene.render()
  3867. * })
  3868. */
  3869. Engine.prototype.runRenderLoop = function (renderFunction) {
  3870. var _this = this;
  3871. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  3872. return;
  3873. }
  3874. this._activeRenderLoops.push(renderFunction);
  3875. if (!this._renderingQueueLaunched) {
  3876. this._renderingQueueLaunched = true;
  3877. BABYLON.Tools.QueueNewFrame(function () {
  3878. _this._renderLoop();
  3879. });
  3880. }
  3881. };
  3882. /**
  3883. * Toggle full screen mode.
  3884. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  3885. */
  3886. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  3887. if (this.isFullscreen) {
  3888. BABYLON.Tools.ExitFullscreen();
  3889. }
  3890. else {
  3891. this._pointerLockRequested = requestPointerLock;
  3892. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  3893. }
  3894. };
  3895. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  3896. this.applyStates();
  3897. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  3898. if (this._depthCullingState.depthMask) {
  3899. this._gl.clearDepth(1.0);
  3900. }
  3901. var mode = 0;
  3902. if (backBuffer)
  3903. mode |= this._gl.COLOR_BUFFER_BIT;
  3904. if (depthStencil && this._depthCullingState.depthMask)
  3905. mode |= this._gl.DEPTH_BUFFER_BIT;
  3906. this._gl.clear(mode);
  3907. };
  3908. /**
  3909. * Set the WebGL's viewport
  3910. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  3911. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  3912. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  3913. */
  3914. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  3915. var width = requiredWidth || this._renderingCanvas.width;
  3916. var height = requiredHeight || this._renderingCanvas.height;
  3917. var x = viewport.x || 0;
  3918. var y = viewport.y || 0;
  3919. this._cachedViewport = viewport;
  3920. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  3921. };
  3922. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  3923. this._cachedViewport = null;
  3924. this._gl.viewport(x, y, width, height);
  3925. };
  3926. Engine.prototype.beginFrame = function () {
  3927. this._measureFps();
  3928. };
  3929. Engine.prototype.endFrame = function () {
  3930. //this.flushFramebuffer();
  3931. };
  3932. /**
  3933. * resize the view according to the canvas' size.
  3934. * @example
  3935. * window.addEventListener("resize", function () {
  3936. * engine.resize();
  3937. * });
  3938. */
  3939. Engine.prototype.resize = function () {
  3940. this.setSize(this._renderingCanvas.clientWidth / this._hardwareScalingLevel, this._renderingCanvas.clientHeight / this._hardwareScalingLevel);
  3941. };
  3942. /**
  3943. * force a specific size of the canvas
  3944. * @param {number} width - the new canvas' width
  3945. * @param {number} height - the new canvas' height
  3946. */
  3947. Engine.prototype.setSize = function (width, height) {
  3948. this._renderingCanvas.width = width;
  3949. this._renderingCanvas.height = height;
  3950. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  3951. };
  3952. Engine.prototype.bindFramebuffer = function (texture) {
  3953. this._currentRenderTarget = texture;
  3954. var gl = this._gl;
  3955. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  3956. this._gl.viewport(0, 0, texture._width, texture._height);
  3957. this.wipeCaches();
  3958. };
  3959. Engine.prototype.unBindFramebuffer = function (texture) {
  3960. this._currentRenderTarget = null;
  3961. if (texture.generateMipMaps) {
  3962. var gl = this._gl;
  3963. gl.bindTexture(gl.TEXTURE_2D, texture);
  3964. gl.generateMipmap(gl.TEXTURE_2D);
  3965. gl.bindTexture(gl.TEXTURE_2D, null);
  3966. }
  3967. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  3968. };
  3969. Engine.prototype.flushFramebuffer = function () {
  3970. this._gl.flush();
  3971. };
  3972. Engine.prototype.restoreDefaultFramebuffer = function () {
  3973. this._currentRenderTarget = null;
  3974. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  3975. this.setViewport(this._cachedViewport);
  3976. this.wipeCaches();
  3977. };
  3978. // VBOs
  3979. Engine.prototype._resetVertexBufferBinding = function () {
  3980. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  3981. this._cachedVertexBuffers = null;
  3982. };
  3983. Engine.prototype.createVertexBuffer = function (vertices) {
  3984. var vbo = this._gl.createBuffer();
  3985. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  3986. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  3987. this._resetVertexBufferBinding();
  3988. vbo.references = 1;
  3989. return vbo;
  3990. };
  3991. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  3992. var vbo = this._gl.createBuffer();
  3993. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  3994. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  3995. this._resetVertexBufferBinding();
  3996. vbo.references = 1;
  3997. return vbo;
  3998. };
  3999. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  4000. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  4001. if (offset === undefined) {
  4002. offset = 0;
  4003. }
  4004. if (vertices instanceof Float32Array) {
  4005. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  4006. }
  4007. else {
  4008. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  4009. }
  4010. this._resetVertexBufferBinding();
  4011. };
  4012. Engine.prototype._resetIndexBufferBinding = function () {
  4013. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  4014. this._cachedIndexBuffer = null;
  4015. };
  4016. Engine.prototype.createIndexBuffer = function (indices) {
  4017. var vbo = this._gl.createBuffer();
  4018. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  4019. // Check for 32 bits indices
  4020. var arrayBuffer;
  4021. var need32Bits = false;
  4022. if (this._caps.uintIndices) {
  4023. for (var index = 0; index < indices.length; index++) {
  4024. if (indices[index] > 65535) {
  4025. need32Bits = true;
  4026. break;
  4027. }
  4028. }
  4029. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  4030. }
  4031. else {
  4032. arrayBuffer = new Uint16Array(indices);
  4033. }
  4034. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  4035. this._resetIndexBufferBinding();
  4036. vbo.references = 1;
  4037. vbo.is32Bits = need32Bits;
  4038. return vbo;
  4039. };
  4040. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  4041. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  4042. this._cachedVertexBuffers = vertexBuffer;
  4043. this._cachedEffectForVertexBuffers = effect;
  4044. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  4045. var offset = 0;
  4046. for (var index = 0; index < vertexDeclaration.length; index++) {
  4047. var order = effect.getAttributeLocation(index);
  4048. if (order >= 0) {
  4049. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  4050. }
  4051. offset += vertexDeclaration[index] * 4;
  4052. }
  4053. }
  4054. if (this._cachedIndexBuffer !== indexBuffer) {
  4055. this._cachedIndexBuffer = indexBuffer;
  4056. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  4057. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  4058. }
  4059. };
  4060. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  4061. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  4062. this._cachedVertexBuffers = vertexBuffers;
  4063. this._cachedEffectForVertexBuffers = effect;
  4064. var attributes = effect.getAttributesNames();
  4065. for (var index = 0; index < attributes.length; index++) {
  4066. var order = effect.getAttributeLocation(index);
  4067. if (order >= 0) {
  4068. var vertexBuffer = vertexBuffers[attributes[index]];
  4069. if (!vertexBuffer) {
  4070. continue;
  4071. }
  4072. var stride = vertexBuffer.getStrideSize();
  4073. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  4074. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  4075. }
  4076. }
  4077. }
  4078. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  4079. this._cachedIndexBuffer = indexBuffer;
  4080. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  4081. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  4082. }
  4083. };
  4084. Engine.prototype._releaseBuffer = function (buffer) {
  4085. buffer.references--;
  4086. if (buffer.references === 0) {
  4087. this._gl.deleteBuffer(buffer);
  4088. return true;
  4089. }
  4090. return false;
  4091. };
  4092. Engine.prototype.createInstancesBuffer = function (capacity) {
  4093. var buffer = this._gl.createBuffer();
  4094. buffer.capacity = capacity;
  4095. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  4096. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  4097. return buffer;
  4098. };
  4099. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  4100. this._gl.deleteBuffer(buffer);
  4101. };
  4102. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  4103. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  4104. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  4105. for (var index = 0; index < 4; index++) {
  4106. var offsetLocation = offsetLocations[index];
  4107. this._gl.enableVertexAttribArray(offsetLocation);
  4108. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  4109. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  4110. }
  4111. };
  4112. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  4113. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  4114. for (var index = 0; index < 4; index++) {
  4115. var offsetLocation = offsetLocations[index];
  4116. this._gl.disableVertexAttribArray(offsetLocation);
  4117. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  4118. }
  4119. };
  4120. Engine.prototype.applyStates = function () {
  4121. this._depthCullingState.apply(this._gl);
  4122. this._alphaState.apply(this._gl);
  4123. };
  4124. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  4125. // Apply states
  4126. this.applyStates();
  4127. this._drawCalls++;
  4128. // Render
  4129. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  4130. if (instancesCount) {
  4131. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2, instancesCount);
  4132. return;
  4133. }
  4134. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2);
  4135. };
  4136. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  4137. // Apply states
  4138. this.applyStates();
  4139. this._drawCalls++;
  4140. if (instancesCount) {
  4141. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  4142. return;
  4143. }
  4144. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  4145. };
  4146. // Shaders
  4147. Engine.prototype._releaseEffect = function (effect) {
  4148. if (this._compiledEffects[effect._key]) {
  4149. delete this._compiledEffects[effect._key];
  4150. if (effect.getProgram()) {
  4151. this._gl.deleteProgram(effect.getProgram());
  4152. }
  4153. }
  4154. };
  4155. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  4156. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  4157. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  4158. var name = vertex + "+" + fragment + "@" + defines;
  4159. if (this._compiledEffects[name]) {
  4160. return this._compiledEffects[name];
  4161. }
  4162. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  4163. effect._key = name;
  4164. this._compiledEffects[name] = effect;
  4165. return effect;
  4166. };
  4167. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  4168. if (uniformsNames === void 0) { uniformsNames = []; }
  4169. if (samplers === void 0) { samplers = []; }
  4170. if (defines === void 0) { defines = ""; }
  4171. return this.createEffect({
  4172. vertex: "particles",
  4173. fragmentElement: fragmentName
  4174. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  4175. };
  4176. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  4177. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  4178. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  4179. var shaderProgram = this._gl.createProgram();
  4180. this._gl.attachShader(shaderProgram, vertexShader);
  4181. this._gl.attachShader(shaderProgram, fragmentShader);
  4182. this._gl.linkProgram(shaderProgram);
  4183. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  4184. if (!linked) {
  4185. var error = this._gl.getProgramInfoLog(shaderProgram);
  4186. if (error) {
  4187. throw new Error(error);
  4188. }
  4189. }
  4190. this._gl.deleteShader(vertexShader);
  4191. this._gl.deleteShader(fragmentShader);
  4192. return shaderProgram;
  4193. };
  4194. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  4195. var results = [];
  4196. for (var index = 0; index < uniformsNames.length; index++) {
  4197. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  4198. }
  4199. return results;
  4200. };
  4201. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  4202. var results = [];
  4203. for (var index = 0; index < attributesNames.length; index++) {
  4204. try {
  4205. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  4206. }
  4207. catch (e) {
  4208. results.push(-1);
  4209. }
  4210. }
  4211. return results;
  4212. };
  4213. Engine.prototype.enableEffect = function (effect) {
  4214. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  4215. if (effect && effect.onBind) {
  4216. effect.onBind(effect);
  4217. }
  4218. return;
  4219. }
  4220. this._vertexAttribArrays = this._vertexAttribArrays || [];
  4221. // Use program
  4222. this._gl.useProgram(effect.getProgram());
  4223. for (var i in this._vertexAttribArrays) {
  4224. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  4225. continue;
  4226. }
  4227. this._vertexAttribArrays[i] = false;
  4228. this._gl.disableVertexAttribArray(i);
  4229. }
  4230. var attributesCount = effect.getAttributesCount();
  4231. for (var index = 0; index < attributesCount; index++) {
  4232. // Attributes
  4233. var order = effect.getAttributeLocation(index);
  4234. if (order >= 0) {
  4235. this._vertexAttribArrays[order] = true;
  4236. this._gl.enableVertexAttribArray(order);
  4237. }
  4238. }
  4239. this._currentEffect = effect;
  4240. if (effect.onBind) {
  4241. effect.onBind(effect);
  4242. }
  4243. };
  4244. Engine.prototype.setArray = function (uniform, array) {
  4245. if (!uniform)
  4246. return;
  4247. this._gl.uniform1fv(uniform, array);
  4248. };
  4249. Engine.prototype.setArray2 = function (uniform, array) {
  4250. if (!uniform || array.length % 2 !== 0)
  4251. return;
  4252. this._gl.uniform2fv(uniform, array);
  4253. };
  4254. Engine.prototype.setArray3 = function (uniform, array) {
  4255. if (!uniform || array.length % 3 !== 0)
  4256. return;
  4257. this._gl.uniform3fv(uniform, array);
  4258. };
  4259. Engine.prototype.setArray4 = function (uniform, array) {
  4260. if (!uniform || array.length % 4 !== 0)
  4261. return;
  4262. this._gl.uniform4fv(uniform, array);
  4263. };
  4264. Engine.prototype.setMatrices = function (uniform, matrices) {
  4265. if (!uniform)
  4266. return;
  4267. this._gl.uniformMatrix4fv(uniform, false, matrices);
  4268. };
  4269. Engine.prototype.setMatrix = function (uniform, matrix) {
  4270. if (!uniform)
  4271. return;
  4272. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  4273. };
  4274. Engine.prototype.setFloat = function (uniform, value) {
  4275. if (!uniform)
  4276. return;
  4277. this._gl.uniform1f(uniform, value);
  4278. };
  4279. Engine.prototype.setFloat2 = function (uniform, x, y) {
  4280. if (!uniform)
  4281. return;
  4282. this._gl.uniform2f(uniform, x, y);
  4283. };
  4284. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  4285. if (!uniform)
  4286. return;
  4287. this._gl.uniform3f(uniform, x, y, z);
  4288. };
  4289. Engine.prototype.setBool = function (uniform, bool) {
  4290. if (!uniform)
  4291. return;
  4292. this._gl.uniform1i(uniform, bool);
  4293. };
  4294. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  4295. if (!uniform)
  4296. return;
  4297. this._gl.uniform4f(uniform, x, y, z, w);
  4298. };
  4299. Engine.prototype.setColor3 = function (uniform, color3) {
  4300. if (!uniform)
  4301. return;
  4302. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  4303. };
  4304. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  4305. if (!uniform)
  4306. return;
  4307. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  4308. };
  4309. // States
  4310. Engine.prototype.setState = function (culling, force) {
  4311. // Culling
  4312. if (this._depthCullingState.cull !== culling || force) {
  4313. if (culling) {
  4314. this._depthCullingState.cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  4315. this._depthCullingState.cull = true;
  4316. }
  4317. else {
  4318. this._depthCullingState.cull = false;
  4319. }
  4320. }
  4321. };
  4322. Engine.prototype.setDepthBuffer = function (enable) {
  4323. this._depthCullingState.depthTest = enable;
  4324. };
  4325. Engine.prototype.getDepthWrite = function () {
  4326. return this._depthCullingState.depthMask;
  4327. };
  4328. Engine.prototype.setDepthWrite = function (enable) {
  4329. this._depthCullingState.depthMask = enable;
  4330. };
  4331. Engine.prototype.setColorWrite = function (enable) {
  4332. this._gl.colorMask(enable, enable, enable, enable);
  4333. };
  4334. Engine.prototype.setAlphaMode = function (mode) {
  4335. switch (mode) {
  4336. case Engine.ALPHA_DISABLE:
  4337. this.setDepthWrite(true);
  4338. this._alphaState.alphaBlend = false;
  4339. break;
  4340. case Engine.ALPHA_COMBINE:
  4341. this.setDepthWrite(false);
  4342. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  4343. this._alphaState.alphaBlend = true;
  4344. break;
  4345. case Engine.ALPHA_ADD:
  4346. this.setDepthWrite(false);
  4347. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  4348. this._alphaState.alphaBlend = true;
  4349. break;
  4350. }
  4351. this._alphaMode = mode;
  4352. };
  4353. Engine.prototype.getAlphaMode = function () {
  4354. return this._alphaMode;
  4355. };
  4356. Engine.prototype.setAlphaTesting = function (enable) {
  4357. this._alphaTest = enable;
  4358. };
  4359. Engine.prototype.getAlphaTesting = function () {
  4360. return this._alphaTest;
  4361. };
  4362. // Textures
  4363. Engine.prototype.wipeCaches = function () {
  4364. this._activeTexturesCache = [];
  4365. this._currentEffect = null;
  4366. this._depthCullingState.reset();
  4367. this._alphaState.reset();
  4368. this._cachedVertexBuffers = null;
  4369. this._cachedIndexBuffer = null;
  4370. this._cachedEffectForVertexBuffers = null;
  4371. };
  4372. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  4373. var gl = this._gl;
  4374. gl.bindTexture(gl.TEXTURE_2D, texture);
  4375. var magFilter = gl.NEAREST;
  4376. var minFilter = gl.NEAREST;
  4377. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  4378. magFilter = gl.LINEAR;
  4379. minFilter = gl.LINEAR;
  4380. }
  4381. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  4382. magFilter = gl.LINEAR;
  4383. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  4384. }
  4385. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  4386. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  4387. gl.bindTexture(gl.TEXTURE_2D, null);
  4388. texture.samplingMode = samplingMode;
  4389. };
  4390. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  4391. var _this = this;
  4392. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  4393. if (onLoad === void 0) { onLoad = null; }
  4394. if (onError === void 0) { onError = null; }
  4395. if (buffer === void 0) { buffer = null; }
  4396. var texture = this._gl.createTexture();
  4397. var extension;
  4398. var fromData = false;
  4399. if (url.substr(0, 5) === "data:") {
  4400. fromData = true;
  4401. }
  4402. if (!fromData)
  4403. extension = url.substr(url.length - 4, 4).toLowerCase();
  4404. else {
  4405. var oldUrl = url;
  4406. fromData = oldUrl.split(':');
  4407. url = oldUrl;
  4408. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  4409. }
  4410. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  4411. var isTGA = (extension === ".tga");
  4412. scene._addPendingData(texture);
  4413. texture.url = url;
  4414. texture.noMipmap = noMipmap;
  4415. texture.references = 1;
  4416. this._loadedTexturesCache.push(texture);
  4417. var onerror = function () {
  4418. scene._removePendingData(texture);
  4419. if (onError) {
  4420. onError();
  4421. }
  4422. };
  4423. if (isTGA) {
  4424. var callback = function (arrayBuffer) {
  4425. var data = new Uint8Array(arrayBuffer);
  4426. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  4427. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  4428. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  4429. if (onLoad) {
  4430. onLoad();
  4431. }
  4432. }, samplingMode);
  4433. };
  4434. if (!(fromData instanceof Array))
  4435. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  4436. callback(arrayBuffer);
  4437. }, onerror, scene.database, true);
  4438. else
  4439. callback(buffer);
  4440. }
  4441. else if (isDDS) {
  4442. callback = function (data) {
  4443. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  4444. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  4445. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  4446. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  4447. if (onLoad) {
  4448. onLoad();
  4449. }
  4450. }, samplingMode);
  4451. };
  4452. if (!(fromData instanceof Array))
  4453. BABYLON.Tools.LoadFile(url, function (data) {
  4454. callback(data);
  4455. }, onerror, scene.database, true);
  4456. else
  4457. callback(buffer);
  4458. }
  4459. else {
  4460. var onload = function (img) {
  4461. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  4462. var isPot = (img.width === potWidth && img.height === potHeight);
  4463. if (!isPot) {
  4464. _this._workingCanvas.width = potWidth;
  4465. _this._workingCanvas.height = potHeight;
  4466. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  4467. _this._workingContext.imageSmoothingEnabled = false;
  4468. _this._workingContext.mozImageSmoothingEnabled = false;
  4469. _this._workingContext.oImageSmoothingEnabled = false;
  4470. _this._workingContext.webkitImageSmoothingEnabled = false;
  4471. _this._workingContext.msImageSmoothingEnabled = false;
  4472. }
  4473. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  4474. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  4475. _this._workingContext.imageSmoothingEnabled = true;
  4476. _this._workingContext.mozImageSmoothingEnabled = true;
  4477. _this._workingContext.oImageSmoothingEnabled = true;
  4478. _this._workingContext.webkitImageSmoothingEnabled = true;
  4479. _this._workingContext.msImageSmoothingEnabled = true;
  4480. }
  4481. }
  4482. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  4483. if (onLoad) {
  4484. onLoad();
  4485. }
  4486. }, samplingMode);
  4487. };
  4488. if (!(fromData instanceof Array))
  4489. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  4490. else
  4491. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  4492. }
  4493. return texture;
  4494. };
  4495. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode) {
  4496. var texture = this._gl.createTexture();
  4497. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4498. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  4499. // Format
  4500. var internalFormat = this._gl.RGBA;
  4501. switch (format) {
  4502. case Engine.TEXTUREFORMAT_ALPHA:
  4503. internalFormat = this._gl.ALPHA;
  4504. break;
  4505. case Engine.TEXTUREFORMAT_LUMINANCE:
  4506. internalFormat = this._gl.LUMINANCE;
  4507. break;
  4508. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  4509. internalFormat = this._gl.LUMINANCE_ALPHA;
  4510. break;
  4511. case Engine.TEXTUREFORMAT_RGB:
  4512. internalFormat = this._gl.RGB;
  4513. break;
  4514. case Engine.TEXTUREFORMAT_RGBA:
  4515. internalFormat = this._gl.RGBA;
  4516. break;
  4517. }
  4518. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, width, height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  4519. if (generateMipMaps) {
  4520. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4521. }
  4522. // Filters
  4523. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  4524. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  4525. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  4526. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4527. this._activeTexturesCache = [];
  4528. texture._baseWidth = width;
  4529. texture._baseHeight = height;
  4530. texture._width = width;
  4531. texture._height = height;
  4532. texture.isReady = true;
  4533. texture.references = 1;
  4534. texture.samplingMode = samplingMode;
  4535. this._loadedTexturesCache.push(texture);
  4536. return texture;
  4537. };
  4538. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  4539. var texture = this._gl.createTexture();
  4540. width = BABYLON.Tools.GetExponantOfTwo(width, this._caps.maxTextureSize);
  4541. height = BABYLON.Tools.GetExponantOfTwo(height, this._caps.maxTextureSize);
  4542. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4543. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  4544. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  4545. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  4546. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4547. this._activeTexturesCache = [];
  4548. texture._baseWidth = width;
  4549. texture._baseHeight = height;
  4550. texture._width = width;
  4551. texture._height = height;
  4552. texture.isReady = false;
  4553. texture.generateMipMaps = generateMipMaps;
  4554. texture.references = 1;
  4555. texture.samplingMode = samplingMode;
  4556. this._loadedTexturesCache.push(texture);
  4557. return texture;
  4558. };
  4559. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  4560. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4561. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  4562. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  4563. if (texture.generateMipMaps) {
  4564. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4565. }
  4566. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4567. this._activeTexturesCache = [];
  4568. texture.isReady = true;
  4569. };
  4570. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  4571. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4572. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  4573. // Scale the video if it is a NPOT using the current working canvas
  4574. if (video.videoWidth !== texture._width || video.videoHeight !== texture._height) {
  4575. if (!texture._workingCanvas) {
  4576. texture._workingCanvas = document.createElement("canvas");
  4577. texture._workingContext = texture._workingCanvas.getContext("2d");
  4578. texture._workingCanvas.width = texture._width;
  4579. texture._workingCanvas.height = texture._height;
  4580. }
  4581. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  4582. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  4583. }
  4584. else {
  4585. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  4586. }
  4587. if (texture.generateMipMaps) {
  4588. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4589. }
  4590. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4591. this._activeTexturesCache = [];
  4592. texture.isReady = true;
  4593. };
  4594. Engine.prototype.createRenderTargetTexture = function (size, options) {
  4595. // old version had a "generateMipMaps" arg instead of options.
  4596. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  4597. // in the same way, generateDepthBuffer is defaulted to true
  4598. var generateMipMaps = false;
  4599. var generateDepthBuffer = true;
  4600. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  4601. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  4602. if (options !== undefined) {
  4603. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipmaps;
  4604. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  4605. type = options.type === undefined ? type : options.type;
  4606. if (options.samplingMode !== undefined) {
  4607. samplingMode = options.samplingMode;
  4608. }
  4609. if (type === Engine.TEXTURETYPE_FLOAT) {
  4610. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  4611. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  4612. }
  4613. }
  4614. var gl = this._gl;
  4615. var texture = gl.createTexture();
  4616. gl.bindTexture(gl.TEXTURE_2D, texture);
  4617. var width = size.width || size;
  4618. var height = size.height || size;
  4619. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  4620. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  4621. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  4622. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  4623. }
  4624. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  4625. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  4626. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4627. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4628. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  4629. var depthBuffer;
  4630. // Create the depth buffer
  4631. if (generateDepthBuffer) {
  4632. depthBuffer = gl.createRenderbuffer();
  4633. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  4634. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  4635. }
  4636. // Create the framebuffer
  4637. var framebuffer = gl.createFramebuffer();
  4638. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  4639. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  4640. if (generateDepthBuffer) {
  4641. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  4642. }
  4643. // Unbind
  4644. gl.bindTexture(gl.TEXTURE_2D, null);
  4645. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  4646. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  4647. texture._framebuffer = framebuffer;
  4648. if (generateDepthBuffer) {
  4649. texture._depthBuffer = depthBuffer;
  4650. }
  4651. texture._width = width;
  4652. texture._height = height;
  4653. texture.isReady = true;
  4654. texture.generateMipMaps = generateMipMaps;
  4655. texture.references = 1;
  4656. texture.samplingMode = samplingMode;
  4657. this._activeTexturesCache = [];
  4658. this._loadedTexturesCache.push(texture);
  4659. return texture;
  4660. };
  4661. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  4662. var _this = this;
  4663. var gl = this._gl;
  4664. var texture = gl.createTexture();
  4665. texture.isCube = true;
  4666. texture.url = rootUrl;
  4667. texture.references = 1;
  4668. this._loadedTexturesCache.push(texture);
  4669. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  4670. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  4671. if (isDDS) {
  4672. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  4673. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  4674. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  4675. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  4676. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  4677. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  4678. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  4679. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  4680. }
  4681. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  4682. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  4683. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4684. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4685. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  4686. _this._activeTexturesCache = [];
  4687. texture._width = info.width;
  4688. texture._height = info.height;
  4689. texture.isReady = true;
  4690. }, null, null, true);
  4691. }
  4692. else {
  4693. cascadeLoad(rootUrl, scene, function (imgs) {
  4694. var width = BABYLON.Tools.GetExponantOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  4695. var height = width;
  4696. _this._workingCanvas.width = width;
  4697. _this._workingCanvas.height = height;
  4698. var faces = [
  4699. gl.TEXTURE_CUBE_MAP_POSITIVE_X,
  4700. gl.TEXTURE_CUBE_MAP_POSITIVE_Y,
  4701. gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  4702. gl.TEXTURE_CUBE_MAP_NEGATIVE_X,
  4703. gl.TEXTURE_CUBE_MAP_NEGATIVE_Y,
  4704. gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  4705. ];
  4706. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  4707. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  4708. for (var index = 0; index < faces.length; index++) {
  4709. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  4710. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  4711. }
  4712. if (!noMipmap) {
  4713. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  4714. }
  4715. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  4716. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  4717. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4718. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4719. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  4720. _this._activeTexturesCache = [];
  4721. texture._width = width;
  4722. texture._height = height;
  4723. texture.isReady = true;
  4724. }, extensions);
  4725. }
  4726. return texture;
  4727. };
  4728. Engine.prototype._releaseTexture = function (texture) {
  4729. var gl = this._gl;
  4730. if (texture._framebuffer) {
  4731. gl.deleteFramebuffer(texture._framebuffer);
  4732. }
  4733. if (texture._depthBuffer) {
  4734. gl.deleteRenderbuffer(texture._depthBuffer);
  4735. }
  4736. gl.deleteTexture(texture);
  4737. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  4738. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4739. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4740. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  4741. this._activeTexturesCache[channel] = null;
  4742. }
  4743. var index = this._loadedTexturesCache.indexOf(texture);
  4744. if (index !== -1) {
  4745. this._loadedTexturesCache.splice(index, 1);
  4746. }
  4747. };
  4748. Engine.prototype.bindSamplers = function (effect) {
  4749. this._gl.useProgram(effect.getProgram());
  4750. var samplers = effect.getSamplers();
  4751. for (var index = 0; index < samplers.length; index++) {
  4752. var uniform = effect.getUniform(samplers[index]);
  4753. this._gl.uniform1i(uniform, index);
  4754. }
  4755. this._currentEffect = null;
  4756. };
  4757. Engine.prototype._bindTexture = function (channel, texture) {
  4758. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4759. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4760. this._activeTexturesCache[channel] = null;
  4761. };
  4762. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  4763. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  4764. };
  4765. Engine.prototype.setTexture = function (channel, texture) {
  4766. if (channel < 0) {
  4767. return;
  4768. }
  4769. // Not ready?
  4770. if (!texture || !texture.isReady()) {
  4771. if (this._activeTexturesCache[channel] != null) {
  4772. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4773. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4774. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  4775. this._activeTexturesCache[channel] = null;
  4776. }
  4777. return;
  4778. }
  4779. // Video
  4780. if (texture instanceof BABYLON.VideoTexture) {
  4781. if (texture.update()) {
  4782. this._activeTexturesCache[channel] = null;
  4783. }
  4784. }
  4785. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  4786. texture.delayLoad();
  4787. return;
  4788. }
  4789. if (this._activeTexturesCache[channel] === texture) {
  4790. return;
  4791. }
  4792. this._activeTexturesCache[channel] = texture;
  4793. var internalTexture = texture.getInternalTexture();
  4794. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4795. if (internalTexture.isCube) {
  4796. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  4797. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  4798. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  4799. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  4800. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  4801. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  4802. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  4803. }
  4804. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  4805. }
  4806. else {
  4807. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  4808. if (internalTexture._cachedWrapU !== texture.wrapU) {
  4809. internalTexture._cachedWrapU = texture.wrapU;
  4810. switch (texture.wrapU) {
  4811. case BABYLON.Texture.WRAP_ADDRESSMODE:
  4812. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  4813. break;
  4814. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  4815. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  4816. break;
  4817. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  4818. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  4819. break;
  4820. }
  4821. }
  4822. if (internalTexture._cachedWrapV !== texture.wrapV) {
  4823. internalTexture._cachedWrapV = texture.wrapV;
  4824. switch (texture.wrapV) {
  4825. case BABYLON.Texture.WRAP_ADDRESSMODE:
  4826. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  4827. break;
  4828. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  4829. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  4830. break;
  4831. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  4832. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  4833. break;
  4834. }
  4835. }
  4836. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  4837. }
  4838. };
  4839. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  4840. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  4841. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== texture.anisotropicFilteringLevel) {
  4842. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropicFilteringLevel, this._caps.maxAnisotropy));
  4843. texture._cachedAnisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  4844. }
  4845. };
  4846. Engine.prototype.readPixels = function (x, y, width, height) {
  4847. var data = new Uint8Array(height * width * 4);
  4848. this._gl.readPixels(0, 0, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  4849. return data;
  4850. };
  4851. // Dispose
  4852. Engine.prototype.dispose = function () {
  4853. this.hideLoadingUI();
  4854. this.stopRenderLoop();
  4855. while (this.scenes.length) {
  4856. this.scenes[0].dispose();
  4857. }
  4858. // Release audio engine
  4859. Engine.audioEngine.dispose();
  4860. for (var name in this._compiledEffects) {
  4861. this._gl.deleteProgram(this._compiledEffects[name]._program);
  4862. }
  4863. for (var i in this._vertexAttribArrays) {
  4864. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  4865. continue;
  4866. }
  4867. this._gl.disableVertexAttribArray(i);
  4868. }
  4869. // Events
  4870. window.removeEventListener("blur", this._onBlur);
  4871. window.removeEventListener("focus", this._onFocus);
  4872. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  4873. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  4874. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  4875. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  4876. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  4877. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  4878. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  4879. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  4880. };
  4881. // Loading screen
  4882. Engine.prototype.displayLoadingUI = function () {
  4883. var _this = this;
  4884. this._loadingDiv = document.createElement("div");
  4885. this._loadingDiv.style.opacity = "0";
  4886. this._loadingDiv.style.transition = "opacity 1.5s ease";
  4887. // Loading text
  4888. this._loadingTextDiv = document.createElement("div");
  4889. this._loadingTextDiv.style.position = "absolute";
  4890. this._loadingTextDiv.style.left = "0";
  4891. this._loadingTextDiv.style.top = "50%";
  4892. this._loadingTextDiv.style.marginTop = "80px";
  4893. this._loadingTextDiv.style.width = "100%";
  4894. this._loadingTextDiv.style.height = "20px";
  4895. this._loadingTextDiv.style.fontFamily = "Arial";
  4896. this._loadingTextDiv.style.fontSize = "14px";
  4897. this._loadingTextDiv.style.color = "white";
  4898. this._loadingTextDiv.style.textAlign = "center";
  4899. this._loadingTextDiv.innerHTML = "Loading";
  4900. this._loadingDiv.appendChild(this._loadingTextDiv);
  4901. // Loading img
  4902. var imgBack = new Image();
  4903. imgBack.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAYAAABw4pVUAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAYdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuM4zml1AAAARbSURBVHhe7Z09aFNRFMc716kuLrq4FdyLq4Wi4CAoRQcR0UJBUBdRiuLSIYMo6CA4FF2sgw6CFAdFUOpSQYcWO4hD26UQCfXrIQrx/JJzw1OSWq3NPeL/B4Fy+0jg/HO+7j3vpUcI8b/Q39+/49ihfWdPHT94Yf/e3Se3bd263f8lus218TPn6vV6Ya8Wi/MzNRNmj18iusX9W1evmP1/EKNEIVG6CMbG6E3bt+fT++pHha8NoHdT72bLE8NDg7tGU64gLLndV4Wc4m8j/pS+vr4tGB/DT16v3Fyr8dvBe/jbit8BL0AES9LX1iPAz+BR/hFiLVCynj95dPzNy6fv3IZ/k4L3948Sq7FzYGBg4vLFGxitabuOFCbWNKGrMnbiUuo18KaV6tIHv6YtvL9/nOgE31jCktmrY7k6+/zhE4yP4Vf7hiNqh/BWWEl8mzDol4p22Lf7cIdvdUMEvv0Y2S9fE5S1hLzpqTsPkiep//gFGPnR3Yl7GL5p/xYFBrTwM+iXio3GqpwDGL5p/xYNIX7XG8Q6IJRgdIzf1KBBgafII7oMidhyQtVFaMA2Bt7il4huQRhaXphbcR2g4RXqBzKAGHiCCwGFVUAj/m/RTRDj29cvn10I0PZ3LghH5f4CL1EFlQmqqXK3jDDKFxmhQ3Yt6oQseUZGKmMnTpsOqc8o1F9kBOMjQlOLeqEeIyOc6JV6jYLJD/+XyIFvnzdgl9aXRQ5I2qZDK1SpospMqaoqON/wZZGDciLnMMiXRS7IF4hhqMTNTdk7CFu+LHLhR7BQqBvPDJUUQqCGvCMATHUgBmhWNgApmdOda9YpM+VwRYfuyyIXDK8hBlilNerLIheMZCKGwlUAyru6GlwOgPUbRxADdJ9FAChxXY864viyyEXqPxhc0M2TAfAbatSdRyHtXymhByEdRnE3ky+JnHAIhSA0h74kckETmHoQbSgGwJrCIRMEPSRIBCRIMAhZaYhaggQhJXUJEoRU9mofKwh+F22dLRRfEjlJM7w6KQwCoQpBOKTyJZETjmwRxKqtGV8SOSkNOGjKPQppBEgDDkFgpxdBVGkFgaYQQXRIFQSObk0P5ZFIpAZRHXsQ0r0hCluBWKkuvVbYCkQaCdL5ehBScudJP4yY+rLISdps1NBDEJKXMMmoSfggWC4ZQRR17oFYXph7hSiquIKQ+hJGTX1J5MYSPD/GVdNzsgLBwZVCVyAQAkF0ohiI/c1fS6tNXq9UfEnkhudmIQolsS+J3Hh/UtNDzQLhj42VKJFInqLwFYiUU5ToA+HdfI0JevUpQUAIn+vSz2lHIuUV/dJOIHhOY/IWVWGBIHQtzs88s9zyWBuTgcBLzGOmeNnfF/QslSDgMeQW85i3DOQxuipxAkCyZ8SIm4Omp+7MMlCB59j6sKZcMoM4iIEoeI2J9AKxrFobZx0v4vYInuHFS4J1GQRCAGaLEYQXfyMML5XSQgghhBBCCCH+cXp6vgNhKpSKX/XdOAAAAABJRU5ErkJggg==";
  4904. imgBack.style.position = "absolute";
  4905. imgBack.style.left = "50%";
  4906. imgBack.style.top = "50%";
  4907. imgBack.style.marginLeft = "-50px";
  4908. imgBack.style.marginTop = "-50px";
  4909. imgBack.style.transition = "transform 1.0s ease";
  4910. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  4911. var deg = 360;
  4912. var onTransitionEnd = function () {
  4913. deg += 360;
  4914. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  4915. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  4916. };
  4917. imgBack.addEventListener("transitionend", onTransitionEnd);
  4918. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  4919. this._loadingDiv.appendChild(imgBack);
  4920. // front image
  4921. var imgFront = new Image();
  4922. imgFront.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAYAAABw4pVUAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAYdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuM4zml1AAAAYJSURBVHhe7Zy/qx1FFMff/2Av2Nvbi4WFiiAEY/OQ2IgQsbCJQoqkCAgpFLXyoZURLfwBIiIpgqZJoYQYlWelNsIrNOxDJcrzfHe+G97dnTl75u7euzv7zgcWHrlnZmfOmXPmzI/NjuM4juM4juM4juM4juM4juM4juM4juM45fPic08/uHf5/CvffH7lnT8PfrtxdHS0n3p+/fHGl5+89/prr5599iEWd8bg0rkXHoFyqehKnlxQpjYSDHTm9JMPsGrHylOPPXofvICKXMcIGtXdf/76AYbm6xyNW9e/eAtKC7rbKLXnvHHx5Sf4auc4Ek7OQkFU1Dap/vv37k/wSjblZANFiFIGzw98hhizwqBgs04mCBdQRNCHidoAEtY+lLIvtSdoGFeyql2ZH57HBH4sE7O+o/r9l+8/ZXUni68+2jsHBQQ9qNRGeP/tSxdSYQX/roUcpL4/f3vtM9TD+jTq92n1LQ7jxF1hhGPtwWL3gGccy8JuS1r8sVWBGXNVdSKMYjBGPUJjCzooiGuSpnwlnnOGP2dhHRSLNgpHp2oMKIriK8TmG4Qh/rwW8D6pps9b9im+LDDipXOqMVJrAngBfg9i98gevWKA+/nnCod3Dr5GfaHaDgidVym6HKRjGIkpqthcAVKGxNqBImbEo66kjCih8AOpNmkUmbMuUrR8kEqiU6FvHZLGAPJ71JCYSyhiBqmwFE2GoD6jLGIfDHtG6EzoU4dK21PCqIRMEF0FGRjFzGDtIkXVAdATvsqfT9CJ0JcOFdYiFIsiMlqYy1YOFpQo2OddqBtyEaq9y+efoVh5oPHoROjLKn0j3JIE5Ka8UqZRtGrMnneX6yVofOhDh94MSbznTcpqmDOt1vyQzOgaJAF4F3JBfIXesrNEGWWmjIX7UBZ6jRJbBMLg/DmJiKUGVHleIpnVNTa+jakzkAviJqLhi4MC9XQGBrZeKJZESSrKy7ik0VGFWhQBRDTHIACKQ5l9nAjy75gya4a2w+Jhs0FJdc0xX/GwUbAqFBkZi7QpJ2w16WUbjFyK9MJF3KaoEM74KhVtLrQOrsmRxkbdHEqmSC/c+EuGnIFkjW7Ih2Kr4CCMIvNG2hrrgLpCjiFloooYCjyYrzCRyvhyBthkIPuQtsZGdnbMTezyDiU71KTC5zr7aVsHbsz2tllrEkS5UHwU1tq1HbtPW4UbeB0O7xx8R5EsMJql+BheUmHjkNVmIRP7LutoM3+D4O4tG7vCkNO9ESZ4lL3J6rKRMPx4qKbD/A0icf8CG7tC7kTahnMTwleuYSrsS7GatRAvfZh1tTm5BmmQCdZ8a0Sefe28xUrRBkmFLKy8KTIKUDRX0Y1xagPgwbaIdeFnQULmKak3xvwNMkVGgok/N5XNoehJvejRlCDl9escI28dJU0tZ++nBTJE9mEF647x5Ehbo4s5hDOKFIU0PdofeA5F5k1q63zIWmQqNI/P3ZubjFTqKxQ3jyjHAOX0RdlgVO9hzRFpczRcjZ3Gbxxpc7Qj6+5pTYF2OFXawNI+yDGf1k2NcvOlzBQeDQ/t7zD7DsEDpJ2xATXaNtDWUS4IzP4DS2ljajAVu57SUkYw245ptxZxA5JiZaJ0DswudGn3kYUy54426EjoT4dZfYbccxC2nI92cDkZHQr96jD4AGkMDKeSy/COBsRe6VTSKFN6irLeaCh3IteQjt1E5+oudsG/b/2DfZ5AqsYo8vMDK9LB1HzSsLWvlGThdxXvC6+NsqyPPWP0pMINtbdsajfVeC6f/GZ+cdAofQoB1d+Hf9waY98I7+RXWab3Lt4zYkjHtTnlOLXHYMsCh1zWeQYehu1zfNPOOiys/d91LAKEBSgh6MJMbSA82AaHofDgAIwbgvVvlLNS11nModMm4UZergLHZBZrodmBuA3lBB1thdorSjkOmATMDwg/UBQVtglqQyx6fbEJ+H3IWIapjYAjAfeIgeCMHldueJvFaqDaAHhwf8qNsEEQ1iQbOoUUGIbCLRc8+Bvfp4jyd2FEijuO4ziO4ziO4ziO4ziO4ziO4ziO4ziOUzw7O/8D0P7rcZ/GEboAAAAASUVORK5CYII=";
  4923. imgFront.style.position = "absolute";
  4924. imgFront.style.left = "50%";
  4925. imgFront.style.top = "50%";
  4926. imgFront.style.marginLeft = "-50px";
  4927. imgFront.style.marginTop = "-50px";
  4928. this._loadingDiv.appendChild(imgFront);
  4929. // Resize
  4930. this._resizeLoadingUI = function () {
  4931. var canvasRect = _this.getRenderingCanvasClientRect();
  4932. _this._loadingDiv.style.position = "absolute";
  4933. _this._loadingDiv.style.left = canvasRect.left + "px";
  4934. _this._loadingDiv.style.top = canvasRect.top + "px";
  4935. _this._loadingDiv.style.width = canvasRect.width + "px";
  4936. _this._loadingDiv.style.height = canvasRect.height + "px";
  4937. };
  4938. this._resizeLoadingUI();
  4939. window.addEventListener("resize", this._resizeLoadingUI);
  4940. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  4941. document.body.appendChild(this._loadingDiv);
  4942. setTimeout(function () {
  4943. _this._loadingDiv.style.opacity = "1";
  4944. imgBack.style.transform = "rotateZ(360deg)";
  4945. imgBack.style.webkitTransform = "rotateZ(360deg)";
  4946. }, 0);
  4947. };
  4948. Object.defineProperty(Engine.prototype, "loadingUIText", {
  4949. set: function (text) {
  4950. if (!this._loadingDiv) {
  4951. return;
  4952. }
  4953. this._loadingTextDiv.innerHTML = text;
  4954. },
  4955. enumerable: true,
  4956. configurable: true
  4957. });
  4958. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  4959. get: function () {
  4960. return this._loadingDivBackgroundColor;
  4961. },
  4962. set: function (color) {
  4963. this._loadingDivBackgroundColor = color;
  4964. if (!this._loadingDiv) {
  4965. return;
  4966. }
  4967. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  4968. },
  4969. enumerable: true,
  4970. configurable: true
  4971. });
  4972. Engine.prototype.hideLoadingUI = function () {
  4973. var _this = this;
  4974. if (!this._loadingDiv) {
  4975. return;
  4976. }
  4977. var onTransitionEnd = function () {
  4978. if (!_this._loadingDiv) {
  4979. return;
  4980. }
  4981. document.body.removeChild(_this._loadingDiv);
  4982. window.removeEventListener("resize", _this._resizeLoadingUI);
  4983. _this._loadingDiv = null;
  4984. };
  4985. this._loadingDiv.style.opacity = "0";
  4986. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  4987. };
  4988. // FPS
  4989. Engine.prototype.getFps = function () {
  4990. return this.fps;
  4991. };
  4992. Engine.prototype.getDeltaTime = function () {
  4993. return this.deltaTime;
  4994. };
  4995. Engine.prototype._measureFps = function () {
  4996. this.previousFramesDuration.push(BABYLON.Tools.Now);
  4997. var length = this.previousFramesDuration.length;
  4998. if (length >= 2) {
  4999. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  5000. }
  5001. if (length >= this.fpsRange) {
  5002. if (length > this.fpsRange) {
  5003. this.previousFramesDuration.splice(0, 1);
  5004. length = this.previousFramesDuration.length;
  5005. }
  5006. var sum = 0;
  5007. for (var id = 0; id < length - 1; id++) {
  5008. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  5009. }
  5010. this.fps = 1000.0 / (sum / (length - 1));
  5011. }
  5012. };
  5013. // Statics
  5014. Engine.isSupported = function () {
  5015. try {
  5016. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  5017. if (navigator.isCocoonJS) {
  5018. return true;
  5019. }
  5020. var tempcanvas = document.createElement("canvas");
  5021. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  5022. return gl != null && !!window.WebGLRenderingContext;
  5023. }
  5024. catch (e) {
  5025. return false;
  5026. }
  5027. };
  5028. // Const statics
  5029. Engine._ALPHA_DISABLE = 0;
  5030. Engine._ALPHA_ADD = 1;
  5031. Engine._ALPHA_COMBINE = 2;
  5032. Engine._DELAYLOADSTATE_NONE = 0;
  5033. Engine._DELAYLOADSTATE_LOADED = 1;
  5034. Engine._DELAYLOADSTATE_LOADING = 2;
  5035. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  5036. Engine._TEXTUREFORMAT_ALPHA = 0;
  5037. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  5038. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  5039. Engine._TEXTUREFORMAT_RGB = 4;
  5040. Engine._TEXTUREFORMAT_RGBA = 4;
  5041. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  5042. Engine._TEXTURETYPE_FLOAT = 1;
  5043. // Updatable statics so stick with vars here
  5044. Engine.Epsilon = 0.001;
  5045. Engine.CollisionsEpsilon = 0.001;
  5046. Engine.ShadersRepository = "Babylon/Shaders/";
  5047. return Engine;
  5048. })();
  5049. BABYLON.Engine = Engine;
  5050. })(BABYLON || (BABYLON = {}));
  5051. //# sourceMappingURL=babylon.engine.js.mapvar BABYLON;
  5052. (function (BABYLON) {
  5053. /**
  5054. * Node is the basic class for all scene objects (Mesh, Light Camera).
  5055. */
  5056. var Node = (function () {
  5057. /**
  5058. * @constructor
  5059. * @param {string} name - the name and id to be given to this node
  5060. * @param {BABYLON.Scene} the scene this node will be added to
  5061. */
  5062. function Node(name, scene) {
  5063. this.state = "";
  5064. this.animations = new Array();
  5065. this._childrenFlag = -1;
  5066. this._isEnabled = true;
  5067. this._isReady = true;
  5068. this._currentRenderId = -1;
  5069. this.name = name;
  5070. this.id = name;
  5071. this._scene = scene;
  5072. this._initCache();
  5073. }
  5074. Node.prototype.getScene = function () {
  5075. return this._scene;
  5076. };
  5077. Node.prototype.getEngine = function () {
  5078. return this._scene.getEngine();
  5079. };
  5080. // override it in derived class
  5081. Node.prototype.getWorldMatrix = function () {
  5082. return BABYLON.Matrix.Identity();
  5083. };
  5084. // override it in derived class if you add new variables to the cache
  5085. // and call the parent class method
  5086. Node.prototype._initCache = function () {
  5087. this._cache = {};
  5088. this._cache.parent = undefined;
  5089. };
  5090. Node.prototype.updateCache = function (force) {
  5091. if (!force && this.isSynchronized())
  5092. return;
  5093. this._cache.parent = this.parent;
  5094. this._updateCache();
  5095. };
  5096. // override it in derived class if you add new variables to the cache
  5097. // and call the parent class method if !ignoreParentClass
  5098. Node.prototype._updateCache = function (ignoreParentClass) {
  5099. };
  5100. // override it in derived class if you add new variables to the cache
  5101. Node.prototype._isSynchronized = function () {
  5102. return true;
  5103. };
  5104. Node.prototype.isSynchronizedWithParent = function () {
  5105. return this.parent ? this.parent._currentRenderId <= this._currentRenderId : true;
  5106. };
  5107. Node.prototype.isSynchronized = function (updateCache) {
  5108. var check = this.hasNewParent();
  5109. check = check || !this.isSynchronizedWithParent();
  5110. check = check || !this._isSynchronized();
  5111. if (updateCache)
  5112. this.updateCache(true);
  5113. return !check;
  5114. };
  5115. Node.prototype.hasNewParent = function (update) {
  5116. if (this._cache.parent === this.parent)
  5117. return false;
  5118. if (update)
  5119. this._cache.parent = this.parent;
  5120. return true;
  5121. };
  5122. /**
  5123. * Is this node ready to be used/rendered
  5124. * @return {boolean} is it ready
  5125. */
  5126. Node.prototype.isReady = function () {
  5127. return this._isReady;
  5128. };
  5129. /**
  5130. * Is this node enabled.
  5131. * If the node has a parent and is enabled, the parent will be inspected as well.
  5132. * @return {boolean} whether this node (and its parent) is enabled.
  5133. * @see setEnabled
  5134. */
  5135. Node.prototype.isEnabled = function () {
  5136. if (!this._isEnabled) {
  5137. return false;
  5138. }
  5139. if (this.parent) {
  5140. return this.parent.isEnabled();
  5141. }
  5142. return true;
  5143. };
  5144. /**
  5145. * Set the enabled state of this node.
  5146. * @param {boolean} value - the new enabled state
  5147. * @see isEnabled
  5148. */
  5149. Node.prototype.setEnabled = function (value) {
  5150. this._isEnabled = value;
  5151. };
  5152. /**
  5153. * Is this node a descendant of the given node.
  5154. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  5155. * @param {BABYLON.Node} ancestor - The parent node to inspect
  5156. * @see parent
  5157. */
  5158. Node.prototype.isDescendantOf = function (ancestor) {
  5159. if (this.parent) {
  5160. if (this.parent === ancestor) {
  5161. return true;
  5162. }
  5163. return this.parent.isDescendantOf(ancestor);
  5164. }
  5165. return false;
  5166. };
  5167. Node.prototype._getDescendants = function (list, results) {
  5168. for (var index = 0; index < list.length; index++) {
  5169. var item = list[index];
  5170. if (item.isDescendantOf(this)) {
  5171. results.push(item);
  5172. }
  5173. }
  5174. };
  5175. /**
  5176. * Will return all nodes that have this node as parent.
  5177. * @return {BABYLON.Node[]} all children nodes of all types.
  5178. */
  5179. Node.prototype.getDescendants = function () {
  5180. var results = [];
  5181. this._getDescendants(this._scene.meshes, results);
  5182. this._getDescendants(this._scene.lights, results);
  5183. this._getDescendants(this._scene.cameras, results);
  5184. return results;
  5185. };
  5186. Node.prototype._setReady = function (state) {
  5187. if (state == this._isReady) {
  5188. return;
  5189. }
  5190. if (!state) {
  5191. this._isReady = false;
  5192. return;
  5193. }
  5194. this._isReady = true;
  5195. if (this.onReady) {
  5196. this.onReady(this);
  5197. }
  5198. };
  5199. return Node;
  5200. })();
  5201. BABYLON.Node = Node;
  5202. })(BABYLON || (BABYLON = {}));
  5203. //# sourceMappingURL=babylon.node.js.mapvar BABYLON;
  5204. (function (BABYLON) {
  5205. var BoundingSphere = (function () {
  5206. function BoundingSphere(minimum, maximum) {
  5207. this.minimum = minimum;
  5208. this.maximum = maximum;
  5209. this._tempRadiusVector = BABYLON.Vector3.Zero();
  5210. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  5211. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  5212. this.radius = distance * 0.5;
  5213. this.centerWorld = BABYLON.Vector3.Zero();
  5214. this._update(BABYLON.Matrix.Identity());
  5215. }
  5216. // Methods
  5217. BoundingSphere.prototype._update = function (world) {
  5218. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  5219. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  5220. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  5221. };
  5222. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  5223. for (var i = 0; i < 6; i++) {
  5224. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  5225. return false;
  5226. }
  5227. return true;
  5228. };
  5229. BoundingSphere.prototype.intersectsPoint = function (point) {
  5230. var x = this.centerWorld.x - point.x;
  5231. var y = this.centerWorld.y - point.y;
  5232. var z = this.centerWorld.z - point.z;
  5233. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  5234. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  5235. return false;
  5236. return true;
  5237. };
  5238. // Statics
  5239. BoundingSphere.Intersects = function (sphere0, sphere1) {
  5240. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  5241. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  5242. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  5243. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  5244. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  5245. return false;
  5246. return true;
  5247. };
  5248. return BoundingSphere;
  5249. })();
  5250. BABYLON.BoundingSphere = BoundingSphere;
  5251. })(BABYLON || (BABYLON = {}));
  5252. //# sourceMappingURL=babylon.boundingSphere.js.mapvar BABYLON;
  5253. (function (BABYLON) {
  5254. var BoundingBox = (function () {
  5255. function BoundingBox(minimum, maximum) {
  5256. this.minimum = minimum;
  5257. this.maximum = maximum;
  5258. this.vectors = new Array();
  5259. this.vectorsWorld = new Array();
  5260. // Bounding vectors
  5261. this.vectors.push(this.minimum.clone());
  5262. this.vectors.push(this.maximum.clone());
  5263. this.vectors.push(this.minimum.clone());
  5264. this.vectors[2].x = this.maximum.x;
  5265. this.vectors.push(this.minimum.clone());
  5266. this.vectors[3].y = this.maximum.y;
  5267. this.vectors.push(this.minimum.clone());
  5268. this.vectors[4].z = this.maximum.z;
  5269. this.vectors.push(this.maximum.clone());
  5270. this.vectors[5].z = this.minimum.z;
  5271. this.vectors.push(this.maximum.clone());
  5272. this.vectors[6].x = this.minimum.x;
  5273. this.vectors.push(this.maximum.clone());
  5274. this.vectors[7].y = this.minimum.y;
  5275. // OBB
  5276. this.center = this.maximum.add(this.minimum).scale(0.5);
  5277. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  5278. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  5279. for (var index = 0; index < this.vectors.length; index++) {
  5280. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  5281. }
  5282. this.minimumWorld = BABYLON.Vector3.Zero();
  5283. this.maximumWorld = BABYLON.Vector3.Zero();
  5284. this._update(BABYLON.Matrix.Identity());
  5285. }
  5286. // Methods
  5287. BoundingBox.prototype.getWorldMatrix = function () {
  5288. return this._worldMatrix;
  5289. };
  5290. BoundingBox.prototype._update = function (world) {
  5291. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  5292. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  5293. for (var index = 0; index < this.vectors.length; index++) {
  5294. var v = this.vectorsWorld[index];
  5295. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  5296. if (v.x < this.minimumWorld.x)
  5297. this.minimumWorld.x = v.x;
  5298. if (v.y < this.minimumWorld.y)
  5299. this.minimumWorld.y = v.y;
  5300. if (v.z < this.minimumWorld.z)
  5301. this.minimumWorld.z = v.z;
  5302. if (v.x > this.maximumWorld.x)
  5303. this.maximumWorld.x = v.x;
  5304. if (v.y > this.maximumWorld.y)
  5305. this.maximumWorld.y = v.y;
  5306. if (v.z > this.maximumWorld.z)
  5307. this.maximumWorld.z = v.z;
  5308. }
  5309. // OBB
  5310. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  5311. this.center.scaleInPlace(0.5);
  5312. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  5313. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  5314. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  5315. this._worldMatrix = world;
  5316. };
  5317. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  5318. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  5319. };
  5320. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  5321. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  5322. };
  5323. BoundingBox.prototype.intersectsPoint = function (point) {
  5324. var delta = BABYLON.Engine.Epsilon;
  5325. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  5326. return false;
  5327. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  5328. return false;
  5329. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  5330. return false;
  5331. return true;
  5332. };
  5333. BoundingBox.prototype.intersectsSphere = function (sphere) {
  5334. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  5335. };
  5336. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  5337. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  5338. return false;
  5339. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  5340. return false;
  5341. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  5342. return false;
  5343. return true;
  5344. };
  5345. // Statics
  5346. BoundingBox.Intersects = function (box0, box1) {
  5347. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  5348. return false;
  5349. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  5350. return false;
  5351. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  5352. return false;
  5353. return true;
  5354. };
  5355. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  5356. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  5357. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  5358. return (num <= (sphereRadius * sphereRadius));
  5359. };
  5360. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  5361. for (var p = 0; p < 6; p++) {
  5362. for (var i = 0; i < 8; i++) {
  5363. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  5364. return false;
  5365. }
  5366. }
  5367. }
  5368. return true;
  5369. };
  5370. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  5371. for (var p = 0; p < 6; p++) {
  5372. var inCount = 8;
  5373. for (var i = 0; i < 8; i++) {
  5374. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  5375. --inCount;
  5376. }
  5377. else {
  5378. break;
  5379. }
  5380. }
  5381. if (inCount === 0)
  5382. return false;
  5383. }
  5384. return true;
  5385. };
  5386. return BoundingBox;
  5387. })();
  5388. BABYLON.BoundingBox = BoundingBox;
  5389. })(BABYLON || (BABYLON = {}));
  5390. //# sourceMappingURL=babylon.boundingBox.js.mapvar BABYLON;
  5391. (function (BABYLON) {
  5392. var computeBoxExtents = function (axis, box) {
  5393. var p = BABYLON.Vector3.Dot(box.center, axis);
  5394. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  5395. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  5396. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  5397. var r = r0 + r1 + r2;
  5398. return {
  5399. min: p - r,
  5400. max: p + r
  5401. };
  5402. };
  5403. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  5404. var axisOverlap = function (axis, box0, box1) {
  5405. var result0 = computeBoxExtents(axis, box0);
  5406. var result1 = computeBoxExtents(axis, box1);
  5407. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  5408. };
  5409. var BoundingInfo = (function () {
  5410. function BoundingInfo(minimum, maximum) {
  5411. this.minimum = minimum;
  5412. this.maximum = maximum;
  5413. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  5414. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  5415. }
  5416. // Methods
  5417. BoundingInfo.prototype._update = function (world) {
  5418. this.boundingBox._update(world);
  5419. this.boundingSphere._update(world);
  5420. };
  5421. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  5422. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  5423. return false;
  5424. return this.boundingBox.isInFrustum(frustumPlanes);
  5425. };
  5426. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  5427. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  5428. };
  5429. BoundingInfo.prototype._checkCollision = function (collider) {
  5430. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  5431. };
  5432. BoundingInfo.prototype.intersectsPoint = function (point) {
  5433. if (!this.boundingSphere.centerWorld) {
  5434. return false;
  5435. }
  5436. if (!this.boundingSphere.intersectsPoint(point)) {
  5437. return false;
  5438. }
  5439. if (!this.boundingBox.intersectsPoint(point)) {
  5440. return false;
  5441. }
  5442. return true;
  5443. };
  5444. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  5445. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  5446. return false;
  5447. }
  5448. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  5449. return false;
  5450. }
  5451. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  5452. return false;
  5453. }
  5454. if (!precise) {
  5455. return true;
  5456. }
  5457. var box0 = this.boundingBox;
  5458. var box1 = boundingInfo.boundingBox;
  5459. if (!axisOverlap(box0.directions[0], box0, box1))
  5460. return false;
  5461. if (!axisOverlap(box0.directions[1], box0, box1))
  5462. return false;
  5463. if (!axisOverlap(box0.directions[2], box0, box1))
  5464. return false;
  5465. if (!axisOverlap(box1.directions[0], box0, box1))
  5466. return false;
  5467. if (!axisOverlap(box1.directions[1], box0, box1))
  5468. return false;
  5469. if (!axisOverlap(box1.directions[2], box0, box1))
  5470. return false;
  5471. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  5472. return false;
  5473. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  5474. return false;
  5475. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  5476. return false;
  5477. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  5478. return false;
  5479. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  5480. return false;
  5481. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  5482. return false;
  5483. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  5484. return false;
  5485. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  5486. return false;
  5487. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  5488. return false;
  5489. return true;
  5490. };
  5491. return BoundingInfo;
  5492. })();
  5493. BABYLON.BoundingInfo = BoundingInfo;
  5494. })(BABYLON || (BABYLON = {}));
  5495. //# sourceMappingURL=babylon.boundingInfo.js.map
  5496. var BABYLON;
  5497. (function (BABYLON) {
  5498. var Light = (function (_super) {
  5499. __extends(Light, _super);
  5500. function Light(name, scene) {
  5501. _super.call(this, name, scene);
  5502. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  5503. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  5504. this.intensity = 1.0;
  5505. this.range = Number.MAX_VALUE;
  5506. this.includedOnlyMeshes = new Array();
  5507. this.excludedMeshes = new Array();
  5508. this._excludedMeshesIds = new Array();
  5509. this._includedOnlyMeshesIds = new Array();
  5510. scene.lights.push(this);
  5511. }
  5512. Light.prototype.getShadowGenerator = function () {
  5513. return this._shadowGenerator;
  5514. };
  5515. Light.prototype.getAbsolutePosition = function () {
  5516. return BABYLON.Vector3.Zero();
  5517. };
  5518. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  5519. };
  5520. Light.prototype._getWorldMatrix = function () {
  5521. return BABYLON.Matrix.Identity();
  5522. };
  5523. Light.prototype.canAffectMesh = function (mesh) {
  5524. if (!mesh) {
  5525. return true;
  5526. }
  5527. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  5528. return false;
  5529. }
  5530. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  5531. return false;
  5532. }
  5533. return true;
  5534. };
  5535. Light.prototype.getWorldMatrix = function () {
  5536. this._currentRenderId = this.getScene().getRenderId();
  5537. var worldMatrix = this._getWorldMatrix();
  5538. if (this.parent && this.parent.getWorldMatrix) {
  5539. if (!this._parentedWorldMatrix) {
  5540. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  5541. }
  5542. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  5543. return this._parentedWorldMatrix;
  5544. }
  5545. return worldMatrix;
  5546. };
  5547. Light.prototype.dispose = function () {
  5548. if (this._shadowGenerator) {
  5549. this._shadowGenerator.dispose();
  5550. this._shadowGenerator = null;
  5551. }
  5552. // Remove from scene
  5553. var index = this.getScene().lights.indexOf(this);
  5554. this.getScene().lights.splice(index, 1);
  5555. };
  5556. return Light;
  5557. })(BABYLON.Node);
  5558. BABYLON.Light = Light;
  5559. })(BABYLON || (BABYLON = {}));
  5560. //# sourceMappingURL=babylon.light.js.map
  5561. var BABYLON;
  5562. (function (BABYLON) {
  5563. var PointLight = (function (_super) {
  5564. __extends(PointLight, _super);
  5565. function PointLight(name, position, scene) {
  5566. _super.call(this, name, scene);
  5567. this.position = position;
  5568. }
  5569. PointLight.prototype.getAbsolutePosition = function () {
  5570. return this._transformedPosition ? this._transformedPosition : this.position;
  5571. };
  5572. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  5573. if (this.parent && this.parent.getWorldMatrix) {
  5574. if (!this._transformedPosition) {
  5575. this._transformedPosition = BABYLON.Vector3.Zero();
  5576. }
  5577. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  5578. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, 0);
  5579. return;
  5580. }
  5581. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  5582. };
  5583. PointLight.prototype.getShadowGenerator = function () {
  5584. return null;
  5585. };
  5586. PointLight.prototype._getWorldMatrix = function () {
  5587. if (!this._worldMatrix) {
  5588. this._worldMatrix = BABYLON.Matrix.Identity();
  5589. }
  5590. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  5591. return this._worldMatrix;
  5592. };
  5593. return PointLight;
  5594. })(BABYLON.Light);
  5595. BABYLON.PointLight = PointLight;
  5596. })(BABYLON || (BABYLON = {}));
  5597. //# sourceMappingURL=babylon.pointLight.js.map
  5598. var BABYLON;
  5599. (function (BABYLON) {
  5600. var SpotLight = (function (_super) {
  5601. __extends(SpotLight, _super);
  5602. function SpotLight(name, position, direction, angle, exponent, scene) {
  5603. _super.call(this, name, scene);
  5604. this.position = position;
  5605. this.direction = direction;
  5606. this.angle = angle;
  5607. this.exponent = exponent;
  5608. }
  5609. SpotLight.prototype.getAbsolutePosition = function () {
  5610. return this.transformedPosition ? this.transformedPosition : this.position;
  5611. };
  5612. SpotLight.prototype.setDirectionToTarget = function (target) {
  5613. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  5614. return this.direction;
  5615. };
  5616. SpotLight.prototype.computeTransformedPosition = function () {
  5617. if (this.parent && this.parent.getWorldMatrix) {
  5618. if (!this.transformedPosition) {
  5619. this.transformedPosition = BABYLON.Vector3.Zero();
  5620. }
  5621. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  5622. return true;
  5623. }
  5624. return false;
  5625. };
  5626. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  5627. var normalizeDirection;
  5628. if (this.parent && this.parent.getWorldMatrix) {
  5629. if (!this._transformedDirection) {
  5630. this._transformedDirection = BABYLON.Vector3.Zero();
  5631. }
  5632. this.computeTransformedPosition();
  5633. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  5634. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  5635. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  5636. }
  5637. else {
  5638. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  5639. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  5640. }
  5641. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  5642. };
  5643. SpotLight.prototype._getWorldMatrix = function () {
  5644. if (!this._worldMatrix) {
  5645. this._worldMatrix = BABYLON.Matrix.Identity();
  5646. }
  5647. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  5648. return this._worldMatrix;
  5649. };
  5650. return SpotLight;
  5651. })(BABYLON.Light);
  5652. BABYLON.SpotLight = SpotLight;
  5653. })(BABYLON || (BABYLON = {}));
  5654. //# sourceMappingURL=babylon.spotLight.js.map
  5655. var BABYLON;
  5656. (function (BABYLON) {
  5657. var DirectionalLight = (function (_super) {
  5658. __extends(DirectionalLight, _super);
  5659. function DirectionalLight(name, direction, scene) {
  5660. _super.call(this, name, scene);
  5661. this.direction = direction;
  5662. this.position = direction.scale(-1);
  5663. }
  5664. DirectionalLight.prototype.getAbsolutePosition = function () {
  5665. return this.transformedPosition ? this.transformedPosition : this.position;
  5666. };
  5667. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  5668. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  5669. return this.direction;
  5670. };
  5671. DirectionalLight.prototype.computeTransformedPosition = function () {
  5672. if (this.parent && this.parent.getWorldMatrix) {
  5673. if (!this.transformedPosition) {
  5674. this.transformedPosition = BABYLON.Vector3.Zero();
  5675. }
  5676. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  5677. return true;
  5678. }
  5679. return false;
  5680. };
  5681. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  5682. if (this.parent && this.parent.getWorldMatrix) {
  5683. if (!this._transformedDirection) {
  5684. this._transformedDirection = BABYLON.Vector3.Zero();
  5685. }
  5686. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  5687. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  5688. return;
  5689. }
  5690. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  5691. };
  5692. DirectionalLight.prototype._getWorldMatrix = function () {
  5693. if (!this._worldMatrix) {
  5694. this._worldMatrix = BABYLON.Matrix.Identity();
  5695. }
  5696. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  5697. return this._worldMatrix;
  5698. };
  5699. return DirectionalLight;
  5700. })(BABYLON.Light);
  5701. BABYLON.DirectionalLight = DirectionalLight;
  5702. })(BABYLON || (BABYLON = {}));
  5703. //# sourceMappingURL=babylon.directionalLight.js.mapvar BABYLON;
  5704. (function (BABYLON) {
  5705. var ShadowGenerator = (function () {
  5706. function ShadowGenerator(mapSize, light) {
  5707. var _this = this;
  5708. // Members
  5709. this.filter = ShadowGenerator.FILTER_NONE;
  5710. this._darkness = 0;
  5711. this._transparencyShadow = false;
  5712. this._viewMatrix = BABYLON.Matrix.Zero();
  5713. this._projectionMatrix = BABYLON.Matrix.Zero();
  5714. this._transformMatrix = BABYLON.Matrix.Zero();
  5715. this._worldViewProjection = BABYLON.Matrix.Zero();
  5716. this._light = light;
  5717. this._scene = light.getScene();
  5718. light._shadowGenerator = this;
  5719. // Render target
  5720. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false);
  5721. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  5722. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  5723. this._shadowMap.renderParticles = false;
  5724. // Custom render function
  5725. var renderSubMesh = function (subMesh) {
  5726. var mesh = subMesh.getRenderingMesh();
  5727. var scene = _this._scene;
  5728. var engine = scene.getEngine();
  5729. // Culling
  5730. engine.setState(subMesh.getMaterial().backFaceCulling);
  5731. // Managing instances
  5732. var batch = mesh._getInstancesRenderList(subMesh._id);
  5733. if (batch.mustReturn) {
  5734. return;
  5735. }
  5736. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  5737. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  5738. engine.enableEffect(_this._effect);
  5739. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  5740. var material = subMesh.getMaterial();
  5741. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  5742. // Alpha test
  5743. if (material && material.needAlphaTesting()) {
  5744. var alphaTexture = material.getAlphaTestTexture();
  5745. _this._effect.setTexture("diffuseSampler", alphaTexture);
  5746. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  5747. }
  5748. // Bones
  5749. if (mesh.useBones) {
  5750. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  5751. }
  5752. // Draw
  5753. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  5754. }
  5755. else {
  5756. // Need to reset refresh rate of the shadowMap
  5757. _this._shadowMap.resetRefreshCounter();
  5758. }
  5759. };
  5760. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  5761. var index;
  5762. for (index = 0; index < opaqueSubMeshes.length; index++) {
  5763. renderSubMesh(opaqueSubMeshes.data[index]);
  5764. }
  5765. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  5766. renderSubMesh(alphaTestSubMeshes.data[index]);
  5767. }
  5768. if (_this._transparencyShadow) {
  5769. for (index = 0; index < transparentSubMeshes.length; index++) {
  5770. renderSubMesh(transparentSubMeshes.data[index]);
  5771. }
  5772. }
  5773. };
  5774. }
  5775. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  5776. // Static
  5777. get: function () {
  5778. return ShadowGenerator._FILTER_NONE;
  5779. },
  5780. enumerable: true,
  5781. configurable: true
  5782. });
  5783. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  5784. get: function () {
  5785. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  5786. },
  5787. enumerable: true,
  5788. configurable: true
  5789. });
  5790. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  5791. get: function () {
  5792. return ShadowGenerator._FILTER_POISSONSAMPLING;
  5793. },
  5794. enumerable: true,
  5795. configurable: true
  5796. });
  5797. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  5798. get: function () {
  5799. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP;
  5800. },
  5801. set: function (value) {
  5802. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  5803. },
  5804. enumerable: true,
  5805. configurable: true
  5806. });
  5807. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  5808. get: function () {
  5809. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  5810. },
  5811. set: function (value) {
  5812. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  5813. },
  5814. enumerable: true,
  5815. configurable: true
  5816. });
  5817. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  5818. var defines = [];
  5819. if (this.useVarianceShadowMap) {
  5820. defines.push("#define VSM");
  5821. }
  5822. var attribs = [BABYLON.VertexBuffer.PositionKind];
  5823. var mesh = subMesh.getMesh();
  5824. var material = subMesh.getMaterial();
  5825. // Alpha test
  5826. if (material && material.needAlphaTesting()) {
  5827. defines.push("#define ALPHATEST");
  5828. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  5829. attribs.push(BABYLON.VertexBuffer.UVKind);
  5830. defines.push("#define UV1");
  5831. }
  5832. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  5833. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  5834. defines.push("#define UV2");
  5835. }
  5836. }
  5837. // Bones
  5838. if (mesh.useBones) {
  5839. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  5840. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  5841. defines.push("#define BONES");
  5842. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  5843. }
  5844. // Instances
  5845. if (useInstances) {
  5846. defines.push("#define INSTANCES");
  5847. attribs.push("world0");
  5848. attribs.push("world1");
  5849. attribs.push("world2");
  5850. attribs.push("world3");
  5851. }
  5852. // Get correct effect
  5853. var join = defines.join("\n");
  5854. if (this._cachedDefines !== join) {
  5855. this._cachedDefines = join;
  5856. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  5857. }
  5858. return this._effect.isReady();
  5859. };
  5860. ShadowGenerator.prototype.getShadowMap = function () {
  5861. return this._shadowMap;
  5862. };
  5863. ShadowGenerator.prototype.getLight = function () {
  5864. return this._light;
  5865. };
  5866. // Methods
  5867. ShadowGenerator.prototype.getTransformMatrix = function () {
  5868. var lightPosition = this._light.position;
  5869. var lightDirection = this._light.direction;
  5870. if (this._light.computeTransformedPosition()) {
  5871. lightPosition = this._light.transformedPosition;
  5872. }
  5873. if (!this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !lightDirection.equals(this._cachedDirection)) {
  5874. this._cachedPosition = lightPosition.clone();
  5875. this._cachedDirection = lightDirection.clone();
  5876. var activeCamera = this._scene.activeCamera;
  5877. BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  5878. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2.0, 1.0, activeCamera.minZ, activeCamera.maxZ, this._projectionMatrix);
  5879. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  5880. }
  5881. return this._transformMatrix;
  5882. };
  5883. ShadowGenerator.prototype.getDarkness = function () {
  5884. return this._darkness;
  5885. };
  5886. ShadowGenerator.prototype.setDarkness = function (darkness) {
  5887. if (darkness >= 1.0)
  5888. this._darkness = 1.0;
  5889. else if (darkness <= 0.0)
  5890. this._darkness = 0.0;
  5891. else
  5892. this._darkness = darkness;
  5893. };
  5894. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  5895. this._transparencyShadow = hasShadow;
  5896. };
  5897. ShadowGenerator.prototype.dispose = function () {
  5898. this._shadowMap.dispose();
  5899. };
  5900. ShadowGenerator._FILTER_NONE = 0;
  5901. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  5902. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  5903. return ShadowGenerator;
  5904. })();
  5905. BABYLON.ShadowGenerator = ShadowGenerator;
  5906. })(BABYLON || (BABYLON = {}));
  5907. //# sourceMappingURL=babylon.shadowGenerator.js.map
  5908. var BABYLON;
  5909. (function (BABYLON) {
  5910. var HemisphericLight = (function (_super) {
  5911. __extends(HemisphericLight, _super);
  5912. function HemisphericLight(name, direction, scene) {
  5913. _super.call(this, name, scene);
  5914. this.direction = direction;
  5915. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  5916. }
  5917. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  5918. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  5919. return this.direction;
  5920. };
  5921. HemisphericLight.prototype.getShadowGenerator = function () {
  5922. return null;
  5923. };
  5924. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  5925. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  5926. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  5927. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  5928. };
  5929. HemisphericLight.prototype._getWorldMatrix = function () {
  5930. if (!this._worldMatrix) {
  5931. this._worldMatrix = BABYLON.Matrix.Identity();
  5932. }
  5933. return this._worldMatrix;
  5934. };
  5935. return HemisphericLight;
  5936. })(BABYLON.Light);
  5937. BABYLON.HemisphericLight = HemisphericLight;
  5938. })(BABYLON || (BABYLON = {}));
  5939. //# sourceMappingURL=babylon.hemisphericLight.js.mapvar BABYLON;
  5940. (function (BABYLON) {
  5941. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  5942. if (boxMin.x > sphereCenter.x + sphereRadius)
  5943. return false;
  5944. if (sphereCenter.x - sphereRadius > boxMax.x)
  5945. return false;
  5946. if (boxMin.y > sphereCenter.y + sphereRadius)
  5947. return false;
  5948. if (sphereCenter.y - sphereRadius > boxMax.y)
  5949. return false;
  5950. if (boxMin.z > sphereCenter.z + sphereRadius)
  5951. return false;
  5952. if (sphereCenter.z - sphereRadius > boxMax.z)
  5953. return false;
  5954. return true;
  5955. };
  5956. var getLowestRoot = function (a, b, c, maxR) {
  5957. var determinant = b * b - 4.0 * a * c;
  5958. var result = { root: 0, found: false };
  5959. if (determinant < 0)
  5960. return result;
  5961. var sqrtD = Math.sqrt(determinant);
  5962. var r1 = (-b - sqrtD) / (2.0 * a);
  5963. var r2 = (-b + sqrtD) / (2.0 * a);
  5964. if (r1 > r2) {
  5965. var temp = r2;
  5966. r2 = r1;
  5967. r1 = temp;
  5968. }
  5969. if (r1 > 0 && r1 < maxR) {
  5970. result.root = r1;
  5971. result.found = true;
  5972. return result;
  5973. }
  5974. if (r2 > 0 && r2 < maxR) {
  5975. result.root = r2;
  5976. result.found = true;
  5977. return result;
  5978. }
  5979. return result;
  5980. };
  5981. var Collider = (function () {
  5982. function Collider() {
  5983. this.radius = new BABYLON.Vector3(1, 1, 1);
  5984. this.retry = 0;
  5985. this.basePointWorld = BABYLON.Vector3.Zero();
  5986. this.velocityWorld = BABYLON.Vector3.Zero();
  5987. this.normalizedVelocity = BABYLON.Vector3.Zero();
  5988. this._collisionPoint = BABYLON.Vector3.Zero();
  5989. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  5990. this._tempVector = BABYLON.Vector3.Zero();
  5991. this._tempVector2 = BABYLON.Vector3.Zero();
  5992. this._tempVector3 = BABYLON.Vector3.Zero();
  5993. this._tempVector4 = BABYLON.Vector3.Zero();
  5994. this._edge = BABYLON.Vector3.Zero();
  5995. this._baseToVertex = BABYLON.Vector3.Zero();
  5996. this._destinationPoint = BABYLON.Vector3.Zero();
  5997. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  5998. this._displacementVector = BABYLON.Vector3.Zero();
  5999. }
  6000. // Methods
  6001. Collider.prototype._initialize = function (source, dir, e) {
  6002. this.velocity = dir;
  6003. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  6004. this.basePoint = source;
  6005. source.multiplyToRef(this.radius, this.basePointWorld);
  6006. dir.multiplyToRef(this.radius, this.velocityWorld);
  6007. this.velocityWorldLength = this.velocityWorld.length();
  6008. this.epsilon = e;
  6009. this.collisionFound = false;
  6010. };
  6011. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  6012. pa.subtractToRef(point, this._tempVector);
  6013. pb.subtractToRef(point, this._tempVector2);
  6014. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  6015. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  6016. if (d < 0)
  6017. return false;
  6018. pc.subtractToRef(point, this._tempVector3);
  6019. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  6020. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  6021. if (d < 0)
  6022. return false;
  6023. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  6024. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  6025. return d >= 0;
  6026. };
  6027. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  6028. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  6029. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  6030. if (distance > this.velocityWorldLength + max + sphereRadius) {
  6031. return false;
  6032. }
  6033. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  6034. return false;
  6035. return true;
  6036. };
  6037. Collider.prototype._testTriangle = function (faceIndex, subMesh, p1, p2, p3) {
  6038. var t0;
  6039. var embeddedInPlane = false;
  6040. if (!subMesh._trianglePlanes) {
  6041. subMesh._trianglePlanes = [];
  6042. }
  6043. if (!subMesh._trianglePlanes[faceIndex]) {
  6044. subMesh._trianglePlanes[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  6045. subMesh._trianglePlanes[faceIndex].copyFromPoints(p1, p2, p3);
  6046. }
  6047. var trianglePlane = subMesh._trianglePlanes[faceIndex];
  6048. if ((!subMesh.getMaterial()) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  6049. return;
  6050. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  6051. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  6052. if (normalDotVelocity == 0) {
  6053. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  6054. return;
  6055. embeddedInPlane = true;
  6056. t0 = 0;
  6057. }
  6058. else {
  6059. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  6060. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  6061. if (t0 > t1) {
  6062. var temp = t1;
  6063. t1 = t0;
  6064. t0 = temp;
  6065. }
  6066. if (t0 > 1.0 || t1 < 0.0)
  6067. return;
  6068. if (t0 < 0)
  6069. t0 = 0;
  6070. if (t0 > 1.0)
  6071. t0 = 1.0;
  6072. }
  6073. this._collisionPoint.copyFromFloats(0, 0, 0);
  6074. var found = false;
  6075. var t = 1.0;
  6076. if (!embeddedInPlane) {
  6077. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  6078. this.velocity.scaleToRef(t0, this._tempVector);
  6079. this._planeIntersectionPoint.addInPlace(this._tempVector);
  6080. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  6081. found = true;
  6082. t = t0;
  6083. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  6084. }
  6085. }
  6086. if (!found) {
  6087. var velocitySquaredLength = this.velocity.lengthSquared();
  6088. var a = velocitySquaredLength;
  6089. this.basePoint.subtractToRef(p1, this._tempVector);
  6090. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  6091. var c = this._tempVector.lengthSquared() - 1.0;
  6092. var lowestRoot = getLowestRoot(a, b, c, t);
  6093. if (lowestRoot.found) {
  6094. t = lowestRoot.root;
  6095. found = true;
  6096. this._collisionPoint.copyFrom(p1);
  6097. }
  6098. this.basePoint.subtractToRef(p2, this._tempVector);
  6099. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  6100. c = this._tempVector.lengthSquared() - 1.0;
  6101. lowestRoot = getLowestRoot(a, b, c, t);
  6102. if (lowestRoot.found) {
  6103. t = lowestRoot.root;
  6104. found = true;
  6105. this._collisionPoint.copyFrom(p2);
  6106. }
  6107. this.basePoint.subtractToRef(p3, this._tempVector);
  6108. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  6109. c = this._tempVector.lengthSquared() - 1.0;
  6110. lowestRoot = getLowestRoot(a, b, c, t);
  6111. if (lowestRoot.found) {
  6112. t = lowestRoot.root;
  6113. found = true;
  6114. this._collisionPoint.copyFrom(p3);
  6115. }
  6116. p2.subtractToRef(p1, this._edge);
  6117. p1.subtractToRef(this.basePoint, this._baseToVertex);
  6118. var edgeSquaredLength = this._edge.lengthSquared();
  6119. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  6120. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  6121. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  6122. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  6123. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  6124. lowestRoot = getLowestRoot(a, b, c, t);
  6125. if (lowestRoot.found) {
  6126. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  6127. if (f >= 0.0 && f <= 1.0) {
  6128. t = lowestRoot.root;
  6129. found = true;
  6130. this._edge.scaleInPlace(f);
  6131. p1.addToRef(this._edge, this._collisionPoint);
  6132. }
  6133. }
  6134. p3.subtractToRef(p2, this._edge);
  6135. p2.subtractToRef(this.basePoint, this._baseToVertex);
  6136. edgeSquaredLength = this._edge.lengthSquared();
  6137. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  6138. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  6139. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  6140. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  6141. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  6142. lowestRoot = getLowestRoot(a, b, c, t);
  6143. if (lowestRoot.found) {
  6144. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  6145. if (f >= 0.0 && f <= 1.0) {
  6146. t = lowestRoot.root;
  6147. found = true;
  6148. this._edge.scaleInPlace(f);
  6149. p2.addToRef(this._edge, this._collisionPoint);
  6150. }
  6151. }
  6152. p1.subtractToRef(p3, this._edge);
  6153. p3.subtractToRef(this.basePoint, this._baseToVertex);
  6154. edgeSquaredLength = this._edge.lengthSquared();
  6155. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  6156. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  6157. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  6158. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  6159. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  6160. lowestRoot = getLowestRoot(a, b, c, t);
  6161. if (lowestRoot.found) {
  6162. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  6163. if (f >= 0.0 && f <= 1.0) {
  6164. t = lowestRoot.root;
  6165. found = true;
  6166. this._edge.scaleInPlace(f);
  6167. p3.addToRef(this._edge, this._collisionPoint);
  6168. }
  6169. }
  6170. }
  6171. if (found) {
  6172. var distToCollision = t * this.velocity.length();
  6173. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  6174. if (!this.intersectionPoint) {
  6175. this.intersectionPoint = this._collisionPoint.clone();
  6176. }
  6177. else {
  6178. this.intersectionPoint.copyFrom(this._collisionPoint);
  6179. }
  6180. this.nearestDistance = distToCollision;
  6181. this.collisionFound = true;
  6182. this.collidedMesh = subMesh.getMesh();
  6183. }
  6184. }
  6185. };
  6186. Collider.prototype._collide = function (subMesh, pts, indices, indexStart, indexEnd, decal) {
  6187. for (var i = indexStart; i < indexEnd; i += 3) {
  6188. var p1 = pts[indices[i] - decal];
  6189. var p2 = pts[indices[i + 1] - decal];
  6190. var p3 = pts[indices[i + 2] - decal];
  6191. this._testTriangle(i, subMesh, p3, p2, p1);
  6192. }
  6193. };
  6194. Collider.prototype._getResponse = function (pos, vel) {
  6195. pos.addToRef(vel, this._destinationPoint);
  6196. vel.scaleInPlace((this.nearestDistance / vel.length()));
  6197. this.basePoint.addToRef(vel, pos);
  6198. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  6199. this._slidePlaneNormal.normalize();
  6200. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  6201. pos.addInPlace(this._displacementVector);
  6202. this.intersectionPoint.addInPlace(this._displacementVector);
  6203. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  6204. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  6205. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  6206. };
  6207. return Collider;
  6208. })();
  6209. BABYLON.Collider = Collider;
  6210. })(BABYLON || (BABYLON = {}));
  6211. //# sourceMappingURL=babylon.collider.js.map
  6212. var BABYLON;
  6213. (function (BABYLON) {
  6214. var Camera = (function (_super) {
  6215. __extends(Camera, _super);
  6216. function Camera(name, position, scene) {
  6217. _super.call(this, name, scene);
  6218. this.position = position;
  6219. // Members
  6220. this.upVector = BABYLON.Vector3.Up();
  6221. this.orthoLeft = null;
  6222. this.orthoRight = null;
  6223. this.orthoBottom = null;
  6224. this.orthoTop = null;
  6225. this.fov = 0.8;
  6226. this.minZ = 1.0;
  6227. this.maxZ = 10000.0;
  6228. this.inertia = 0.9;
  6229. this.mode = Camera.PERSPECTIVE_CAMERA;
  6230. this.isIntermediate = false;
  6231. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  6232. this.subCameras = [];
  6233. this.layerMask = 0xFFFFFFFF;
  6234. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  6235. this._computedViewMatrix = BABYLON.Matrix.Identity();
  6236. this._projectionMatrix = new BABYLON.Matrix();
  6237. this._postProcesses = new Array();
  6238. this._postProcessesTakenIndices = [];
  6239. scene.cameras.push(this);
  6240. if (!scene.activeCamera) {
  6241. scene.activeCamera = this;
  6242. }
  6243. }
  6244. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  6245. get: function () {
  6246. return Camera._PERSPECTIVE_CAMERA;
  6247. },
  6248. enumerable: true,
  6249. configurable: true
  6250. });
  6251. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  6252. get: function () {
  6253. return Camera._ORTHOGRAPHIC_CAMERA;
  6254. },
  6255. enumerable: true,
  6256. configurable: true
  6257. });
  6258. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  6259. get: function () {
  6260. return Camera._FOVMODE_VERTICAL_FIXED;
  6261. },
  6262. enumerable: true,
  6263. configurable: true
  6264. });
  6265. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  6266. get: function () {
  6267. return Camera._FOVMODE_HORIZONTAL_FIXED;
  6268. },
  6269. enumerable: true,
  6270. configurable: true
  6271. });
  6272. //Cache
  6273. Camera.prototype._initCache = function () {
  6274. _super.prototype._initCache.call(this);
  6275. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6276. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6277. this._cache.mode = undefined;
  6278. this._cache.minZ = undefined;
  6279. this._cache.maxZ = undefined;
  6280. this._cache.fov = undefined;
  6281. this._cache.aspectRatio = undefined;
  6282. this._cache.orthoLeft = undefined;
  6283. this._cache.orthoRight = undefined;
  6284. this._cache.orthoBottom = undefined;
  6285. this._cache.orthoTop = undefined;
  6286. this._cache.renderWidth = undefined;
  6287. this._cache.renderHeight = undefined;
  6288. };
  6289. Camera.prototype._updateCache = function (ignoreParentClass) {
  6290. if (!ignoreParentClass) {
  6291. _super.prototype._updateCache.call(this);
  6292. }
  6293. var engine = this.getEngine();
  6294. this._cache.position.copyFrom(this.position);
  6295. this._cache.upVector.copyFrom(this.upVector);
  6296. this._cache.mode = this.mode;
  6297. this._cache.minZ = this.minZ;
  6298. this._cache.maxZ = this.maxZ;
  6299. this._cache.fov = this.fov;
  6300. this._cache.aspectRatio = engine.getAspectRatio(this);
  6301. this._cache.orthoLeft = this.orthoLeft;
  6302. this._cache.orthoRight = this.orthoRight;
  6303. this._cache.orthoBottom = this.orthoBottom;
  6304. this._cache.orthoTop = this.orthoTop;
  6305. this._cache.renderWidth = engine.getRenderWidth();
  6306. this._cache.renderHeight = engine.getRenderHeight();
  6307. };
  6308. Camera.prototype._updateFromScene = function () {
  6309. this.updateCache();
  6310. this._update();
  6311. };
  6312. // Synchronized
  6313. Camera.prototype._isSynchronized = function () {
  6314. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  6315. };
  6316. Camera.prototype._isSynchronizedViewMatrix = function () {
  6317. if (!_super.prototype._isSynchronized.call(this))
  6318. return false;
  6319. return this._cache.position.equals(this.position) && this._cache.upVector.equals(this.upVector) && this.isSynchronizedWithParent();
  6320. };
  6321. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  6322. var check = this._cache.mode === this.mode && this._cache.minZ === this.minZ && this._cache.maxZ === this.maxZ;
  6323. if (!check) {
  6324. return false;
  6325. }
  6326. var engine = this.getEngine();
  6327. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  6328. check = this._cache.fov === this.fov && this._cache.aspectRatio === engine.getAspectRatio(this);
  6329. }
  6330. else {
  6331. check = this._cache.orthoLeft === this.orthoLeft && this._cache.orthoRight === this.orthoRight && this._cache.orthoBottom === this.orthoBottom && this._cache.orthoTop === this.orthoTop && this._cache.renderWidth === engine.getRenderWidth() && this._cache.renderHeight === engine.getRenderHeight();
  6332. }
  6333. return check;
  6334. };
  6335. // Controls
  6336. Camera.prototype.attachControl = function (element) {
  6337. };
  6338. Camera.prototype.detachControl = function (element) {
  6339. };
  6340. Camera.prototype._update = function () {
  6341. };
  6342. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  6343. if (insertAt === void 0) { insertAt = null; }
  6344. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  6345. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  6346. return 0;
  6347. }
  6348. if (insertAt == null || insertAt < 0) {
  6349. this._postProcesses.push(postProcess);
  6350. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  6351. return this._postProcesses.length - 1;
  6352. }
  6353. var add = 0;
  6354. if (this._postProcesses[insertAt]) {
  6355. var start = this._postProcesses.length - 1;
  6356. for (var i = start; i >= insertAt + 1; --i) {
  6357. this._postProcesses[i + 1] = this._postProcesses[i];
  6358. }
  6359. add = 1;
  6360. }
  6361. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  6362. if (this._postProcessesTakenIndices[i] < insertAt) {
  6363. continue;
  6364. }
  6365. start = this._postProcessesTakenIndices.length - 1;
  6366. for (var j = start; j >= i; --j) {
  6367. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  6368. }
  6369. this._postProcessesTakenIndices[i] = insertAt;
  6370. break;
  6371. }
  6372. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) == -1) {
  6373. this._postProcessesTakenIndices.push(insertAt);
  6374. }
  6375. var result = insertAt + add;
  6376. this._postProcesses[result] = postProcess;
  6377. return result;
  6378. };
  6379. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  6380. if (atIndices === void 0) { atIndices = null; }
  6381. var result = [];
  6382. if (!atIndices) {
  6383. var length = this._postProcesses.length;
  6384. for (var i = 0; i < length; i++) {
  6385. if (this._postProcesses[i] !== postProcess) {
  6386. continue;
  6387. }
  6388. delete this._postProcesses[i];
  6389. var index = this._postProcessesTakenIndices.indexOf(i);
  6390. this._postProcessesTakenIndices.splice(index, 1);
  6391. }
  6392. }
  6393. else {
  6394. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  6395. for (i = 0; i < atIndices.length; i++) {
  6396. var foundPostProcess = this._postProcesses[atIndices[i]];
  6397. if (foundPostProcess !== postProcess) {
  6398. result.push(i);
  6399. continue;
  6400. }
  6401. delete this._postProcesses[atIndices[i]];
  6402. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  6403. this._postProcessesTakenIndices.splice(index, 1);
  6404. }
  6405. }
  6406. return result;
  6407. };
  6408. Camera.prototype.getWorldMatrix = function () {
  6409. if (!this._worldMatrix) {
  6410. this._worldMatrix = BABYLON.Matrix.Identity();
  6411. }
  6412. var viewMatrix = this.getViewMatrix();
  6413. viewMatrix.invertToRef(this._worldMatrix);
  6414. return this._worldMatrix;
  6415. };
  6416. Camera.prototype._getViewMatrix = function () {
  6417. return BABYLON.Matrix.Identity();
  6418. };
  6419. Camera.prototype.getViewMatrix = function () {
  6420. this._computedViewMatrix = this._computeViewMatrix();
  6421. if (!this.parent || !this.parent.getWorldMatrix || this.isSynchronized()) {
  6422. return this._computedViewMatrix;
  6423. }
  6424. if (!this._worldMatrix) {
  6425. this._worldMatrix = BABYLON.Matrix.Identity();
  6426. }
  6427. this._computedViewMatrix.invertToRef(this._worldMatrix);
  6428. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  6429. this._computedViewMatrix.invert();
  6430. this._currentRenderId = this.getScene().getRenderId();
  6431. return this._computedViewMatrix;
  6432. };
  6433. Camera.prototype._computeViewMatrix = function (force) {
  6434. if (!force && this._isSynchronizedViewMatrix()) {
  6435. return this._computedViewMatrix;
  6436. }
  6437. this._computedViewMatrix = this._getViewMatrix();
  6438. if (!this.parent || !this.parent.getWorldMatrix) {
  6439. this._currentRenderId = this.getScene().getRenderId();
  6440. }
  6441. return this._computedViewMatrix;
  6442. };
  6443. Camera.prototype.getProjectionMatrix = function (force) {
  6444. if (!force && this._isSynchronizedProjectionMatrix()) {
  6445. return this._projectionMatrix;
  6446. }
  6447. var engine = this.getEngine();
  6448. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  6449. if (this.minZ <= 0) {
  6450. this.minZ = 0.1;
  6451. }
  6452. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode);
  6453. return this._projectionMatrix;
  6454. }
  6455. var halfWidth = engine.getRenderWidth() / 2.0;
  6456. var halfHeight = engine.getRenderHeight() / 2.0;
  6457. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  6458. return this._projectionMatrix;
  6459. };
  6460. Camera.prototype.dispose = function () {
  6461. // Remove from scene
  6462. var index = this.getScene().cameras.indexOf(this);
  6463. this.getScene().cameras.splice(index, 1);
  6464. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  6465. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  6466. }
  6467. };
  6468. // Statics
  6469. Camera._PERSPECTIVE_CAMERA = 0;
  6470. Camera._ORTHOGRAPHIC_CAMERA = 1;
  6471. Camera._FOVMODE_VERTICAL_FIXED = 0;
  6472. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  6473. return Camera;
  6474. })(BABYLON.Node);
  6475. BABYLON.Camera = Camera;
  6476. })(BABYLON || (BABYLON = {}));
  6477. //# sourceMappingURL=babylon.camera.js.map
  6478. var BABYLON;
  6479. (function (BABYLON) {
  6480. var TargetCamera = (function (_super) {
  6481. __extends(TargetCamera, _super);
  6482. function TargetCamera(name, position, scene) {
  6483. _super.call(this, name, position, scene);
  6484. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  6485. this.cameraRotation = new BABYLON.Vector2(0, 0);
  6486. this.rotation = new BABYLON.Vector3(0, 0, 0);
  6487. this.speed = 2.0;
  6488. this.noRotationConstraint = false;
  6489. this.lockedTarget = null;
  6490. this._currentTarget = BABYLON.Vector3.Zero();
  6491. this._viewMatrix = BABYLON.Matrix.Zero();
  6492. this._camMatrix = BABYLON.Matrix.Zero();
  6493. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  6494. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  6495. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  6496. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  6497. this._lookAtTemp = BABYLON.Matrix.Zero();
  6498. this._tempMatrix = BABYLON.Matrix.Zero();
  6499. }
  6500. TargetCamera.prototype._getLockedTargetPosition = function () {
  6501. if (!this.lockedTarget) {
  6502. return null;
  6503. }
  6504. return this.lockedTarget.position || this.lockedTarget;
  6505. };
  6506. // Cache
  6507. TargetCamera.prototype._initCache = function () {
  6508. _super.prototype._initCache.call(this);
  6509. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6510. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6511. };
  6512. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  6513. if (!ignoreParentClass) {
  6514. _super.prototype._updateCache.call(this);
  6515. }
  6516. var lockedTargetPosition = this._getLockedTargetPosition();
  6517. if (!lockedTargetPosition) {
  6518. this._cache.lockedTarget = null;
  6519. }
  6520. else {
  6521. if (!this._cache.lockedTarget) {
  6522. this._cache.lockedTarget = lockedTargetPosition.clone();
  6523. }
  6524. else {
  6525. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  6526. }
  6527. }
  6528. this._cache.rotation.copyFrom(this.rotation);
  6529. };
  6530. // Synchronized
  6531. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  6532. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  6533. return false;
  6534. }
  6535. var lockedTargetPosition = this._getLockedTargetPosition();
  6536. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition) && this._cache.rotation.equals(this.rotation);
  6537. };
  6538. // Methods
  6539. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  6540. var engine = this.getEngine();
  6541. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  6542. };
  6543. // Target
  6544. TargetCamera.prototype.setTarget = function (target) {
  6545. this.upVector.normalize();
  6546. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  6547. this._camMatrix.invert();
  6548. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  6549. var vDir = target.subtract(this.position);
  6550. if (vDir.x >= 0.0) {
  6551. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  6552. }
  6553. else {
  6554. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  6555. }
  6556. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  6557. if (isNaN(this.rotation.x)) {
  6558. this.rotation.x = 0;
  6559. }
  6560. if (isNaN(this.rotation.y)) {
  6561. this.rotation.y = 0;
  6562. }
  6563. if (isNaN(this.rotation.z)) {
  6564. this.rotation.z = 0;
  6565. }
  6566. };
  6567. TargetCamera.prototype.getTarget = function () {
  6568. return this._currentTarget;
  6569. };
  6570. TargetCamera.prototype._decideIfNeedsToMove = function () {
  6571. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  6572. };
  6573. TargetCamera.prototype._updatePosition = function () {
  6574. this.position.addInPlace(this.cameraDirection);
  6575. };
  6576. TargetCamera.prototype._update = function () {
  6577. var needToMove = this._decideIfNeedsToMove();
  6578. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  6579. // Move
  6580. if (needToMove) {
  6581. this._updatePosition();
  6582. }
  6583. // Rotate
  6584. if (needToRotate) {
  6585. this.rotation.x += this.cameraRotation.x;
  6586. this.rotation.y += this.cameraRotation.y;
  6587. if (!this.noRotationConstraint) {
  6588. var limit = (Math.PI / 2) * 0.95;
  6589. if (this.rotation.x > limit)
  6590. this.rotation.x = limit;
  6591. if (this.rotation.x < -limit)
  6592. this.rotation.x = -limit;
  6593. }
  6594. }
  6595. // Inertia
  6596. if (needToMove) {
  6597. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  6598. this.cameraDirection.x = 0;
  6599. }
  6600. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  6601. this.cameraDirection.y = 0;
  6602. }
  6603. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  6604. this.cameraDirection.z = 0;
  6605. }
  6606. this.cameraDirection.scaleInPlace(this.inertia);
  6607. }
  6608. if (needToRotate) {
  6609. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  6610. this.cameraRotation.x = 0;
  6611. }
  6612. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  6613. this.cameraRotation.y = 0;
  6614. }
  6615. this.cameraRotation.scaleInPlace(this.inertia);
  6616. }
  6617. };
  6618. TargetCamera.prototype._getViewMatrix = function () {
  6619. if (!this.lockedTarget) {
  6620. // Compute
  6621. if (this.upVector.x != 0 || this.upVector.y != 1.0 || this.upVector.z != 0) {
  6622. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  6623. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  6624. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  6625. this._lookAtTemp.invert();
  6626. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  6627. }
  6628. else {
  6629. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  6630. }
  6631. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  6632. // Computing target and final matrix
  6633. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  6634. }
  6635. else {
  6636. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  6637. }
  6638. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  6639. return this._viewMatrix;
  6640. };
  6641. return TargetCamera;
  6642. })(BABYLON.Camera);
  6643. BABYLON.TargetCamera = TargetCamera;
  6644. })(BABYLON || (BABYLON = {}));
  6645. //# sourceMappingURL=babylon.targetCamera.js.map
  6646. var BABYLON;
  6647. (function (BABYLON) {
  6648. var FollowCamera = (function (_super) {
  6649. __extends(FollowCamera, _super);
  6650. function FollowCamera(name, position, scene) {
  6651. _super.call(this, name, position, scene);
  6652. this.radius = 12;
  6653. this.rotationOffset = 0;
  6654. this.heightOffset = 4;
  6655. this.cameraAcceleration = 0.05;
  6656. this.maxCameraSpeed = 20;
  6657. }
  6658. FollowCamera.prototype.getRadians = function (degrees) {
  6659. return degrees * Math.PI / 180;
  6660. };
  6661. FollowCamera.prototype.follow = function (cameraTarget) {
  6662. if (!cameraTarget)
  6663. return;
  6664. var radians = this.getRadians(this.rotationOffset) + cameraTarget.rotation.y;
  6665. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  6666. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  6667. var dx = targetX - this.position.x;
  6668. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  6669. var dz = (targetZ) - this.position.z;
  6670. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  6671. var vy = dy * this.cameraAcceleration;
  6672. var vz = dz * this.cameraAcceleration * 2;
  6673. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  6674. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  6675. }
  6676. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  6677. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  6678. }
  6679. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  6680. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  6681. }
  6682. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  6683. this.setTarget(cameraTarget.position);
  6684. };
  6685. FollowCamera.prototype._update = function () {
  6686. _super.prototype._update.call(this);
  6687. this.follow(this.target);
  6688. };
  6689. return FollowCamera;
  6690. })(BABYLON.TargetCamera);
  6691. BABYLON.FollowCamera = FollowCamera;
  6692. })(BABYLON || (BABYLON = {}));
  6693. //# sourceMappingURL=babylon.followCamera.js.map
  6694. var BABYLON;
  6695. (function (BABYLON) {
  6696. var FreeCamera = (function (_super) {
  6697. __extends(FreeCamera, _super);
  6698. function FreeCamera(name, position, scene) {
  6699. _super.call(this, name, position, scene);
  6700. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  6701. this.keysUp = [38];
  6702. this.keysDown = [40];
  6703. this.keysLeft = [37];
  6704. this.keysRight = [39];
  6705. this.checkCollisions = false;
  6706. this.applyGravity = false;
  6707. this.angularSensibility = 2000.0;
  6708. this._keys = [];
  6709. this._collider = new BABYLON.Collider();
  6710. this._needMoveForGravity = true;
  6711. this._oldPosition = BABYLON.Vector3.Zero();
  6712. this._diffPosition = BABYLON.Vector3.Zero();
  6713. this._newPosition = BABYLON.Vector3.Zero();
  6714. }
  6715. // Controls
  6716. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  6717. var _this = this;
  6718. var previousPosition;
  6719. var engine = this.getEngine();
  6720. if (this._attachedElement) {
  6721. return;
  6722. }
  6723. this._attachedElement = element;
  6724. if (this._onMouseDown === undefined) {
  6725. this._onMouseDown = function (evt) {
  6726. previousPosition = {
  6727. x: evt.clientX,
  6728. y: evt.clientY
  6729. };
  6730. if (!noPreventDefault) {
  6731. evt.preventDefault();
  6732. }
  6733. };
  6734. this._onMouseUp = function (evt) {
  6735. previousPosition = null;
  6736. if (!noPreventDefault) {
  6737. evt.preventDefault();
  6738. }
  6739. };
  6740. this._onMouseOut = function (evt) {
  6741. previousPosition = null;
  6742. _this._keys = [];
  6743. if (!noPreventDefault) {
  6744. evt.preventDefault();
  6745. }
  6746. };
  6747. this._onMouseMove = function (evt) {
  6748. if (!previousPosition && !engine.isPointerLock) {
  6749. return;
  6750. }
  6751. var offsetX;
  6752. var offsetY;
  6753. if (!engine.isPointerLock) {
  6754. offsetX = evt.clientX - previousPosition.x;
  6755. offsetY = evt.clientY - previousPosition.y;
  6756. }
  6757. else {
  6758. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  6759. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  6760. }
  6761. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  6762. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  6763. previousPosition = {
  6764. x: evt.clientX,
  6765. y: evt.clientY
  6766. };
  6767. if (!noPreventDefault) {
  6768. evt.preventDefault();
  6769. }
  6770. };
  6771. this._onKeyDown = function (evt) {
  6772. if (_this.keysUp.indexOf(evt.keyCode) !== -1 || _this.keysDown.indexOf(evt.keyCode) !== -1 || _this.keysLeft.indexOf(evt.keyCode) !== -1 || _this.keysRight.indexOf(evt.keyCode) !== -1) {
  6773. var index = _this._keys.indexOf(evt.keyCode);
  6774. if (index === -1) {
  6775. _this._keys.push(evt.keyCode);
  6776. }
  6777. if (!noPreventDefault) {
  6778. evt.preventDefault();
  6779. }
  6780. }
  6781. };
  6782. this._onKeyUp = function (evt) {
  6783. if (_this.keysUp.indexOf(evt.keyCode) !== -1 || _this.keysDown.indexOf(evt.keyCode) !== -1 || _this.keysLeft.indexOf(evt.keyCode) !== -1 || _this.keysRight.indexOf(evt.keyCode) !== -1) {
  6784. var index = _this._keys.indexOf(evt.keyCode);
  6785. if (index >= 0) {
  6786. _this._keys.splice(index, 1);
  6787. }
  6788. if (!noPreventDefault) {
  6789. evt.preventDefault();
  6790. }
  6791. }
  6792. };
  6793. this._onLostFocus = function () {
  6794. _this._keys = [];
  6795. };
  6796. this._reset = function () {
  6797. _this._keys = [];
  6798. previousPosition = null;
  6799. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  6800. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  6801. };
  6802. }
  6803. element.addEventListener("mousedown", this._onMouseDown, false);
  6804. element.addEventListener("mouseup", this._onMouseUp, false);
  6805. element.addEventListener("mouseout", this._onMouseOut, false);
  6806. element.addEventListener("mousemove", this._onMouseMove, false);
  6807. BABYLON.Tools.RegisterTopRootEvents([
  6808. { name: "keydown", handler: this._onKeyDown },
  6809. { name: "keyup", handler: this._onKeyUp },
  6810. { name: "blur", handler: this._onLostFocus }
  6811. ]);
  6812. };
  6813. FreeCamera.prototype.detachControl = function (element) {
  6814. if (this._attachedElement != element) {
  6815. return;
  6816. }
  6817. element.removeEventListener("mousedown", this._onMouseDown);
  6818. element.removeEventListener("mouseup", this._onMouseUp);
  6819. element.removeEventListener("mouseout", this._onMouseOut);
  6820. element.removeEventListener("mousemove", this._onMouseMove);
  6821. BABYLON.Tools.UnregisterTopRootEvents([
  6822. { name: "keydown", handler: this._onKeyDown },
  6823. { name: "keyup", handler: this._onKeyUp },
  6824. { name: "blur", handler: this._onLostFocus }
  6825. ]);
  6826. this._attachedElement = null;
  6827. if (this._reset) {
  6828. this._reset();
  6829. }
  6830. };
  6831. FreeCamera.prototype._collideWithWorld = function (velocity) {
  6832. var globalPosition;
  6833. if (this.parent) {
  6834. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  6835. }
  6836. else {
  6837. globalPosition = this.position;
  6838. }
  6839. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  6840. this._collider.radius = this.ellipsoid;
  6841. this.getScene()._getNewPosition(this._oldPosition, velocity, this._collider, 3, this._newPosition);
  6842. this._newPosition.subtractToRef(this._oldPosition, this._diffPosition);
  6843. if (this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  6844. this.position.addInPlace(this._diffPosition);
  6845. if (this.onCollide) {
  6846. this.onCollide(this._collider.collidedMesh);
  6847. }
  6848. }
  6849. };
  6850. FreeCamera.prototype._checkInputs = function () {
  6851. if (!this._localDirection) {
  6852. this._localDirection = BABYLON.Vector3.Zero();
  6853. this._transformedDirection = BABYLON.Vector3.Zero();
  6854. }
  6855. for (var index = 0; index < this._keys.length; index++) {
  6856. var keyCode = this._keys[index];
  6857. var speed = this._computeLocalCameraSpeed();
  6858. if (this.keysLeft.indexOf(keyCode) !== -1) {
  6859. this._localDirection.copyFromFloats(-speed, 0, 0);
  6860. }
  6861. else if (this.keysUp.indexOf(keyCode) !== -1) {
  6862. this._localDirection.copyFromFloats(0, 0, speed);
  6863. }
  6864. else if (this.keysRight.indexOf(keyCode) !== -1) {
  6865. this._localDirection.copyFromFloats(speed, 0, 0);
  6866. }
  6867. else if (this.keysDown.indexOf(keyCode) !== -1) {
  6868. this._localDirection.copyFromFloats(0, 0, -speed);
  6869. }
  6870. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  6871. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  6872. this.cameraDirection.addInPlace(this._transformedDirection);
  6873. }
  6874. };
  6875. FreeCamera.prototype._decideIfNeedsToMove = function () {
  6876. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  6877. };
  6878. FreeCamera.prototype._updatePosition = function () {
  6879. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  6880. this._collideWithWorld(this.cameraDirection);
  6881. if (this.applyGravity) {
  6882. var oldPosition = this.position;
  6883. this._collideWithWorld(this.getScene().gravity);
  6884. this._needMoveForGravity = (BABYLON.Vector3.DistanceSquared(oldPosition, this.position) != 0);
  6885. }
  6886. }
  6887. else {
  6888. this.position.addInPlace(this.cameraDirection);
  6889. }
  6890. };
  6891. FreeCamera.prototype._update = function () {
  6892. this._checkInputs();
  6893. _super.prototype._update.call(this);
  6894. };
  6895. return FreeCamera;
  6896. })(BABYLON.TargetCamera);
  6897. BABYLON.FreeCamera = FreeCamera;
  6898. })(BABYLON || (BABYLON = {}));
  6899. //# sourceMappingURL=babylon.freeCamera.js.map
  6900. var BABYLON;
  6901. (function (BABYLON) {
  6902. // We're mainly based on the logic defined into the FreeCamera code
  6903. var TouchCamera = (function (_super) {
  6904. __extends(TouchCamera, _super);
  6905. function TouchCamera(name, position, scene) {
  6906. _super.call(this, name, position, scene);
  6907. this._offsetX = null;
  6908. this._offsetY = null;
  6909. this._pointerCount = 0;
  6910. this._pointerPressed = [];
  6911. this.angularSensibility = 200000.0;
  6912. this.moveSensibility = 500.0;
  6913. }
  6914. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  6915. var _this = this;
  6916. var previousPosition;
  6917. if (this._attachedCanvas) {
  6918. return;
  6919. }
  6920. this._attachedCanvas = canvas;
  6921. if (this._onPointerDown === undefined) {
  6922. this._onPointerDown = function (evt) {
  6923. if (!noPreventDefault) {
  6924. evt.preventDefault();
  6925. }
  6926. _this._pointerPressed.push(evt.pointerId);
  6927. if (_this._pointerPressed.length !== 1) {
  6928. return;
  6929. }
  6930. previousPosition = {
  6931. x: evt.clientX,
  6932. y: evt.clientY
  6933. };
  6934. };
  6935. this._onPointerUp = function (evt) {
  6936. if (!noPreventDefault) {
  6937. evt.preventDefault();
  6938. }
  6939. var index = _this._pointerPressed.indexOf(evt.pointerId);
  6940. if (index === -1) {
  6941. return;
  6942. }
  6943. _this._pointerPressed.splice(index, 1);
  6944. if (index != 0) {
  6945. return;
  6946. }
  6947. previousPosition = null;
  6948. _this._offsetX = null;
  6949. _this._offsetY = null;
  6950. };
  6951. this._onPointerMove = function (evt) {
  6952. if (!noPreventDefault) {
  6953. evt.preventDefault();
  6954. }
  6955. if (!previousPosition) {
  6956. return;
  6957. }
  6958. var index = _this._pointerPressed.indexOf(evt.pointerId);
  6959. if (index != 0) {
  6960. return;
  6961. }
  6962. _this._offsetX = evt.clientX - previousPosition.x;
  6963. _this._offsetY = -(evt.clientY - previousPosition.y);
  6964. };
  6965. this._onLostFocus = function () {
  6966. _this._offsetX = null;
  6967. _this._offsetY = null;
  6968. };
  6969. }
  6970. canvas.addEventListener("pointerdown", this._onPointerDown);
  6971. canvas.addEventListener("pointerup", this._onPointerUp);
  6972. canvas.addEventListener("pointerout", this._onPointerUp);
  6973. canvas.addEventListener("pointermove", this._onPointerMove);
  6974. BABYLON.Tools.RegisterTopRootEvents([
  6975. { name: "blur", handler: this._onLostFocus }
  6976. ]);
  6977. };
  6978. TouchCamera.prototype.detachControl = function (canvas) {
  6979. if (this._attachedCanvas != canvas) {
  6980. return;
  6981. }
  6982. canvas.removeEventListener("pointerdown", this._onPointerDown);
  6983. canvas.removeEventListener("pointerup", this._onPointerUp);
  6984. canvas.removeEventListener("pointerout", this._onPointerUp);
  6985. canvas.removeEventListener("pointermove", this._onPointerMove);
  6986. BABYLON.Tools.UnregisterTopRootEvents([
  6987. { name: "blur", handler: this._onLostFocus }
  6988. ]);
  6989. this._attachedCanvas = null;
  6990. };
  6991. TouchCamera.prototype._checkInputs = function () {
  6992. if (!this._offsetX) {
  6993. return;
  6994. }
  6995. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  6996. if (this._pointerPressed.length > 1) {
  6997. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  6998. }
  6999. else {
  7000. var speed = this._computeLocalCameraSpeed();
  7001. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  7002. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  7003. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  7004. }
  7005. };
  7006. return TouchCamera;
  7007. })(BABYLON.FreeCamera);
  7008. BABYLON.TouchCamera = TouchCamera;
  7009. })(BABYLON || (BABYLON = {}));
  7010. //# sourceMappingURL=babylon.touchCamera.js.map
  7011. var BABYLON;
  7012. (function (BABYLON) {
  7013. // We're mainly based on the logic defined into the FreeCamera code
  7014. var DeviceOrientationCamera = (function (_super) {
  7015. __extends(DeviceOrientationCamera, _super);
  7016. function DeviceOrientationCamera(name, position, scene) {
  7017. var _this = this;
  7018. _super.call(this, name, position, scene);
  7019. this._offsetX = null;
  7020. this._offsetY = null;
  7021. this._orientationGamma = 0;
  7022. this._orientationBeta = 0;
  7023. this._initialOrientationGamma = 0;
  7024. this._initialOrientationBeta = 0;
  7025. this.angularSensibility = 10000.0;
  7026. this.moveSensibility = 50.0;
  7027. window.addEventListener("resize", function () {
  7028. _this._initialOrientationGamma = null;
  7029. }, false);
  7030. }
  7031. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  7032. var _this = this;
  7033. if (this._attachedCanvas) {
  7034. return;
  7035. }
  7036. this._attachedCanvas = canvas;
  7037. if (!this._orientationChanged) {
  7038. this._orientationChanged = function (evt) {
  7039. if (!_this._initialOrientationGamma) {
  7040. _this._initialOrientationGamma = evt.gamma;
  7041. _this._initialOrientationBeta = evt.beta;
  7042. }
  7043. _this._orientationGamma = evt.gamma;
  7044. _this._orientationBeta = evt.beta;
  7045. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  7046. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  7047. };
  7048. }
  7049. window.addEventListener("deviceorientation", this._orientationChanged);
  7050. };
  7051. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  7052. if (this._attachedCanvas != canvas) {
  7053. return;
  7054. }
  7055. window.removeEventListener("deviceorientation", this._orientationChanged);
  7056. this._attachedCanvas = null;
  7057. this._orientationGamma = 0;
  7058. this._orientationBeta = 0;
  7059. this._initialOrientationGamma = 0;
  7060. this._initialOrientationBeta = 0;
  7061. };
  7062. DeviceOrientationCamera.prototype._checkInputs = function () {
  7063. if (!this._offsetX) {
  7064. return;
  7065. }
  7066. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  7067. var speed = this._computeLocalCameraSpeed();
  7068. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  7069. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  7070. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  7071. };
  7072. return DeviceOrientationCamera;
  7073. })(BABYLON.FreeCamera);
  7074. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  7075. })(BABYLON || (BABYLON = {}));
  7076. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  7077. var BABYLON;
  7078. (function (BABYLON) {
  7079. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  7080. var ArcRotateCamera = (function (_super) {
  7081. __extends(ArcRotateCamera, _super);
  7082. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  7083. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  7084. this.alpha = alpha;
  7085. this.beta = beta;
  7086. this.radius = radius;
  7087. this.target = target;
  7088. this.inertialAlphaOffset = 0;
  7089. this.inertialBetaOffset = 0;
  7090. this.inertialRadiusOffset = 0;
  7091. this.lowerAlphaLimit = null;
  7092. this.upperAlphaLimit = null;
  7093. this.lowerBetaLimit = 0.01;
  7094. this.upperBetaLimit = Math.PI;
  7095. this.lowerRadiusLimit = null;
  7096. this.upperRadiusLimit = null;
  7097. this.angularSensibility = 1000.0;
  7098. this.wheelPrecision = 3.0;
  7099. this.keysUp = [38];
  7100. this.keysDown = [40];
  7101. this.keysLeft = [37];
  7102. this.keysRight = [39];
  7103. this.zoomOnFactor = 1;
  7104. this.targetScreenOffset = BABYLON.Vector2.Zero();
  7105. this._keys = [];
  7106. this._viewMatrix = new BABYLON.Matrix();
  7107. this.checkCollisions = false;
  7108. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  7109. this._collider = new BABYLON.Collider();
  7110. this._previousPosition = BABYLON.Vector3.Zero();
  7111. this._collisionVelocity = BABYLON.Vector3.Zero();
  7112. this._newPosition = BABYLON.Vector3.Zero();
  7113. // Pinch
  7114. // value for pinch step scaling
  7115. // set to 20 by default
  7116. this.pinchPrecision = 20;
  7117. this.getViewMatrix();
  7118. }
  7119. ArcRotateCamera.prototype._getTargetPosition = function () {
  7120. return this.target.position || this.target;
  7121. };
  7122. // Cache
  7123. ArcRotateCamera.prototype._initCache = function () {
  7124. _super.prototype._initCache.call(this);
  7125. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7126. this._cache.alpha = undefined;
  7127. this._cache.beta = undefined;
  7128. this._cache.radius = undefined;
  7129. this._cache.targetScreenOffset = undefined;
  7130. };
  7131. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  7132. if (!ignoreParentClass) {
  7133. _super.prototype._updateCache.call(this);
  7134. }
  7135. this._cache.target.copyFrom(this._getTargetPosition());
  7136. this._cache.alpha = this.alpha;
  7137. this._cache.beta = this.beta;
  7138. this._cache.radius = this.radius;
  7139. this._cache.targetScreenOffset = this.targetScreenOffset.clone();
  7140. };
  7141. // Synchronized
  7142. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  7143. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  7144. return false;
  7145. return this._cache.target.equals(this._getTargetPosition()) && this._cache.alpha === this.alpha && this._cache.beta === this.beta && this._cache.radius === this.radius && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  7146. };
  7147. // Methods
  7148. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault) {
  7149. var _this = this;
  7150. var previousPosition;
  7151. var pointerId;
  7152. // to know if pinch started
  7153. var pinchStarted = false;
  7154. // two pinch point on X
  7155. // that will use for find if user action is pinch open or pinch close
  7156. var pinchPointX1, pinchPointX2;
  7157. if (this._attachedElement) {
  7158. return;
  7159. }
  7160. this._attachedElement = element;
  7161. var engine = this.getEngine();
  7162. if (this._onPointerDown === undefined) {
  7163. this._onPointerDown = function (evt) {
  7164. if (pointerId) {
  7165. return;
  7166. }
  7167. pointerId = evt.pointerId;
  7168. previousPosition = {
  7169. x: evt.clientX,
  7170. y: evt.clientY
  7171. };
  7172. if (!noPreventDefault) {
  7173. evt.preventDefault();
  7174. }
  7175. };
  7176. this._onPointerUp = function (evt) {
  7177. previousPosition = null;
  7178. pointerId = null;
  7179. if (!noPreventDefault) {
  7180. evt.preventDefault();
  7181. }
  7182. };
  7183. this._onPointerMove = function (evt) {
  7184. if (!previousPosition) {
  7185. return;
  7186. }
  7187. if (pointerId !== evt.pointerId) {
  7188. return;
  7189. }
  7190. // return pinch is started
  7191. if (pinchStarted) {
  7192. return;
  7193. }
  7194. var offsetX = evt.clientX - previousPosition.x;
  7195. var offsetY = evt.clientY - previousPosition.y;
  7196. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  7197. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  7198. previousPosition = {
  7199. x: evt.clientX,
  7200. y: evt.clientY
  7201. };
  7202. if (!noPreventDefault) {
  7203. evt.preventDefault();
  7204. }
  7205. };
  7206. this._onMouseMove = function (evt) {
  7207. if (!engine.isPointerLock) {
  7208. return;
  7209. }
  7210. // return pinch is started
  7211. if (pinchStarted) {
  7212. return;
  7213. }
  7214. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  7215. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  7216. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  7217. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  7218. if (!noPreventDefault) {
  7219. evt.preventDefault();
  7220. }
  7221. };
  7222. this._wheel = function (event) {
  7223. var delta = 0;
  7224. if (event.wheelDelta) {
  7225. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  7226. }
  7227. else if (event.detail) {
  7228. delta = -event.detail / _this.wheelPrecision;
  7229. }
  7230. if (delta)
  7231. _this.inertialRadiusOffset += delta;
  7232. if (event.preventDefault) {
  7233. if (!noPreventDefault) {
  7234. event.preventDefault();
  7235. }
  7236. }
  7237. };
  7238. this._onKeyDown = function (evt) {
  7239. if (_this.keysUp.indexOf(evt.keyCode) !== -1 || _this.keysDown.indexOf(evt.keyCode) !== -1 || _this.keysLeft.indexOf(evt.keyCode) !== -1 || _this.keysRight.indexOf(evt.keyCode) !== -1) {
  7240. var index = _this._keys.indexOf(evt.keyCode);
  7241. if (index === -1) {
  7242. _this._keys.push(evt.keyCode);
  7243. }
  7244. if (evt.preventDefault) {
  7245. if (!noPreventDefault) {
  7246. evt.preventDefault();
  7247. }
  7248. }
  7249. }
  7250. };
  7251. this._onKeyUp = function (evt) {
  7252. if (_this.keysUp.indexOf(evt.keyCode) !== -1 || _this.keysDown.indexOf(evt.keyCode) !== -1 || _this.keysLeft.indexOf(evt.keyCode) !== -1 || _this.keysRight.indexOf(evt.keyCode) !== -1) {
  7253. var index = _this._keys.indexOf(evt.keyCode);
  7254. if (index >= 0) {
  7255. _this._keys.splice(index, 1);
  7256. }
  7257. if (evt.preventDefault) {
  7258. if (!noPreventDefault) {
  7259. evt.preventDefault();
  7260. }
  7261. }
  7262. }
  7263. };
  7264. this._onLostFocus = function () {
  7265. _this._keys = [];
  7266. pointerId = null;
  7267. };
  7268. this._onGestureStart = function (e) {
  7269. if (window.MSGesture === undefined) {
  7270. return;
  7271. }
  7272. if (!_this._MSGestureHandler) {
  7273. _this._MSGestureHandler = new MSGesture();
  7274. _this._MSGestureHandler.target = element;
  7275. }
  7276. _this._MSGestureHandler.addPointer(e.pointerId);
  7277. };
  7278. this._onGesture = function (e) {
  7279. _this.radius *= e.scale;
  7280. if (e.preventDefault) {
  7281. if (!noPreventDefault) {
  7282. e.stopPropagation();
  7283. e.preventDefault();
  7284. }
  7285. }
  7286. };
  7287. this._reset = function () {
  7288. _this._keys = [];
  7289. _this.inertialAlphaOffset = 0;
  7290. _this.inertialBetaOffset = 0;
  7291. _this.inertialRadiusOffset = 0;
  7292. previousPosition = null;
  7293. pointerId = null;
  7294. };
  7295. this._touchStart = function (event) {
  7296. if (event.touches.length === 2) {
  7297. //-- start pinch if two fingers on the screen
  7298. pinchStarted = true;
  7299. _this._pinchStart(event);
  7300. }
  7301. };
  7302. this._touchMove = function (event) {
  7303. if (pinchStarted) {
  7304. //-- make scaling
  7305. _this._pinchMove(event);
  7306. }
  7307. };
  7308. this._touchEnd = function (event) {
  7309. if (pinchStarted) {
  7310. //-- end of pinch
  7311. _this._pinchEnd(event);
  7312. }
  7313. };
  7314. this._pinchStart = function (event) {
  7315. // save origin touch point
  7316. pinchPointX1 = event.touches[0].clientX;
  7317. pinchPointX2 = event.touches[1].clientX;
  7318. // block the camera
  7319. // if not it rotate around target during pinch
  7320. pinchStarted = true;
  7321. };
  7322. this._pinchMove = function (event) {
  7323. // variable for new camera's radius
  7324. var delta = 0;
  7325. // variables to know if pinch open or pinch close
  7326. var direction = 1;
  7327. var distanceXOrigine, distanceXNow;
  7328. if (event.touches.length !== 2)
  7329. return;
  7330. // calculate absolute distances of the two fingers
  7331. distanceXOrigine = Math.abs(pinchPointX1 - pinchPointX2);
  7332. distanceXNow = Math.abs(event.touches[0].clientX - event.touches[1].clientX);
  7333. // if distanceXNow < distanceXOrigine -> pinch close so direction = -1
  7334. if (distanceXNow < distanceXOrigine) {
  7335. direction = -1;
  7336. }
  7337. // calculate new radius
  7338. delta = (_this.pinchPrecision / (_this.wheelPrecision * 40)) * direction;
  7339. // set new radius
  7340. _this.inertialRadiusOffset -= delta;
  7341. // save origin touch point
  7342. pinchPointX1 = event.touches[0].clientX;
  7343. pinchPointX2 = event.touches[1].clientX;
  7344. };
  7345. this._pinchEnd = function (event) {
  7346. // cancel pinch and deblock camera rotation
  7347. pinchStarted = false;
  7348. };
  7349. }
  7350. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  7351. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  7352. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  7353. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  7354. element.addEventListener("mousemove", this._onMouseMove, false);
  7355. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  7356. element.addEventListener("MSGestureChange", this._onGesture, false);
  7357. element.addEventListener('mousewheel', this._wheel, false);
  7358. element.addEventListener('DOMMouseScroll', this._wheel, false);
  7359. // pinch
  7360. element.addEventListener('touchstart', this._touchStart, false);
  7361. element.addEventListener('touchmove', this._touchMove, false);
  7362. element.addEventListener('touchend', this._touchEnd, false);
  7363. BABYLON.Tools.RegisterTopRootEvents([
  7364. { name: "keydown", handler: this._onKeyDown },
  7365. { name: "keyup", handler: this._onKeyUp },
  7366. { name: "blur", handler: this._onLostFocus }
  7367. ]);
  7368. };
  7369. ArcRotateCamera.prototype.detachControl = function (element) {
  7370. if (this._attachedElement != element) {
  7371. return;
  7372. }
  7373. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  7374. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  7375. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  7376. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  7377. element.removeEventListener("mousemove", this._onMouseMove);
  7378. element.removeEventListener("MSPointerDown", this._onGestureStart);
  7379. element.removeEventListener("MSGestureChange", this._onGesture);
  7380. element.removeEventListener('mousewheel', this._wheel);
  7381. element.removeEventListener('DOMMouseScroll', this._wheel);
  7382. // pinch
  7383. element.removeEventListener('touchstart', this._touchStart);
  7384. element.removeEventListener('touchmove', this._touchMove);
  7385. element.removeEventListener('touchend', this._touchEnd);
  7386. BABYLON.Tools.UnregisterTopRootEvents([
  7387. { name: "keydown", handler: this._onKeyDown },
  7388. { name: "keyup", handler: this._onKeyUp },
  7389. { name: "blur", handler: this._onLostFocus }
  7390. ]);
  7391. this._MSGestureHandler = null;
  7392. this._attachedElement = null;
  7393. if (this._reset) {
  7394. this._reset();
  7395. }
  7396. };
  7397. ArcRotateCamera.prototype._update = function () {
  7398. for (var index = 0; index < this._keys.length; index++) {
  7399. var keyCode = this._keys[index];
  7400. if (this.keysLeft.indexOf(keyCode) !== -1) {
  7401. this.inertialAlphaOffset -= 0.01;
  7402. }
  7403. else if (this.keysUp.indexOf(keyCode) !== -1) {
  7404. this.inertialBetaOffset -= 0.01;
  7405. }
  7406. else if (this.keysRight.indexOf(keyCode) !== -1) {
  7407. this.inertialAlphaOffset += 0.01;
  7408. }
  7409. else if (this.keysDown.indexOf(keyCode) !== -1) {
  7410. this.inertialBetaOffset += 0.01;
  7411. }
  7412. }
  7413. // Inertia
  7414. if (this.inertialAlphaOffset != 0 || this.inertialBetaOffset != 0 || this.inertialRadiusOffset != 0) {
  7415. this.alpha += this.inertialAlphaOffset;
  7416. this.beta += this.inertialBetaOffset;
  7417. this.radius -= this.inertialRadiusOffset;
  7418. this.inertialAlphaOffset *= this.inertia;
  7419. this.inertialBetaOffset *= this.inertia;
  7420. this.inertialRadiusOffset *= this.inertia;
  7421. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  7422. this.inertialAlphaOffset = 0;
  7423. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  7424. this.inertialBetaOffset = 0;
  7425. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  7426. this.inertialRadiusOffset = 0;
  7427. }
  7428. // Limits
  7429. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  7430. this.alpha = this.lowerAlphaLimit;
  7431. }
  7432. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  7433. this.alpha = this.upperAlphaLimit;
  7434. }
  7435. if (this.lowerBetaLimit && this.beta < this.lowerBetaLimit) {
  7436. this.beta = this.lowerBetaLimit;
  7437. }
  7438. if (this.upperBetaLimit && this.beta > this.upperBetaLimit) {
  7439. this.beta = this.upperBetaLimit;
  7440. }
  7441. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  7442. this.radius = this.lowerRadiusLimit;
  7443. }
  7444. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  7445. this.radius = this.upperRadiusLimit;
  7446. }
  7447. };
  7448. ArcRotateCamera.prototype.setPosition = function (position) {
  7449. var radiusv3 = position.subtract(this._getTargetPosition());
  7450. this.radius = radiusv3.length();
  7451. // Alpha
  7452. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  7453. if (radiusv3.z < 0) {
  7454. this.alpha = 2 * Math.PI - this.alpha;
  7455. }
  7456. // Beta
  7457. this.beta = Math.acos(radiusv3.y / this.radius);
  7458. };
  7459. ArcRotateCamera.prototype._getViewMatrix = function () {
  7460. // Compute
  7461. var cosa = Math.cos(this.alpha);
  7462. var sina = Math.sin(this.alpha);
  7463. var cosb = Math.cos(this.beta);
  7464. var sinb = Math.sin(this.beta);
  7465. var target = this._getTargetPosition();
  7466. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this.position);
  7467. if (this.checkCollisions) {
  7468. this._collider.radius = this.collisionRadius;
  7469. this.position.subtractToRef(this._previousPosition, this._collisionVelocity);
  7470. this.getScene()._getNewPosition(this._previousPosition, this._collisionVelocity, this._collider, 3, this._newPosition);
  7471. if (!this._newPosition.equalsWithEpsilon(this.position)) {
  7472. this.position.copyFrom(this._previousPosition);
  7473. this.alpha = this._previousAlpha;
  7474. this.beta = this._previousBeta;
  7475. this.radius = this._previousRadius;
  7476. if (this.onCollide) {
  7477. this.onCollide(this._collider.collidedMesh);
  7478. }
  7479. }
  7480. }
  7481. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._viewMatrix);
  7482. this._previousAlpha = this.alpha;
  7483. this._previousBeta = this.beta;
  7484. this._previousRadius = this.radius;
  7485. this._previousPosition.copyFrom(this.position);
  7486. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  7487. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  7488. return this._viewMatrix;
  7489. };
  7490. ArcRotateCamera.prototype.zoomOn = function (meshes) {
  7491. meshes = meshes || this.getScene().meshes;
  7492. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  7493. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  7494. this.radius = distance * this.zoomOnFactor;
  7495. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance });
  7496. };
  7497. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance) {
  7498. var meshesOrMinMaxVector;
  7499. var distance;
  7500. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  7501. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  7502. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  7503. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  7504. }
  7505. else {
  7506. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  7507. distance = meshesOrMinMaxVectorAndDistance.distance;
  7508. }
  7509. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  7510. this.maxZ = distance * 2;
  7511. };
  7512. return ArcRotateCamera;
  7513. })(BABYLON.Camera);
  7514. BABYLON.ArcRotateCamera = ArcRotateCamera;
  7515. })(BABYLON || (BABYLON = {}));
  7516. //# sourceMappingURL=babylon.arcRotateCamera.js.mapvar BABYLON;
  7517. (function (BABYLON) {
  7518. /**
  7519. * Represents a scene to be rendered by the engine.
  7520. * @see http://doc.babylonjs.com/page.php?p=21911
  7521. */
  7522. var Scene = (function () {
  7523. /**
  7524. * @constructor
  7525. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  7526. */
  7527. function Scene(engine) {
  7528. // Members
  7529. this.autoClear = true;
  7530. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  7531. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  7532. this.forceWireframe = false;
  7533. this.forcePointsCloud = false;
  7534. this.forceShowBoundingBoxes = false;
  7535. this.animationsEnabled = true;
  7536. this.cameraToUseForPointers = null; // Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position
  7537. // Fog
  7538. /**
  7539. * is fog enabled on this scene.
  7540. * @type {boolean}
  7541. */
  7542. this.fogEnabled = true;
  7543. this.fogMode = Scene.FOGMODE_NONE;
  7544. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  7545. this.fogDensity = 0.1;
  7546. this.fogStart = 0;
  7547. this.fogEnd = 1000.0;
  7548. // Lights
  7549. /**
  7550. * is shadow enabled on this scene.
  7551. * @type {boolean}
  7552. */
  7553. this.shadowsEnabled = true;
  7554. /**
  7555. * is light enabled on this scene.
  7556. * @type {boolean}
  7557. */
  7558. this.lightsEnabled = true;
  7559. /**
  7560. * All of the lights added to this scene.
  7561. * @see BABYLON.Light
  7562. * @type {BABYLON.Light[]}
  7563. */
  7564. this.lights = new Array();
  7565. // Cameras
  7566. /**
  7567. * All of the cameras added to this scene.
  7568. * @see BABYLON.Camera
  7569. * @type {BABYLON.Camera[]}
  7570. */
  7571. this.cameras = new Array();
  7572. this.activeCameras = new Array();
  7573. // Meshes
  7574. /**
  7575. * All of the (abstract) meshes added to this scene.
  7576. * @see BABYLON.AbstractMesh
  7577. * @type {BABYLON.AbstractMesh[]}
  7578. */
  7579. this.meshes = new Array();
  7580. // Geometries
  7581. this._geometries = new Array();
  7582. this.materials = new Array();
  7583. this.multiMaterials = new Array();
  7584. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  7585. // Textures
  7586. this.texturesEnabled = true;
  7587. this.textures = new Array();
  7588. // Particles
  7589. this.particlesEnabled = true;
  7590. this.particleSystems = new Array();
  7591. // Sprites
  7592. this.spriteManagers = new Array();
  7593. // Layers
  7594. this.layers = new Array();
  7595. // Skeletons
  7596. this.skeletonsEnabled = true;
  7597. this.skeletons = new Array();
  7598. // Lens flares
  7599. this.lensFlaresEnabled = true;
  7600. this.lensFlareSystems = new Array();
  7601. // Collisions
  7602. this.collisionsEnabled = true;
  7603. this.gravity = new BABYLON.Vector3(0, -9.0, 0);
  7604. // Postprocesses
  7605. this.postProcessesEnabled = true;
  7606. // Customs render targets
  7607. this.renderTargetsEnabled = true;
  7608. this.customRenderTargets = new Array();
  7609. // Imported meshes
  7610. this.importedMeshesFiles = new Array();
  7611. this._actionManagers = new Array();
  7612. this._meshesForIntersections = new BABYLON.SmartArray(256);
  7613. // Procedural textures
  7614. this.proceduralTexturesEnabled = true;
  7615. this._proceduralTextures = new Array();
  7616. this.soundTracks = new Array();
  7617. this._totalVertices = 0;
  7618. this._activeVertices = 0;
  7619. this._activeParticles = 0;
  7620. this._lastFrameDuration = 0;
  7621. this._evaluateActiveMeshesDuration = 0;
  7622. this._renderTargetsDuration = 0;
  7623. this._particlesDuration = 0;
  7624. this._renderDuration = 0;
  7625. this._spritesDuration = 0;
  7626. this._animationRatio = 0;
  7627. this._renderId = 0;
  7628. this._executeWhenReadyTimeoutId = -1;
  7629. this._toBeDisposed = new BABYLON.SmartArray(256);
  7630. this._onReadyCallbacks = new Array();
  7631. this._pendingData = []; //ANY
  7632. this._onBeforeRenderCallbacks = new Array();
  7633. this._onAfterRenderCallbacks = new Array();
  7634. this._activeMeshes = new BABYLON.SmartArray(256);
  7635. this._processedMaterials = new BABYLON.SmartArray(256);
  7636. this._renderTargets = new BABYLON.SmartArray(256);
  7637. this._activeParticleSystems = new BABYLON.SmartArray(256);
  7638. this._activeSkeletons = new BABYLON.SmartArray(32);
  7639. this._activeBones = 0;
  7640. this._activeAnimatables = new Array();
  7641. this._transformMatrix = BABYLON.Matrix.Zero();
  7642. this._scaledPosition = BABYLON.Vector3.Zero();
  7643. this._scaledVelocity = BABYLON.Vector3.Zero();
  7644. this._engine = engine;
  7645. engine.scenes.push(this);
  7646. this._renderingManager = new BABYLON.RenderingManager(this);
  7647. this.postProcessManager = new BABYLON.PostProcessManager(this);
  7648. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  7649. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  7650. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  7651. this.attachControl();
  7652. this._debugLayer = new BABYLON.DebugLayer(this);
  7653. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  7654. }
  7655. Object.defineProperty(Scene, "FOGMODE_NONE", {
  7656. get: function () {
  7657. return Scene._FOGMODE_NONE;
  7658. },
  7659. enumerable: true,
  7660. configurable: true
  7661. });
  7662. Object.defineProperty(Scene, "FOGMODE_EXP", {
  7663. get: function () {
  7664. return Scene._FOGMODE_EXP;
  7665. },
  7666. enumerable: true,
  7667. configurable: true
  7668. });
  7669. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  7670. get: function () {
  7671. return Scene._FOGMODE_EXP2;
  7672. },
  7673. enumerable: true,
  7674. configurable: true
  7675. });
  7676. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  7677. get: function () {
  7678. return Scene._FOGMODE_LINEAR;
  7679. },
  7680. enumerable: true,
  7681. configurable: true
  7682. });
  7683. Object.defineProperty(Scene.prototype, "debugLayer", {
  7684. // Properties
  7685. get: function () {
  7686. return this._debugLayer;
  7687. },
  7688. enumerable: true,
  7689. configurable: true
  7690. });
  7691. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  7692. /**
  7693. * The mesh that is currently under the pointer.
  7694. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  7695. */
  7696. get: function () {
  7697. return this._meshUnderPointer;
  7698. },
  7699. enumerable: true,
  7700. configurable: true
  7701. });
  7702. Object.defineProperty(Scene.prototype, "pointerX", {
  7703. /**
  7704. * Current on-screen X position of the pointer
  7705. * @return {number} X position of the pointer
  7706. */
  7707. get: function () {
  7708. return this._pointerX;
  7709. },
  7710. enumerable: true,
  7711. configurable: true
  7712. });
  7713. Object.defineProperty(Scene.prototype, "pointerY", {
  7714. /**
  7715. * Current on-screen Y position of the pointer
  7716. * @return {number} Y position of the pointer
  7717. */
  7718. get: function () {
  7719. return this._pointerY;
  7720. },
  7721. enumerable: true,
  7722. configurable: true
  7723. });
  7724. Scene.prototype.getCachedMaterial = function () {
  7725. return this._cachedMaterial;
  7726. };
  7727. Scene.prototype.getBoundingBoxRenderer = function () {
  7728. return this._boundingBoxRenderer;
  7729. };
  7730. Scene.prototype.getOutlineRenderer = function () {
  7731. return this._outlineRenderer;
  7732. };
  7733. Scene.prototype.getEngine = function () {
  7734. return this._engine;
  7735. };
  7736. Scene.prototype.getTotalVertices = function () {
  7737. return this._totalVertices;
  7738. };
  7739. Scene.prototype.getActiveVertices = function () {
  7740. return this._activeVertices;
  7741. };
  7742. Scene.prototype.getActiveParticles = function () {
  7743. return this._activeParticles;
  7744. };
  7745. Scene.prototype.getActiveBones = function () {
  7746. return this._activeBones;
  7747. };
  7748. // Stats
  7749. Scene.prototype.getLastFrameDuration = function () {
  7750. return this._lastFrameDuration;
  7751. };
  7752. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  7753. return this._evaluateActiveMeshesDuration;
  7754. };
  7755. Scene.prototype.getActiveMeshes = function () {
  7756. return this._activeMeshes;
  7757. };
  7758. Scene.prototype.getRenderTargetsDuration = function () {
  7759. return this._renderTargetsDuration;
  7760. };
  7761. Scene.prototype.getRenderDuration = function () {
  7762. return this._renderDuration;
  7763. };
  7764. Scene.prototype.getParticlesDuration = function () {
  7765. return this._particlesDuration;
  7766. };
  7767. Scene.prototype.getSpritesDuration = function () {
  7768. return this._spritesDuration;
  7769. };
  7770. Scene.prototype.getAnimationRatio = function () {
  7771. return this._animationRatio;
  7772. };
  7773. Scene.prototype.getRenderId = function () {
  7774. return this._renderId;
  7775. };
  7776. Scene.prototype.incrementRenderId = function () {
  7777. this._renderId++;
  7778. };
  7779. Scene.prototype._updatePointerPosition = function (evt) {
  7780. var canvasRect = this._engine.getRenderingCanvasClientRect();
  7781. this._pointerX = evt.clientX - canvasRect.left;
  7782. this._pointerY = evt.clientY - canvasRect.top;
  7783. if (this.cameraToUseForPointers) {
  7784. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  7785. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  7786. }
  7787. };
  7788. // Pointers handling
  7789. Scene.prototype.attachControl = function () {
  7790. var _this = this;
  7791. this._onPointerMove = function (evt) {
  7792. var canvas = _this._engine.getRenderingCanvas();
  7793. _this._updatePointerPosition(evt);
  7794. var pickResult = _this.pick(_this._pointerX, _this._pointerY, function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPointerTriggers; }, false, _this.cameraToUseForPointers);
  7795. if (pickResult.hit) {
  7796. _this._meshUnderPointer = pickResult.pickedMesh;
  7797. _this.setPointerOverMesh(pickResult.pickedMesh);
  7798. canvas.style.cursor = "pointer";
  7799. }
  7800. else {
  7801. _this.setPointerOverMesh(null);
  7802. canvas.style.cursor = "";
  7803. _this._meshUnderPointer = null;
  7804. }
  7805. };
  7806. this._onPointerDown = function (evt) {
  7807. var predicate = null;
  7808. if (!_this.onPointerDown) {
  7809. predicate = function (mesh) {
  7810. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  7811. };
  7812. }
  7813. _this._updatePointerPosition(evt);
  7814. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  7815. if (pickResult.hit) {
  7816. if (pickResult.pickedMesh.actionManager) {
  7817. switch (evt.button) {
  7818. case 0:
  7819. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  7820. break;
  7821. case 1:
  7822. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  7823. break;
  7824. case 2:
  7825. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  7826. break;
  7827. }
  7828. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  7829. }
  7830. }
  7831. if (_this.onPointerDown) {
  7832. _this.onPointerDown(evt, pickResult);
  7833. }
  7834. };
  7835. this._onKeyDown = function (evt) {
  7836. if (_this.actionManager) {
  7837. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  7838. }
  7839. };
  7840. this._onKeyUp = function (evt) {
  7841. if (_this.actionManager) {
  7842. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  7843. }
  7844. };
  7845. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  7846. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  7847. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  7848. BABYLON.Tools.RegisterTopRootEvents([
  7849. { name: "keydown", handler: this._onKeyDown },
  7850. { name: "keyup", handler: this._onKeyUp }
  7851. ]);
  7852. };
  7853. Scene.prototype.detachControl = function () {
  7854. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  7855. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  7856. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  7857. BABYLON.Tools.UnregisterTopRootEvents([
  7858. { name: "keydown", handler: this._onKeyDown },
  7859. { name: "keyup", handler: this._onKeyUp }
  7860. ]);
  7861. };
  7862. // Ready
  7863. Scene.prototype.isReady = function () {
  7864. if (this._pendingData.length > 0) {
  7865. return false;
  7866. }
  7867. for (var index = 0; index < this._geometries.length; index++) {
  7868. var geometry = this._geometries[index];
  7869. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  7870. return false;
  7871. }
  7872. }
  7873. for (index = 0; index < this.meshes.length; index++) {
  7874. var mesh = this.meshes[index];
  7875. if (!mesh.isReady()) {
  7876. return false;
  7877. }
  7878. var mat = mesh.material;
  7879. if (mat) {
  7880. if (!mat.isReady(mesh)) {
  7881. return false;
  7882. }
  7883. }
  7884. }
  7885. return true;
  7886. };
  7887. Scene.prototype.resetCachedMaterial = function () {
  7888. this._cachedMaterial = null;
  7889. };
  7890. Scene.prototype.registerBeforeRender = function (func) {
  7891. this._onBeforeRenderCallbacks.push(func);
  7892. };
  7893. Scene.prototype.unregisterBeforeRender = function (func) {
  7894. var index = this._onBeforeRenderCallbacks.indexOf(func);
  7895. if (index > -1) {
  7896. this._onBeforeRenderCallbacks.splice(index, 1);
  7897. }
  7898. };
  7899. Scene.prototype.registerAfterRender = function (func) {
  7900. this._onAfterRenderCallbacks.push(func);
  7901. };
  7902. Scene.prototype.unregisterAfterRender = function (func) {
  7903. var index = this._onAfterRenderCallbacks.indexOf(func);
  7904. if (index > -1) {
  7905. this._onAfterRenderCallbacks.splice(index, 1);
  7906. }
  7907. };
  7908. Scene.prototype._addPendingData = function (data) {
  7909. this._pendingData.push(data);
  7910. };
  7911. Scene.prototype._removePendingData = function (data) {
  7912. var index = this._pendingData.indexOf(data);
  7913. if (index !== -1) {
  7914. this._pendingData.splice(index, 1);
  7915. }
  7916. };
  7917. Scene.prototype.getWaitingItemsCount = function () {
  7918. return this._pendingData.length;
  7919. };
  7920. /**
  7921. * Registers a function to be executed when the scene is ready.
  7922. * @param {Function} func - the function to be executed.
  7923. */
  7924. Scene.prototype.executeWhenReady = function (func) {
  7925. var _this = this;
  7926. this._onReadyCallbacks.push(func);
  7927. if (this._executeWhenReadyTimeoutId !== -1) {
  7928. return;
  7929. }
  7930. this._executeWhenReadyTimeoutId = setTimeout(function () {
  7931. _this._checkIsReady();
  7932. }, 150);
  7933. };
  7934. Scene.prototype._checkIsReady = function () {
  7935. var _this = this;
  7936. if (this.isReady()) {
  7937. this._onReadyCallbacks.forEach(function (func) {
  7938. func();
  7939. });
  7940. this._onReadyCallbacks = [];
  7941. this._executeWhenReadyTimeoutId = -1;
  7942. return;
  7943. }
  7944. this._executeWhenReadyTimeoutId = setTimeout(function () {
  7945. _this._checkIsReady();
  7946. }, 150);
  7947. };
  7948. // Animations
  7949. /**
  7950. * Will start the animation sequence of a given target
  7951. * @param target - the target
  7952. * @param {number} from - from which frame should animation start
  7953. * @param {number} to - till which frame should animation run.
  7954. * @param {boolean} [loop] - should the animation loop
  7955. * @param {number} [speedRatio] - the speed in which to run the animation
  7956. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  7957. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  7958. * @return {BABYLON.Animatable} the animatable object created for this animation
  7959. * @see BABYLON.Animatable
  7960. * @see http://doc.babylonjs.com/page.php?p=22081
  7961. */
  7962. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  7963. if (speedRatio === undefined) {
  7964. speedRatio = 1.0;
  7965. }
  7966. this.stopAnimation(target);
  7967. if (!animatable) {
  7968. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  7969. }
  7970. // Local animations
  7971. if (target.animations) {
  7972. animatable.appendAnimations(target, target.animations);
  7973. }
  7974. // Children animations
  7975. if (target.getAnimatables) {
  7976. var animatables = target.getAnimatables();
  7977. for (var index = 0; index < animatables.length; index++) {
  7978. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  7979. }
  7980. }
  7981. return animatable;
  7982. };
  7983. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  7984. if (speedRatio === undefined) {
  7985. speedRatio = 1.0;
  7986. }
  7987. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  7988. return animatable;
  7989. };
  7990. Scene.prototype.getAnimatableByTarget = function (target) {
  7991. for (var index = 0; index < this._activeAnimatables.length; index++) {
  7992. if (this._activeAnimatables[index].target === target) {
  7993. return this._activeAnimatables[index];
  7994. }
  7995. }
  7996. return null;
  7997. };
  7998. /**
  7999. * Will stop the animation of the given target
  8000. * @param target - the target
  8001. * @see beginAnimation
  8002. */
  8003. Scene.prototype.stopAnimation = function (target) {
  8004. var animatable = this.getAnimatableByTarget(target);
  8005. if (animatable) {
  8006. animatable.stop();
  8007. }
  8008. };
  8009. Scene.prototype._animate = function () {
  8010. if (!this.animationsEnabled) {
  8011. return;
  8012. }
  8013. if (!this._animationStartDate) {
  8014. this._animationStartDate = BABYLON.Tools.Now;
  8015. }
  8016. // Getting time
  8017. var now = BABYLON.Tools.Now;
  8018. var delay = now - this._animationStartDate;
  8019. for (var index = 0; index < this._activeAnimatables.length; index++) {
  8020. if (!this._activeAnimatables[index]._animate(delay)) {
  8021. this._activeAnimatables.splice(index, 1);
  8022. index--;
  8023. }
  8024. }
  8025. };
  8026. // Matrix
  8027. Scene.prototype.getViewMatrix = function () {
  8028. return this._viewMatrix;
  8029. };
  8030. Scene.prototype.getProjectionMatrix = function () {
  8031. return this._projectionMatrix;
  8032. };
  8033. Scene.prototype.getTransformMatrix = function () {
  8034. return this._transformMatrix;
  8035. };
  8036. Scene.prototype.setTransformMatrix = function (view, projection) {
  8037. this._viewMatrix = view;
  8038. this._projectionMatrix = projection;
  8039. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  8040. };
  8041. // Methods
  8042. /**
  8043. * sets the active camera of the scene using its ID
  8044. * @param {string} id - the camera's ID
  8045. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  8046. * @see activeCamera
  8047. */
  8048. Scene.prototype.setActiveCameraByID = function (id) {
  8049. var camera = this.getCameraByID(id);
  8050. if (camera) {
  8051. this.activeCamera = camera;
  8052. return camera;
  8053. }
  8054. return null;
  8055. };
  8056. /**
  8057. * sets the active camera of the scene using its name
  8058. * @param {string} name - the camera's name
  8059. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  8060. * @see activeCamera
  8061. */
  8062. Scene.prototype.setActiveCameraByName = function (name) {
  8063. var camera = this.getCameraByName(name);
  8064. if (camera) {
  8065. this.activeCamera = camera;
  8066. return camera;
  8067. }
  8068. return null;
  8069. };
  8070. /**
  8071. * get a material using its id
  8072. * @param {string} the material's ID
  8073. * @return {BABYLON.Material|null} the material or null if none found.
  8074. */
  8075. Scene.prototype.getMaterialByID = function (id) {
  8076. for (var index = 0; index < this.materials.length; index++) {
  8077. if (this.materials[index].id === id) {
  8078. return this.materials[index];
  8079. }
  8080. }
  8081. return null;
  8082. };
  8083. /**
  8084. * get a material using its name
  8085. * @param {string} the material's name
  8086. * @return {BABYLON.Material|null} the material or null if none found.
  8087. */
  8088. Scene.prototype.getMaterialByName = function (name) {
  8089. for (var index = 0; index < this.materials.length; index++) {
  8090. if (this.materials[index].name === name) {
  8091. return this.materials[index];
  8092. }
  8093. }
  8094. return null;
  8095. };
  8096. Scene.prototype.getCameraByID = function (id) {
  8097. for (var index = 0; index < this.cameras.length; index++) {
  8098. if (this.cameras[index].id === id) {
  8099. return this.cameras[index];
  8100. }
  8101. }
  8102. return null;
  8103. };
  8104. /**
  8105. * get a camera using its name
  8106. * @param {string} the camera's name
  8107. * @return {BABYLON.Camera|null} the camera or null if none found.
  8108. */
  8109. Scene.prototype.getCameraByName = function (name) {
  8110. for (var index = 0; index < this.cameras.length; index++) {
  8111. if (this.cameras[index].name === name) {
  8112. return this.cameras[index];
  8113. }
  8114. }
  8115. return null;
  8116. };
  8117. /**
  8118. * get a light node using its name
  8119. * @param {string} the light's name
  8120. * @return {BABYLON.Light|null} the light or null if none found.
  8121. */
  8122. Scene.prototype.getLightByName = function (name) {
  8123. for (var index = 0; index < this.lights.length; index++) {
  8124. if (this.lights[index].name === name) {
  8125. return this.lights[index];
  8126. }
  8127. }
  8128. return null;
  8129. };
  8130. /**
  8131. * get a light node using its ID
  8132. * @param {string} the light's id
  8133. * @return {BABYLON.Light|null} the light or null if none found.
  8134. */
  8135. Scene.prototype.getLightByID = function (id) {
  8136. for (var index = 0; index < this.lights.length; index++) {
  8137. if (this.lights[index].id === id) {
  8138. return this.lights[index];
  8139. }
  8140. }
  8141. return null;
  8142. };
  8143. /**
  8144. * get a geometry using its ID
  8145. * @param {string} the geometry's id
  8146. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  8147. */
  8148. Scene.prototype.getGeometryByID = function (id) {
  8149. for (var index = 0; index < this._geometries.length; index++) {
  8150. if (this._geometries[index].id === id) {
  8151. return this._geometries[index];
  8152. }
  8153. }
  8154. return null;
  8155. };
  8156. /**
  8157. * add a new geometry to this scene.
  8158. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  8159. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  8160. * @return {boolean} was the geometry added or not
  8161. */
  8162. Scene.prototype.pushGeometry = function (geometry, force) {
  8163. if (!force && this.getGeometryByID(geometry.id)) {
  8164. return false;
  8165. }
  8166. this._geometries.push(geometry);
  8167. return true;
  8168. };
  8169. Scene.prototype.getGeometries = function () {
  8170. return this._geometries;
  8171. };
  8172. /**
  8173. * Get a the first added mesh found of a given ID
  8174. * @param {string} id - the id to search for
  8175. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  8176. */
  8177. Scene.prototype.getMeshByID = function (id) {
  8178. for (var index = 0; index < this.meshes.length; index++) {
  8179. if (this.meshes[index].id === id) {
  8180. return this.meshes[index];
  8181. }
  8182. }
  8183. return null;
  8184. };
  8185. /**
  8186. * Get a the last added mesh found of a given ID
  8187. * @param {string} id - the id to search for
  8188. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  8189. */
  8190. Scene.prototype.getLastMeshByID = function (id) {
  8191. for (var index = this.meshes.length - 1; index >= 0; index--) {
  8192. if (this.meshes[index].id === id) {
  8193. return this.meshes[index];
  8194. }
  8195. }
  8196. return null;
  8197. };
  8198. /**
  8199. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  8200. * @param {string} id - the id to search for
  8201. * @return {BABYLON.Node|null} the node found or null if not found at all.
  8202. */
  8203. Scene.prototype.getLastEntryByID = function (id) {
  8204. for (var index = this.meshes.length - 1; index >= 0; index--) {
  8205. if (this.meshes[index].id === id) {
  8206. return this.meshes[index];
  8207. }
  8208. }
  8209. for (index = this.cameras.length - 1; index >= 0; index--) {
  8210. if (this.cameras[index].id === id) {
  8211. return this.cameras[index];
  8212. }
  8213. }
  8214. for (index = this.lights.length - 1; index >= 0; index--) {
  8215. if (this.lights[index].id === id) {
  8216. return this.lights[index];
  8217. }
  8218. }
  8219. return null;
  8220. };
  8221. Scene.prototype.getNodeByName = function (name) {
  8222. var mesh = this.getMeshByName(name);
  8223. if (mesh) {
  8224. return mesh;
  8225. }
  8226. var light = this.getLightByName(name);
  8227. if (light) {
  8228. return light;
  8229. }
  8230. return this.getCameraByName(name);
  8231. };
  8232. Scene.prototype.getMeshByName = function (name) {
  8233. for (var index = 0; index < this.meshes.length; index++) {
  8234. if (this.meshes[index].name === name) {
  8235. return this.meshes[index];
  8236. }
  8237. }
  8238. return null;
  8239. };
  8240. Scene.prototype.getSoundByName = function (name) {
  8241. for (var index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  8242. if (this.mainSoundTrack.soundCollection[index].name === name) {
  8243. return this.mainSoundTrack.soundCollection[index];
  8244. }
  8245. }
  8246. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  8247. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  8248. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  8249. return this.soundTracks[sdIndex].soundCollection[index];
  8250. }
  8251. }
  8252. }
  8253. return null;
  8254. };
  8255. Scene.prototype.getLastSkeletonByID = function (id) {
  8256. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  8257. if (this.skeletons[index].id === id) {
  8258. return this.skeletons[index];
  8259. }
  8260. }
  8261. return null;
  8262. };
  8263. Scene.prototype.getSkeletonById = function (id) {
  8264. for (var index = 0; index < this.skeletons.length; index++) {
  8265. if (this.skeletons[index].id === id) {
  8266. return this.skeletons[index];
  8267. }
  8268. }
  8269. return null;
  8270. };
  8271. Scene.prototype.getSkeletonByName = function (name) {
  8272. for (var index = 0; index < this.skeletons.length; index++) {
  8273. if (this.skeletons[index].name === name) {
  8274. return this.skeletons[index];
  8275. }
  8276. }
  8277. return null;
  8278. };
  8279. Scene.prototype.isActiveMesh = function (mesh) {
  8280. return (this._activeMeshes.indexOf(mesh) !== -1);
  8281. };
  8282. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  8283. if (mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  8284. var material = subMesh.getMaterial();
  8285. if (mesh.showSubMeshesBoundingBox) {
  8286. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  8287. }
  8288. if (material) {
  8289. // Render targets
  8290. if (material.getRenderTargetTextures) {
  8291. if (this._processedMaterials.indexOf(material) === -1) {
  8292. this._processedMaterials.push(material);
  8293. this._renderTargets.concat(material.getRenderTargetTextures());
  8294. }
  8295. }
  8296. // Dispatch
  8297. this._activeVertices += subMesh.indexCount;
  8298. this._renderingManager.dispatch(subMesh);
  8299. }
  8300. }
  8301. };
  8302. Scene.prototype._evaluateActiveMeshes = function () {
  8303. this._activeMeshes.reset();
  8304. this._renderingManager.reset();
  8305. this._processedMaterials.reset();
  8306. this._activeParticleSystems.reset();
  8307. this._activeSkeletons.reset();
  8308. this._boundingBoxRenderer.reset();
  8309. if (!this._frustumPlanes) {
  8310. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  8311. }
  8312. else {
  8313. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  8314. }
  8315. // Meshes
  8316. var meshes;
  8317. var len;
  8318. if (this._selectionOctree) {
  8319. var selection = this._selectionOctree.select(this._frustumPlanes);
  8320. meshes = selection.data;
  8321. len = selection.length;
  8322. }
  8323. else {
  8324. len = this.meshes.length;
  8325. meshes = this.meshes;
  8326. }
  8327. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  8328. var mesh = meshes[meshIndex];
  8329. if (mesh.isBlocked) {
  8330. continue;
  8331. }
  8332. this._totalVertices += mesh.getTotalVertices();
  8333. if (!mesh.isReady()) {
  8334. continue;
  8335. }
  8336. mesh.computeWorldMatrix();
  8337. // Intersections
  8338. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  8339. this._meshesForIntersections.pushNoDuplicate(mesh);
  8340. }
  8341. // Switch to current LOD
  8342. var meshLOD = mesh.getLOD(this.activeCamera);
  8343. if (!meshLOD) {
  8344. continue;
  8345. }
  8346. mesh._preActivate();
  8347. if (mesh.isEnabled() && mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  8348. this._activeMeshes.push(mesh);
  8349. mesh._activate(this._renderId);
  8350. this._activeMesh(meshLOD);
  8351. }
  8352. }
  8353. // Particle systems
  8354. var beforeParticlesDate = BABYLON.Tools.Now;
  8355. if (this.particlesEnabled) {
  8356. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  8357. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  8358. var particleSystem = this.particleSystems[particleIndex];
  8359. if (!particleSystem.isStarted()) {
  8360. continue;
  8361. }
  8362. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  8363. this._activeParticleSystems.push(particleSystem);
  8364. particleSystem.animate();
  8365. }
  8366. }
  8367. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  8368. }
  8369. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  8370. };
  8371. Scene.prototype._activeMesh = function (mesh) {
  8372. if (mesh.skeleton && this.skeletonsEnabled) {
  8373. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  8374. }
  8375. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  8376. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  8377. }
  8378. if (mesh && mesh.subMeshes) {
  8379. // Submeshes Octrees
  8380. var len;
  8381. var subMeshes;
  8382. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  8383. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  8384. len = intersections.length;
  8385. subMeshes = intersections.data;
  8386. }
  8387. else {
  8388. subMeshes = mesh.subMeshes;
  8389. len = subMeshes.length;
  8390. }
  8391. for (var subIndex = 0; subIndex < len; subIndex++) {
  8392. var subMesh = subMeshes[subIndex];
  8393. this._evaluateSubMesh(subMesh, mesh);
  8394. }
  8395. }
  8396. };
  8397. Scene.prototype.updateTransformMatrix = function (force) {
  8398. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  8399. };
  8400. Scene.prototype._renderForCamera = function (camera) {
  8401. var engine = this._engine;
  8402. this.activeCamera = camera;
  8403. if (!this.activeCamera)
  8404. throw new Error("Active camera not set");
  8405. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  8406. // Viewport
  8407. engine.setViewport(this.activeCamera.viewport);
  8408. // Camera
  8409. this._renderId++;
  8410. this.updateTransformMatrix();
  8411. if (this.beforeCameraRender) {
  8412. this.beforeCameraRender(this.activeCamera);
  8413. }
  8414. // Meshes
  8415. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  8416. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  8417. this._evaluateActiveMeshes();
  8418. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  8419. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  8420. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  8421. var skeleton = this._activeSkeletons.data[skeletonIndex];
  8422. skeleton.prepare();
  8423. this._activeBones += skeleton.bones.length;
  8424. }
  8425. // Render targets
  8426. var beforeRenderTargetDate = BABYLON.Tools.Now;
  8427. if (this.renderTargetsEnabled) {
  8428. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  8429. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  8430. var renderTarget = this._renderTargets.data[renderIndex];
  8431. if (renderTarget._shouldRender()) {
  8432. this._renderId++;
  8433. renderTarget.render();
  8434. }
  8435. }
  8436. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  8437. this._renderId++;
  8438. }
  8439. if (this._renderTargets.length > 0) {
  8440. engine.restoreDefaultFramebuffer();
  8441. }
  8442. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  8443. // Prepare Frame
  8444. this.postProcessManager._prepareFrame();
  8445. var beforeRenderDate = BABYLON.Tools.Now;
  8446. // Backgrounds
  8447. if (this.layers.length) {
  8448. engine.setDepthBuffer(false);
  8449. var layerIndex;
  8450. var layer;
  8451. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  8452. layer = this.layers[layerIndex];
  8453. if (layer.isBackground) {
  8454. layer.render();
  8455. }
  8456. }
  8457. engine.setDepthBuffer(true);
  8458. }
  8459. // Render
  8460. BABYLON.Tools.StartPerformanceCounter("Main render");
  8461. this._renderingManager.render(null, null, true, true);
  8462. BABYLON.Tools.EndPerformanceCounter("Main render");
  8463. // Bounding boxes
  8464. this._boundingBoxRenderer.render();
  8465. // Lens flares
  8466. if (this.lensFlaresEnabled) {
  8467. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  8468. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  8469. this.lensFlareSystems[lensFlareSystemIndex].render();
  8470. }
  8471. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  8472. }
  8473. // Foregrounds
  8474. if (this.layers.length) {
  8475. engine.setDepthBuffer(false);
  8476. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  8477. layer = this.layers[layerIndex];
  8478. if (!layer.isBackground) {
  8479. layer.render();
  8480. }
  8481. }
  8482. engine.setDepthBuffer(true);
  8483. }
  8484. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  8485. // Finalize frame
  8486. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  8487. // Update camera
  8488. this.activeCamera._updateFromScene();
  8489. // Reset some special arrays
  8490. this._renderTargets.reset();
  8491. if (this.afterCameraRender) {
  8492. this.afterCameraRender(this.activeCamera);
  8493. }
  8494. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  8495. };
  8496. Scene.prototype._processSubCameras = function (camera) {
  8497. if (camera.subCameras.length === 0) {
  8498. this._renderForCamera(camera);
  8499. return;
  8500. }
  8501. for (var index = 0; index < camera.subCameras.length; index++) {
  8502. this._renderForCamera(camera.subCameras[index]);
  8503. }
  8504. this.activeCamera = camera;
  8505. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  8506. // Update camera
  8507. this.activeCamera._updateFromScene();
  8508. };
  8509. Scene.prototype._checkIntersections = function () {
  8510. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  8511. var sourceMesh = this._meshesForIntersections.data[index];
  8512. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  8513. var action = sourceMesh.actionManager.actions[actionIndex];
  8514. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  8515. var parameters = action.getTriggerParameter();
  8516. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  8517. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  8518. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  8519. if (areIntersecting && currentIntersectionInProgress === -1) {
  8520. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  8521. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  8522. sourceMesh._intersectionsInProgress.push(otherMesh);
  8523. }
  8524. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  8525. sourceMesh._intersectionsInProgress.push(otherMesh);
  8526. }
  8527. }
  8528. else if (!areIntersecting && currentIntersectionInProgress > -1 && action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  8529. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  8530. var indexOfOther = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  8531. if (indexOfOther > -1) {
  8532. sourceMesh._intersectionsInProgress.splice(indexOfOther, 1);
  8533. }
  8534. }
  8535. }
  8536. }
  8537. }
  8538. };
  8539. Scene.prototype.render = function () {
  8540. var startDate = BABYLON.Tools.Now;
  8541. this._particlesDuration = 0;
  8542. this._spritesDuration = 0;
  8543. this._activeParticles = 0;
  8544. this._renderDuration = 0;
  8545. this._renderTargetsDuration = 0;
  8546. this._evaluateActiveMeshesDuration = 0;
  8547. this._totalVertices = 0;
  8548. this._activeVertices = 0;
  8549. this._activeBones = 0;
  8550. this.getEngine().resetDrawCalls();
  8551. this._meshesForIntersections.reset();
  8552. this.resetCachedMaterial();
  8553. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  8554. // Actions
  8555. if (this.actionManager) {
  8556. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  8557. }
  8558. // Before render
  8559. if (this.beforeRender) {
  8560. this.beforeRender();
  8561. }
  8562. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  8563. this._onBeforeRenderCallbacks[callbackIndex]();
  8564. }
  8565. // Animations
  8566. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  8567. this._animationRatio = deltaTime * (60.0 / 1000.0);
  8568. this._animate();
  8569. // Physics
  8570. if (this._physicsEngine) {
  8571. BABYLON.Tools.StartPerformanceCounter("Physics");
  8572. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  8573. BABYLON.Tools.EndPerformanceCounter("Physics");
  8574. }
  8575. // Customs render targets
  8576. var beforeRenderTargetDate = BABYLON.Tools.Now;
  8577. var engine = this.getEngine();
  8578. var currentActiveCamera = this.activeCamera;
  8579. if (this.renderTargetsEnabled) {
  8580. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  8581. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  8582. var renderTarget = this.customRenderTargets[customIndex];
  8583. if (renderTarget._shouldRender()) {
  8584. this._renderId++;
  8585. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  8586. if (!this.activeCamera)
  8587. throw new Error("Active camera not set");
  8588. // Viewport
  8589. engine.setViewport(this.activeCamera.viewport);
  8590. // Camera
  8591. this.updateTransformMatrix();
  8592. renderTarget.render();
  8593. }
  8594. }
  8595. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  8596. this._renderId++;
  8597. }
  8598. if (this.customRenderTargets.length > 0) {
  8599. engine.restoreDefaultFramebuffer();
  8600. }
  8601. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  8602. this.activeCamera = currentActiveCamera;
  8603. // Procedural textures
  8604. if (this.proceduralTexturesEnabled) {
  8605. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  8606. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  8607. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  8608. if (proceduralTexture._shouldRender()) {
  8609. proceduralTexture.render();
  8610. }
  8611. }
  8612. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  8613. }
  8614. // Clear
  8615. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  8616. // Shadows
  8617. if (this.shadowsEnabled) {
  8618. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  8619. var light = this.lights[lightIndex];
  8620. var shadowGenerator = light.getShadowGenerator();
  8621. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  8622. this._renderTargets.push(shadowGenerator.getShadowMap());
  8623. }
  8624. }
  8625. }
  8626. // Depth renderer
  8627. if (this._depthRenderer) {
  8628. this._renderTargets.push(this._depthRenderer.getDepthMap());
  8629. }
  8630. // RenderPipeline
  8631. this.postProcessRenderPipelineManager.update();
  8632. // Multi-cameras?
  8633. if (this.activeCameras.length > 0) {
  8634. var currentRenderId = this._renderId;
  8635. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  8636. this._renderId = currentRenderId;
  8637. this._processSubCameras(this.activeCameras[cameraIndex]);
  8638. }
  8639. }
  8640. else {
  8641. if (!this.activeCamera) {
  8642. throw new Error("No camera defined");
  8643. }
  8644. this._processSubCameras(this.activeCamera);
  8645. }
  8646. // Intersection checks
  8647. this._checkIntersections();
  8648. // Update the audio listener attached to the camera
  8649. this._updateAudioParameters();
  8650. // After render
  8651. if (this.afterRender) {
  8652. this.afterRender();
  8653. }
  8654. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  8655. this._onAfterRenderCallbacks[callbackIndex]();
  8656. }
  8657. for (var index = 0; index < this._toBeDisposed.length; index++) {
  8658. this._toBeDisposed.data[index].dispose();
  8659. this._toBeDisposed[index] = null;
  8660. }
  8661. this._toBeDisposed.reset();
  8662. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  8663. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  8664. };
  8665. Scene.prototype._updateAudioParameters = function () {
  8666. var listeningCamera;
  8667. var audioEngine = BABYLON.Engine.audioEngine;
  8668. if (this.activeCameras.length > 0) {
  8669. listeningCamera = this.activeCameras[0];
  8670. }
  8671. else {
  8672. listeningCamera = this.activeCamera;
  8673. }
  8674. if (listeningCamera && audioEngine.canUseWebAudio) {
  8675. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  8676. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  8677. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  8678. cameraDirection.normalize();
  8679. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  8680. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  8681. var sound = this.mainSoundTrack.soundCollection[i];
  8682. if (sound.useCustomAttenuation) {
  8683. sound.updateDistanceFromListener();
  8684. }
  8685. }
  8686. for (i = 0; i < this.soundTracks.length; i++) {
  8687. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  8688. sound = this.soundTracks[i].soundCollection[j];
  8689. if (sound.useCustomAttenuation) {
  8690. sound.updateDistanceFromListener();
  8691. }
  8692. }
  8693. }
  8694. }
  8695. };
  8696. Scene.prototype.enableDepthRenderer = function () {
  8697. if (this._depthRenderer) {
  8698. return this._depthRenderer;
  8699. }
  8700. this._depthRenderer = new BABYLON.DepthRenderer(this);
  8701. return this._depthRenderer;
  8702. };
  8703. Scene.prototype.disableDepthRenderer = function () {
  8704. if (!this._depthRenderer) {
  8705. return;
  8706. }
  8707. this._depthRenderer.dispose();
  8708. this._depthRenderer = null;
  8709. };
  8710. Scene.prototype.dispose = function () {
  8711. this.beforeRender = null;
  8712. this.afterRender = null;
  8713. this.skeletons = [];
  8714. this._boundingBoxRenderer.dispose();
  8715. if (this._depthRenderer) {
  8716. this._depthRenderer.dispose();
  8717. }
  8718. // Debug layer
  8719. this.debugLayer.hide();
  8720. // Events
  8721. if (this.onDispose) {
  8722. this.onDispose();
  8723. }
  8724. this._onBeforeRenderCallbacks = [];
  8725. this._onAfterRenderCallbacks = [];
  8726. this.detachControl();
  8727. // Release sounds & sounds tracks
  8728. this.mainSoundTrack.dispose();
  8729. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  8730. this.soundTracks[scIndex].dispose();
  8731. }
  8732. // Detach cameras
  8733. var canvas = this._engine.getRenderingCanvas();
  8734. var index;
  8735. for (index = 0; index < this.cameras.length; index++) {
  8736. this.cameras[index].detachControl(canvas);
  8737. }
  8738. while (this.lights.length) {
  8739. this.lights[0].dispose();
  8740. }
  8741. while (this.meshes.length) {
  8742. this.meshes[0].dispose(true);
  8743. }
  8744. while (this.cameras.length) {
  8745. this.cameras[0].dispose();
  8746. }
  8747. while (this.materials.length) {
  8748. this.materials[0].dispose();
  8749. }
  8750. while (this.particleSystems.length) {
  8751. this.particleSystems[0].dispose();
  8752. }
  8753. while (this.spriteManagers.length) {
  8754. this.spriteManagers[0].dispose();
  8755. }
  8756. while (this.layers.length) {
  8757. this.layers[0].dispose();
  8758. }
  8759. while (this.textures.length) {
  8760. this.textures[0].dispose();
  8761. }
  8762. // Post-processes
  8763. this.postProcessManager.dispose();
  8764. // Physics
  8765. if (this._physicsEngine) {
  8766. this.disablePhysicsEngine();
  8767. }
  8768. // Remove from engine
  8769. index = this._engine.scenes.indexOf(this);
  8770. if (index > -1) {
  8771. this._engine.scenes.splice(index, 1);
  8772. }
  8773. this._engine.wipeCaches();
  8774. };
  8775. // Collisions
  8776. Scene.prototype._getNewPosition = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  8777. if (excludedMesh === void 0) { excludedMesh = null; }
  8778. position.divideToRef(collider.radius, this._scaledPosition);
  8779. velocity.divideToRef(collider.radius, this._scaledVelocity);
  8780. collider.retry = 0;
  8781. collider.initialVelocity = this._scaledVelocity;
  8782. collider.initialPosition = this._scaledPosition;
  8783. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, finalPosition, excludedMesh);
  8784. finalPosition.multiplyInPlace(collider.radius);
  8785. };
  8786. Scene.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  8787. if (excludedMesh === void 0) { excludedMesh = null; }
  8788. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  8789. if (collider.retry >= maximumRetry) {
  8790. finalPosition.copyFrom(position);
  8791. return;
  8792. }
  8793. collider._initialize(position, velocity, closeDistance);
  8794. for (var index = 0; index < this.meshes.length; index++) {
  8795. var mesh = this.meshes[index];
  8796. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  8797. mesh._checkCollision(collider);
  8798. }
  8799. }
  8800. if (!collider.collisionFound) {
  8801. position.addToRef(velocity, finalPosition);
  8802. return;
  8803. }
  8804. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  8805. collider._getResponse(position, velocity);
  8806. }
  8807. if (velocity.length() <= closeDistance) {
  8808. finalPosition.copyFrom(position);
  8809. return;
  8810. }
  8811. collider.retry++;
  8812. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  8813. };
  8814. // Octrees
  8815. Scene.prototype.getWorldExtends = function () {
  8816. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8817. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8818. for (var index = 0; index < this.meshes.length; index++) {
  8819. var mesh = this.meshes[index];
  8820. mesh.computeWorldMatrix(true);
  8821. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  8822. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  8823. BABYLON.Tools.CheckExtends(minBox, min, max);
  8824. BABYLON.Tools.CheckExtends(maxBox, min, max);
  8825. }
  8826. return {
  8827. min: min,
  8828. max: max
  8829. };
  8830. };
  8831. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  8832. if (maxCapacity === void 0) { maxCapacity = 64; }
  8833. if (maxDepth === void 0) { maxDepth = 2; }
  8834. if (!this._selectionOctree) {
  8835. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  8836. }
  8837. var worldExtends = this.getWorldExtends();
  8838. // Update octree
  8839. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  8840. return this._selectionOctree;
  8841. };
  8842. // Picking
  8843. Scene.prototype.createPickingRay = function (x, y, world, camera) {
  8844. var engine = this._engine;
  8845. if (!camera) {
  8846. if (!this.activeCamera)
  8847. throw new Error("Active camera not set");
  8848. camera = this.activeCamera;
  8849. }
  8850. var cameraViewport = camera.viewport;
  8851. var viewport = cameraViewport.toGlobal(engine);
  8852. // Moving coordinates to local viewport world
  8853. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  8854. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  8855. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  8856. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  8857. };
  8858. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  8859. var pickingInfo = null;
  8860. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  8861. var mesh = this.meshes[meshIndex];
  8862. if (predicate) {
  8863. if (!predicate(mesh)) {
  8864. continue;
  8865. }
  8866. }
  8867. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  8868. continue;
  8869. }
  8870. var world = mesh.getWorldMatrix();
  8871. var ray = rayFunction(world);
  8872. var result = mesh.intersects(ray, fastCheck);
  8873. if (!result || !result.hit)
  8874. continue;
  8875. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  8876. continue;
  8877. pickingInfo = result;
  8878. if (fastCheck) {
  8879. break;
  8880. }
  8881. }
  8882. return pickingInfo || new BABYLON.PickingInfo();
  8883. };
  8884. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  8885. var _this = this;
  8886. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  8887. /// <param name="x">X position on screen</param>
  8888. /// <param name="y">Y position on screen</param>
  8889. /// <param name="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</param>
  8890. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  8891. /// <param name="camera">camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used</param>
  8892. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  8893. };
  8894. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  8895. var _this = this;
  8896. return this._internalPick(function (world) {
  8897. if (!_this._pickWithRayInverseMatrix) {
  8898. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  8899. }
  8900. world.invertToRef(_this._pickWithRayInverseMatrix);
  8901. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  8902. }, predicate, fastCheck);
  8903. };
  8904. Scene.prototype.setPointerOverMesh = function (mesh) {
  8905. if (this._pointerOverMesh === mesh) {
  8906. return;
  8907. }
  8908. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  8909. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  8910. }
  8911. this._pointerOverMesh = mesh;
  8912. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  8913. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  8914. }
  8915. };
  8916. Scene.prototype.getPointerOverMesh = function () {
  8917. return this._pointerOverMesh;
  8918. };
  8919. // Physics
  8920. Scene.prototype.getPhysicsEngine = function () {
  8921. return this._physicsEngine;
  8922. };
  8923. Scene.prototype.enablePhysics = function (gravity, plugin) {
  8924. if (this._physicsEngine) {
  8925. return true;
  8926. }
  8927. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  8928. if (!this._physicsEngine.isSupported()) {
  8929. this._physicsEngine = null;
  8930. return false;
  8931. }
  8932. this._physicsEngine._initialize(gravity);
  8933. return true;
  8934. };
  8935. Scene.prototype.disablePhysicsEngine = function () {
  8936. if (!this._physicsEngine) {
  8937. return;
  8938. }
  8939. this._physicsEngine.dispose();
  8940. this._physicsEngine = undefined;
  8941. };
  8942. Scene.prototype.isPhysicsEnabled = function () {
  8943. return this._physicsEngine !== undefined;
  8944. };
  8945. Scene.prototype.setGravity = function (gravity) {
  8946. if (!this._physicsEngine) {
  8947. return;
  8948. }
  8949. this._physicsEngine._setGravity(gravity);
  8950. };
  8951. Scene.prototype.createCompoundImpostor = function (parts, options) {
  8952. if (parts.parts) {
  8953. options = parts;
  8954. parts = parts.parts;
  8955. }
  8956. if (!this._physicsEngine) {
  8957. return null;
  8958. }
  8959. for (var index = 0; index < parts.length; index++) {
  8960. var mesh = parts[index].mesh;
  8961. mesh._physicImpostor = parts[index].impostor;
  8962. mesh._physicsMass = options.mass / parts.length;
  8963. mesh._physicsFriction = options.friction;
  8964. mesh._physicRestitution = options.restitution;
  8965. }
  8966. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  8967. };
  8968. Scene.prototype.deleteCompoundImpostor = function (compound) {
  8969. for (var index = 0; index < compound.parts.length; index++) {
  8970. var mesh = compound.parts[index].mesh;
  8971. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  8972. this._physicsEngine._unregisterMesh(mesh);
  8973. }
  8974. };
  8975. // Misc.
  8976. Scene.prototype.createDefaultCameraOrLight = function () {
  8977. // Light
  8978. if (this.lights.length === 0) {
  8979. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  8980. }
  8981. // Camera
  8982. if (!this.activeCamera) {
  8983. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  8984. // Compute position
  8985. var worldExtends = this.getWorldExtends();
  8986. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  8987. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  8988. camera.setTarget(worldCenter);
  8989. this.activeCamera = camera;
  8990. }
  8991. };
  8992. // Tags
  8993. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  8994. if (tagsQuery === undefined) {
  8995. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  8996. return list;
  8997. }
  8998. var listByTags = [];
  8999. forEach = forEach || (function (item) {
  9000. return;
  9001. });
  9002. for (var i in list) {
  9003. var item = list[i];
  9004. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  9005. listByTags.push(item);
  9006. forEach(item);
  9007. }
  9008. }
  9009. return listByTags;
  9010. };
  9011. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  9012. return this._getByTags(this.meshes, tagsQuery, forEach);
  9013. };
  9014. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  9015. return this._getByTags(this.cameras, tagsQuery, forEach);
  9016. };
  9017. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  9018. return this._getByTags(this.lights, tagsQuery, forEach);
  9019. };
  9020. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  9021. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  9022. };
  9023. // Statics
  9024. Scene._FOGMODE_NONE = 0;
  9025. Scene._FOGMODE_EXP = 1;
  9026. Scene._FOGMODE_EXP2 = 2;
  9027. Scene._FOGMODE_LINEAR = 3;
  9028. Scene.MinDeltaTime = 1.0;
  9029. Scene.MaxDeltaTime = 1000.0;
  9030. return Scene;
  9031. })();
  9032. BABYLON.Scene = Scene;
  9033. })(BABYLON || (BABYLON = {}));
  9034. //# sourceMappingURL=babylon.scene.js.mapvar BABYLON;
  9035. (function (BABYLON) {
  9036. var VertexBuffer = (function () {
  9037. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  9038. if (engine instanceof BABYLON.Mesh) {
  9039. this._engine = engine.getScene().getEngine();
  9040. }
  9041. else {
  9042. this._engine = engine;
  9043. }
  9044. this._updatable = updatable;
  9045. this._data = data;
  9046. if (!postponeInternalCreation) {
  9047. this.create();
  9048. }
  9049. this._kind = kind;
  9050. if (stride) {
  9051. this._strideSize = stride;
  9052. return;
  9053. }
  9054. switch (kind) {
  9055. case VertexBuffer.PositionKind:
  9056. this._strideSize = 3;
  9057. break;
  9058. case VertexBuffer.NormalKind:
  9059. this._strideSize = 3;
  9060. break;
  9061. case VertexBuffer.UVKind:
  9062. this._strideSize = 2;
  9063. break;
  9064. case VertexBuffer.UV2Kind:
  9065. this._strideSize = 2;
  9066. break;
  9067. case VertexBuffer.ColorKind:
  9068. this._strideSize = 4;
  9069. break;
  9070. case VertexBuffer.MatricesIndicesKind:
  9071. this._strideSize = 4;
  9072. break;
  9073. case VertexBuffer.MatricesWeightsKind:
  9074. this._strideSize = 4;
  9075. break;
  9076. }
  9077. }
  9078. // Properties
  9079. VertexBuffer.prototype.isUpdatable = function () {
  9080. return this._updatable;
  9081. };
  9082. VertexBuffer.prototype.getData = function () {
  9083. return this._data;
  9084. };
  9085. VertexBuffer.prototype.getBuffer = function () {
  9086. return this._buffer;
  9087. };
  9088. VertexBuffer.prototype.getStrideSize = function () {
  9089. return this._strideSize;
  9090. };
  9091. // Methods
  9092. VertexBuffer.prototype.create = function (data) {
  9093. if (!data && this._buffer) {
  9094. return; // nothing to do
  9095. }
  9096. data = data || this._data;
  9097. if (!this._buffer) {
  9098. if (this._updatable) {
  9099. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  9100. }
  9101. else {
  9102. this._buffer = this._engine.createVertexBuffer(data);
  9103. }
  9104. }
  9105. if (this._updatable) {
  9106. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  9107. this._data = data;
  9108. }
  9109. };
  9110. VertexBuffer.prototype.update = function (data) {
  9111. this.create(data);
  9112. };
  9113. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  9114. if (!this._buffer) {
  9115. return;
  9116. }
  9117. if (this._updatable) {
  9118. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  9119. this._data = null;
  9120. }
  9121. };
  9122. VertexBuffer.prototype.dispose = function () {
  9123. if (!this._buffer) {
  9124. return;
  9125. }
  9126. if (this._engine._releaseBuffer(this._buffer)) {
  9127. this._buffer = null;
  9128. }
  9129. };
  9130. Object.defineProperty(VertexBuffer, "PositionKind", {
  9131. get: function () {
  9132. return VertexBuffer._PositionKind;
  9133. },
  9134. enumerable: true,
  9135. configurable: true
  9136. });
  9137. Object.defineProperty(VertexBuffer, "NormalKind", {
  9138. get: function () {
  9139. return VertexBuffer._NormalKind;
  9140. },
  9141. enumerable: true,
  9142. configurable: true
  9143. });
  9144. Object.defineProperty(VertexBuffer, "UVKind", {
  9145. get: function () {
  9146. return VertexBuffer._UVKind;
  9147. },
  9148. enumerable: true,
  9149. configurable: true
  9150. });
  9151. Object.defineProperty(VertexBuffer, "UV2Kind", {
  9152. get: function () {
  9153. return VertexBuffer._UV2Kind;
  9154. },
  9155. enumerable: true,
  9156. configurable: true
  9157. });
  9158. Object.defineProperty(VertexBuffer, "ColorKind", {
  9159. get: function () {
  9160. return VertexBuffer._ColorKind;
  9161. },
  9162. enumerable: true,
  9163. configurable: true
  9164. });
  9165. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  9166. get: function () {
  9167. return VertexBuffer._MatricesIndicesKind;
  9168. },
  9169. enumerable: true,
  9170. configurable: true
  9171. });
  9172. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  9173. get: function () {
  9174. return VertexBuffer._MatricesWeightsKind;
  9175. },
  9176. enumerable: true,
  9177. configurable: true
  9178. });
  9179. // Enums
  9180. VertexBuffer._PositionKind = "position";
  9181. VertexBuffer._NormalKind = "normal";
  9182. VertexBuffer._UVKind = "uv";
  9183. VertexBuffer._UV2Kind = "uv2";
  9184. VertexBuffer._ColorKind = "color";
  9185. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  9186. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  9187. return VertexBuffer;
  9188. })();
  9189. BABYLON.VertexBuffer = VertexBuffer;
  9190. })(BABYLON || (BABYLON = {}));
  9191. //# sourceMappingURL=babylon.vertexBuffer.js.map
  9192. var BABYLON;
  9193. (function (BABYLON) {
  9194. var AbstractMesh = (function (_super) {
  9195. __extends(AbstractMesh, _super);
  9196. function AbstractMesh(name, scene) {
  9197. _super.call(this, name, scene);
  9198. // Properties
  9199. this.definedFacingForward = true; // orientation for POV movement & rotation
  9200. this.position = new BABYLON.Vector3(0, 0, 0);
  9201. this.rotation = new BABYLON.Vector3(0, 0, 0);
  9202. this.scaling = new BABYLON.Vector3(1, 1, 1);
  9203. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  9204. this.visibility = 1.0;
  9205. this.alphaIndex = Number.MAX_VALUE;
  9206. this.infiniteDistance = false;
  9207. this.isVisible = true;
  9208. this.isPickable = true;
  9209. this.showBoundingBox = false;
  9210. this.showSubMeshesBoundingBox = false;
  9211. this.onDispose = null;
  9212. this.checkCollisions = false;
  9213. this.isBlocker = false;
  9214. this.renderingGroupId = 0;
  9215. this.receiveShadows = false;
  9216. this.renderOutline = false;
  9217. this.outlineColor = BABYLON.Color3.Red();
  9218. this.outlineWidth = 0.02;
  9219. this.renderOverlay = false;
  9220. this.overlayColor = BABYLON.Color3.Red();
  9221. this.overlayAlpha = 0.5;
  9222. this.hasVertexAlpha = false;
  9223. this.useVertexColors = true;
  9224. this.applyFog = true;
  9225. this.useOctreeForRenderingSelection = true;
  9226. this.useOctreeForPicking = true;
  9227. this.useOctreeForCollisions = true;
  9228. this.layerMask = 0xFFFFFFFF;
  9229. // Physics
  9230. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  9231. // Collisions
  9232. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  9233. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  9234. this._collider = new BABYLON.Collider();
  9235. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  9236. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  9237. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  9238. // Cache
  9239. this._localScaling = BABYLON.Matrix.Zero();
  9240. this._localRotation = BABYLON.Matrix.Zero();
  9241. this._localTranslation = BABYLON.Matrix.Zero();
  9242. this._localBillboard = BABYLON.Matrix.Zero();
  9243. this._localPivotScaling = BABYLON.Matrix.Zero();
  9244. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  9245. this._localWorld = BABYLON.Matrix.Zero();
  9246. this._worldMatrix = BABYLON.Matrix.Zero();
  9247. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  9248. this._absolutePosition = BABYLON.Vector3.Zero();
  9249. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  9250. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  9251. this._isDirty = false;
  9252. this._pivotMatrix = BABYLON.Matrix.Identity();
  9253. this._isDisposed = false;
  9254. this._renderId = 0;
  9255. this._intersectionsInProgress = new Array();
  9256. this._onAfterWorldMatrixUpdate = new Array();
  9257. scene.meshes.push(this);
  9258. }
  9259. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  9260. get: function () {
  9261. return AbstractMesh._BILLBOARDMODE_NONE;
  9262. },
  9263. enumerable: true,
  9264. configurable: true
  9265. });
  9266. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  9267. get: function () {
  9268. return AbstractMesh._BILLBOARDMODE_X;
  9269. },
  9270. enumerable: true,
  9271. configurable: true
  9272. });
  9273. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  9274. get: function () {
  9275. return AbstractMesh._BILLBOARDMODE_Y;
  9276. },
  9277. enumerable: true,
  9278. configurable: true
  9279. });
  9280. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  9281. get: function () {
  9282. return AbstractMesh._BILLBOARDMODE_Z;
  9283. },
  9284. enumerable: true,
  9285. configurable: true
  9286. });
  9287. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  9288. get: function () {
  9289. return AbstractMesh._BILLBOARDMODE_ALL;
  9290. },
  9291. enumerable: true,
  9292. configurable: true
  9293. });
  9294. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  9295. // Methods
  9296. get: function () {
  9297. return false;
  9298. },
  9299. enumerable: true,
  9300. configurable: true
  9301. });
  9302. AbstractMesh.prototype.getLOD = function (camera) {
  9303. return this;
  9304. };
  9305. AbstractMesh.prototype.getTotalVertices = function () {
  9306. return 0;
  9307. };
  9308. AbstractMesh.prototype.getIndices = function () {
  9309. return null;
  9310. };
  9311. AbstractMesh.prototype.getVerticesData = function (kind) {
  9312. return null;
  9313. };
  9314. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  9315. return false;
  9316. };
  9317. AbstractMesh.prototype.getBoundingInfo = function () {
  9318. if (this._masterMesh) {
  9319. return this._masterMesh.getBoundingInfo();
  9320. }
  9321. if (!this._boundingInfo) {
  9322. this._updateBoundingInfo();
  9323. }
  9324. return this._boundingInfo;
  9325. };
  9326. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  9327. get: function () {
  9328. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  9329. },
  9330. enumerable: true,
  9331. configurable: true
  9332. });
  9333. AbstractMesh.prototype._preActivate = function () {
  9334. };
  9335. AbstractMesh.prototype._activate = function (renderId) {
  9336. this._renderId = renderId;
  9337. };
  9338. AbstractMesh.prototype.getWorldMatrix = function () {
  9339. if (this._masterMesh) {
  9340. return this._masterMesh.getWorldMatrix();
  9341. }
  9342. if (this._currentRenderId !== this.getScene().getRenderId()) {
  9343. this.computeWorldMatrix();
  9344. }
  9345. return this._worldMatrix;
  9346. };
  9347. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  9348. get: function () {
  9349. return this._worldMatrix;
  9350. },
  9351. enumerable: true,
  9352. configurable: true
  9353. });
  9354. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  9355. get: function () {
  9356. return this._absolutePosition;
  9357. },
  9358. enumerable: true,
  9359. configurable: true
  9360. });
  9361. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  9362. if (!this.rotationQuaternion) {
  9363. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  9364. this.rotation = BABYLON.Vector3.Zero();
  9365. }
  9366. if (!space || space == 0 /* LOCAL */) {
  9367. var rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  9368. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  9369. }
  9370. else {
  9371. if (this.parent) {
  9372. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  9373. invertParentWorldMatrix.invert();
  9374. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  9375. }
  9376. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  9377. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  9378. }
  9379. };
  9380. AbstractMesh.prototype.translate = function (axis, distance, space) {
  9381. var displacementVector = axis.scale(distance);
  9382. if (!space || space == 0 /* LOCAL */) {
  9383. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  9384. this.setPositionWithLocalVector(tempV3);
  9385. }
  9386. else {
  9387. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  9388. }
  9389. };
  9390. AbstractMesh.prototype.getAbsolutePosition = function () {
  9391. this.computeWorldMatrix();
  9392. return this._absolutePosition;
  9393. };
  9394. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  9395. if (!absolutePosition) {
  9396. return;
  9397. }
  9398. var absolutePositionX;
  9399. var absolutePositionY;
  9400. var absolutePositionZ;
  9401. if (absolutePosition.x === undefined) {
  9402. if (arguments.length < 3) {
  9403. return;
  9404. }
  9405. absolutePositionX = arguments[0];
  9406. absolutePositionY = arguments[1];
  9407. absolutePositionZ = arguments[2];
  9408. }
  9409. else {
  9410. absolutePositionX = absolutePosition.x;
  9411. absolutePositionY = absolutePosition.y;
  9412. absolutePositionZ = absolutePosition.z;
  9413. }
  9414. if (this.parent) {
  9415. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  9416. invertParentWorldMatrix.invert();
  9417. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  9418. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  9419. }
  9420. else {
  9421. this.position.x = absolutePositionX;
  9422. this.position.y = absolutePositionY;
  9423. this.position.z = absolutePositionZ;
  9424. }
  9425. };
  9426. // ================================== Point of View Movement =================================
  9427. /**
  9428. * Perform relative position change from the point of view of behind the front of the mesh.
  9429. * This is performed taking into account the meshes current rotation, so you do not have to care.
  9430. * Supports definition of mesh facing forward or backward.
  9431. * @param {number} amountRight
  9432. * @param {number} amountUp
  9433. * @param {number} amountForward
  9434. */
  9435. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  9436. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  9437. };
  9438. /**
  9439. * Calculate relative position change from the point of view of behind the front of the mesh.
  9440. * This is performed taking into account the meshes current rotation, so you do not have to care.
  9441. * Supports definition of mesh facing forward or backward.
  9442. * @param {number} amountRight
  9443. * @param {number} amountUp
  9444. * @param {number} amountForward
  9445. */
  9446. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  9447. var rotMatrix = new BABYLON.Matrix();
  9448. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  9449. rotQuaternion.toRotationMatrix(rotMatrix);
  9450. var translationDelta = BABYLON.Vector3.Zero();
  9451. var defForwardMult = this.definedFacingForward ? -1 : 1;
  9452. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  9453. return translationDelta;
  9454. };
  9455. // ================================== Point of View Rotation =================================
  9456. /**
  9457. * Perform relative rotation change from the point of view of behind the front of the mesh.
  9458. * Supports definition of mesh facing forward or backward.
  9459. * @param {number} flipBack
  9460. * @param {number} twirlClockwise
  9461. * @param {number} tiltRight
  9462. */
  9463. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  9464. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  9465. };
  9466. /**
  9467. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  9468. * Supports definition of mesh facing forward or backward.
  9469. * @param {number} flipBack
  9470. * @param {number} twirlClockwise
  9471. * @param {number} tiltRight
  9472. */
  9473. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  9474. var defForwardMult = this.definedFacingForward ? 1 : -1;
  9475. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  9476. };
  9477. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  9478. this._pivotMatrix = matrix;
  9479. this._cache.pivotMatrixUpdated = true;
  9480. };
  9481. AbstractMesh.prototype.getPivotMatrix = function () {
  9482. return this._pivotMatrix;
  9483. };
  9484. AbstractMesh.prototype._isSynchronized = function () {
  9485. if (this._isDirty) {
  9486. return false;
  9487. }
  9488. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  9489. return false;
  9490. if (this._cache.pivotMatrixUpdated) {
  9491. return false;
  9492. }
  9493. if (this.infiniteDistance) {
  9494. return false;
  9495. }
  9496. if (!this._cache.position.equals(this.position))
  9497. return false;
  9498. if (this.rotationQuaternion) {
  9499. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  9500. return false;
  9501. }
  9502. else {
  9503. if (!this._cache.rotation.equals(this.rotation))
  9504. return false;
  9505. }
  9506. if (!this._cache.scaling.equals(this.scaling))
  9507. return false;
  9508. return true;
  9509. };
  9510. AbstractMesh.prototype._initCache = function () {
  9511. _super.prototype._initCache.call(this);
  9512. this._cache.localMatrixUpdated = false;
  9513. this._cache.position = BABYLON.Vector3.Zero();
  9514. this._cache.scaling = BABYLON.Vector3.Zero();
  9515. this._cache.rotation = BABYLON.Vector3.Zero();
  9516. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  9517. };
  9518. AbstractMesh.prototype.markAsDirty = function (property) {
  9519. if (property === "rotation") {
  9520. this.rotationQuaternion = null;
  9521. }
  9522. this._currentRenderId = Number.MAX_VALUE;
  9523. this._isDirty = true;
  9524. };
  9525. AbstractMesh.prototype._updateBoundingInfo = function () {
  9526. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  9527. this._boundingInfo._update(this.worldMatrixFromCache);
  9528. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  9529. };
  9530. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  9531. if (!this.subMeshes) {
  9532. return;
  9533. }
  9534. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  9535. var subMesh = this.subMeshes[subIndex];
  9536. subMesh.updateBoundingInfo(matrix);
  9537. }
  9538. };
  9539. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  9540. if (!force && (this._currentRenderId == this.getScene().getRenderId() || this.isSynchronized(true))) {
  9541. return this._worldMatrix;
  9542. }
  9543. this._cache.position.copyFrom(this.position);
  9544. this._cache.scaling.copyFrom(this.scaling);
  9545. this._cache.pivotMatrixUpdated = false;
  9546. this._currentRenderId = this.getScene().getRenderId();
  9547. this._isDirty = false;
  9548. // Scaling
  9549. BABYLON.Matrix.ScalingToRef(this.scaling.x, this.scaling.y, this.scaling.z, this._localScaling);
  9550. // Rotation
  9551. if (this.rotationQuaternion) {
  9552. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  9553. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  9554. }
  9555. else {
  9556. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  9557. this._cache.rotation.copyFrom(this.rotation);
  9558. }
  9559. // Translation
  9560. if (this.infiniteDistance && !this.parent) {
  9561. var camera = this.getScene().activeCamera;
  9562. var cameraWorldMatrix = camera.getWorldMatrix();
  9563. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  9564. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  9565. }
  9566. else {
  9567. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  9568. }
  9569. // Composing transformations
  9570. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  9571. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  9572. // Billboarding
  9573. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  9574. var localPosition = this.position.clone();
  9575. var zero = this.getScene().activeCamera.position.clone();
  9576. if (this.parent && this.parent.position) {
  9577. localPosition.addInPlace(this.parent.position);
  9578. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  9579. }
  9580. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) === AbstractMesh.BILLBOARDMODE_ALL) {
  9581. zero = this.getScene().activeCamera.position;
  9582. }
  9583. else {
  9584. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X)
  9585. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  9586. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y)
  9587. zero.y = localPosition.y + 0.001;
  9588. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z)
  9589. zero.z = localPosition.z + 0.001;
  9590. }
  9591. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  9592. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  9593. this._localBillboard.invert();
  9594. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  9595. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  9596. }
  9597. // Local world
  9598. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  9599. // Parent
  9600. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  9601. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  9602. }
  9603. else {
  9604. this._worldMatrix.copyFrom(this._localWorld);
  9605. }
  9606. // Bounding info
  9607. this._updateBoundingInfo();
  9608. // Absolute position
  9609. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  9610. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  9611. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  9612. }
  9613. return this._worldMatrix;
  9614. };
  9615. /**
  9616. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  9617. * @param func: callback function to add
  9618. */
  9619. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  9620. this._onAfterWorldMatrixUpdate.push(func);
  9621. };
  9622. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  9623. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  9624. if (index > -1) {
  9625. this._onAfterWorldMatrixUpdate.splice(index, 1);
  9626. }
  9627. };
  9628. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  9629. this.computeWorldMatrix();
  9630. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  9631. };
  9632. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  9633. this.computeWorldMatrix();
  9634. var invLocalWorldMatrix = this._localWorld.clone();
  9635. invLocalWorldMatrix.invert();
  9636. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  9637. };
  9638. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  9639. this.computeWorldMatrix();
  9640. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  9641. };
  9642. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  9643. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  9644. /// <param name="targetPoint" type="BABYLON.Vector3">The position (must be in same space as current mesh) to look at</param>
  9645. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  9646. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  9647. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  9648. /// <returns>Mesh oriented towards targetMesh</returns>
  9649. yawCor = yawCor || 0; // default to zero if undefined
  9650. pitchCor = pitchCor || 0;
  9651. rollCor = rollCor || 0;
  9652. var dv = targetPoint.subtract(this.position);
  9653. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  9654. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  9655. var pitch = Math.atan2(dv.y, len);
  9656. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  9657. };
  9658. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  9659. if (!this._boundingInfo.isInFrustum(frustumPlanes)) {
  9660. return false;
  9661. }
  9662. return true;
  9663. };
  9664. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  9665. if (!camera) {
  9666. camera = this.getScene().activeCamera;
  9667. }
  9668. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  9669. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  9670. return false;
  9671. }
  9672. return true;
  9673. };
  9674. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  9675. if (!this._boundingInfo || !mesh._boundingInfo) {
  9676. return false;
  9677. }
  9678. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  9679. };
  9680. AbstractMesh.prototype.intersectsPoint = function (point) {
  9681. if (!this._boundingInfo) {
  9682. return false;
  9683. }
  9684. return this._boundingInfo.intersectsPoint(point);
  9685. };
  9686. // Physics
  9687. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  9688. var physicsEngine = this.getScene().getPhysicsEngine();
  9689. if (!physicsEngine) {
  9690. return;
  9691. }
  9692. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  9693. if (impostor.impostor) {
  9694. // Old API
  9695. options = impostor;
  9696. impostor = impostor.impostor;
  9697. }
  9698. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  9699. physicsEngine._unregisterMesh(this);
  9700. return;
  9701. }
  9702. if (!options) {
  9703. options = { mass: 0, friction: 0.2, restitution: 0.2 };
  9704. }
  9705. else {
  9706. if (!options.mass && options.mass !== 0)
  9707. options.mass = 0;
  9708. if (!options.friction && options.friction !== 0)
  9709. options.friction = 0.2;
  9710. if (!options.restitution && options.restitution !== 0)
  9711. options.restitution = 0.2;
  9712. }
  9713. this._physicImpostor = impostor;
  9714. this._physicsMass = options.mass;
  9715. this._physicsFriction = options.friction;
  9716. this._physicRestitution = options.restitution;
  9717. return physicsEngine._registerMesh(this, impostor, options);
  9718. };
  9719. AbstractMesh.prototype.getPhysicsImpostor = function () {
  9720. if (!this._physicImpostor) {
  9721. return BABYLON.PhysicsEngine.NoImpostor;
  9722. }
  9723. return this._physicImpostor;
  9724. };
  9725. AbstractMesh.prototype.getPhysicsMass = function () {
  9726. if (!this._physicsMass) {
  9727. return 0;
  9728. }
  9729. return this._physicsMass;
  9730. };
  9731. AbstractMesh.prototype.getPhysicsFriction = function () {
  9732. if (!this._physicsFriction) {
  9733. return 0;
  9734. }
  9735. return this._physicsFriction;
  9736. };
  9737. AbstractMesh.prototype.getPhysicsRestitution = function () {
  9738. if (!this._physicRestitution) {
  9739. return 0;
  9740. }
  9741. return this._physicRestitution;
  9742. };
  9743. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  9744. if (!camera) {
  9745. camera = this.getScene().activeCamera;
  9746. }
  9747. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  9748. };
  9749. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  9750. if (!camera) {
  9751. camera = this.getScene().activeCamera;
  9752. }
  9753. return this.absolutePosition.subtract(camera.position).length();
  9754. };
  9755. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  9756. if (!this._physicImpostor) {
  9757. return;
  9758. }
  9759. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  9760. };
  9761. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  9762. if (!this._physicImpostor) {
  9763. return;
  9764. }
  9765. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  9766. };
  9767. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  9768. if (!this._physicImpostor) {
  9769. return;
  9770. }
  9771. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  9772. };
  9773. // Collisions
  9774. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  9775. var globalPosition = this.getAbsolutePosition();
  9776. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  9777. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  9778. this._collider.radius = this.ellipsoid;
  9779. this.getScene()._getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this._newPositionForCollisions, this);
  9780. this._newPositionForCollisions.subtractToRef(this._oldPositionForCollisions, this._diffPositionForCollisions);
  9781. if (this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  9782. this.position.addInPlace(this._diffPositionForCollisions);
  9783. }
  9784. };
  9785. // Submeshes octree
  9786. /**
  9787. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  9788. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  9789. */
  9790. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  9791. if (maxCapacity === void 0) { maxCapacity = 64; }
  9792. if (maxDepth === void 0) { maxDepth = 2; }
  9793. if (!this._submeshesOctree) {
  9794. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  9795. }
  9796. this.computeWorldMatrix(true);
  9797. // Update octree
  9798. var bbox = this.getBoundingInfo().boundingBox;
  9799. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  9800. return this._submeshesOctree;
  9801. };
  9802. // Collisions
  9803. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  9804. this._generatePointsArray();
  9805. // Transformation
  9806. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  9807. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  9808. subMesh._lastColliderWorldVertices = [];
  9809. subMesh._trianglePlanes = [];
  9810. var start = subMesh.verticesStart;
  9811. var end = (subMesh.verticesStart + subMesh.verticesCount);
  9812. for (var i = start; i < end; i++) {
  9813. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  9814. }
  9815. }
  9816. // Collide
  9817. collider._collide(subMesh, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart);
  9818. };
  9819. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  9820. var subMeshes;
  9821. var len;
  9822. // Octrees
  9823. if (this._submeshesOctree && this.useOctreeForCollisions) {
  9824. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  9825. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  9826. len = intersections.length;
  9827. subMeshes = intersections.data;
  9828. }
  9829. else {
  9830. subMeshes = this.subMeshes;
  9831. len = subMeshes.length;
  9832. }
  9833. for (var index = 0; index < len; index++) {
  9834. var subMesh = subMeshes[index];
  9835. // Bounding test
  9836. if (len > 1 && !subMesh._checkCollision(collider))
  9837. continue;
  9838. this._collideForSubMesh(subMesh, transformMatrix, collider);
  9839. }
  9840. };
  9841. AbstractMesh.prototype._checkCollision = function (collider) {
  9842. // Bounding box test
  9843. if (!this._boundingInfo._checkCollision(collider))
  9844. return;
  9845. // Transformation matrix
  9846. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  9847. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  9848. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  9849. };
  9850. // Picking
  9851. AbstractMesh.prototype._generatePointsArray = function () {
  9852. return false;
  9853. };
  9854. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  9855. var pickingInfo = new BABYLON.PickingInfo();
  9856. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  9857. return pickingInfo;
  9858. }
  9859. if (!this._generatePointsArray()) {
  9860. return pickingInfo;
  9861. }
  9862. var intersectInfo = null;
  9863. // Octrees
  9864. var subMeshes;
  9865. var len;
  9866. if (this._submeshesOctree && this.useOctreeForPicking) {
  9867. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  9868. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  9869. len = intersections.length;
  9870. subMeshes = intersections.data;
  9871. }
  9872. else {
  9873. subMeshes = this.subMeshes;
  9874. len = subMeshes.length;
  9875. }
  9876. for (var index = 0; index < len; index++) {
  9877. var subMesh = subMeshes[index];
  9878. // Bounding test
  9879. if (len > 1 && !subMesh.canIntersects(ray))
  9880. continue;
  9881. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  9882. if (currentIntersectInfo) {
  9883. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  9884. intersectInfo = currentIntersectInfo;
  9885. if (fastCheck) {
  9886. break;
  9887. }
  9888. }
  9889. }
  9890. }
  9891. if (intersectInfo) {
  9892. // Get picked point
  9893. var world = this.getWorldMatrix();
  9894. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  9895. var direction = ray.direction.clone();
  9896. direction = direction.scale(intersectInfo.distance);
  9897. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  9898. var pickedPoint = worldOrigin.add(worldDirection);
  9899. // Return result
  9900. pickingInfo.hit = true;
  9901. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  9902. pickingInfo.pickedPoint = pickedPoint;
  9903. pickingInfo.pickedMesh = this;
  9904. pickingInfo.bu = intersectInfo.bu;
  9905. pickingInfo.bv = intersectInfo.bv;
  9906. pickingInfo.faceId = intersectInfo.faceId;
  9907. return pickingInfo;
  9908. }
  9909. return pickingInfo;
  9910. };
  9911. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  9912. return null;
  9913. };
  9914. AbstractMesh.prototype.releaseSubMeshes = function () {
  9915. if (this.subMeshes) {
  9916. while (this.subMeshes.length) {
  9917. this.subMeshes[0].dispose();
  9918. }
  9919. }
  9920. else {
  9921. this.subMeshes = new Array();
  9922. }
  9923. };
  9924. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  9925. // Physics
  9926. if (this.getPhysicsImpostor() != BABYLON.PhysicsEngine.NoImpostor) {
  9927. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  9928. }
  9929. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  9930. var other = this._intersectionsInProgress[index];
  9931. var pos = other._intersectionsInProgress.indexOf(this);
  9932. other._intersectionsInProgress.splice(pos, 1);
  9933. }
  9934. this._intersectionsInProgress = [];
  9935. // SubMeshes
  9936. this.releaseSubMeshes();
  9937. // Remove from scene
  9938. var index = this.getScene().meshes.indexOf(this);
  9939. if (index != -1) {
  9940. // Remove from the scene if mesh found
  9941. this.getScene().meshes.splice(index, 1);
  9942. }
  9943. if (!doNotRecurse) {
  9944. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  9945. if (this.getScene().particleSystems[index].emitter == this) {
  9946. this.getScene().particleSystems[index].dispose();
  9947. index--;
  9948. }
  9949. }
  9950. // Children
  9951. var objects = this.getScene().meshes.slice(0);
  9952. for (index = 0; index < objects.length; index++) {
  9953. if (objects[index].parent == this) {
  9954. objects[index].dispose();
  9955. }
  9956. }
  9957. }
  9958. else {
  9959. for (index = 0; index < this.getScene().meshes.length; index++) {
  9960. var obj = this.getScene().meshes[index];
  9961. if (obj.parent === this) {
  9962. obj.parent = null;
  9963. obj.computeWorldMatrix(true);
  9964. }
  9965. }
  9966. }
  9967. this._onAfterWorldMatrixUpdate = [];
  9968. this._isDisposed = true;
  9969. // Callback
  9970. if (this.onDispose) {
  9971. this.onDispose();
  9972. }
  9973. };
  9974. // Statics
  9975. AbstractMesh._BILLBOARDMODE_NONE = 0;
  9976. AbstractMesh._BILLBOARDMODE_X = 1;
  9977. AbstractMesh._BILLBOARDMODE_Y = 2;
  9978. AbstractMesh._BILLBOARDMODE_Z = 4;
  9979. AbstractMesh._BILLBOARDMODE_ALL = 7;
  9980. return AbstractMesh;
  9981. })(BABYLON.Node);
  9982. BABYLON.AbstractMesh = AbstractMesh;
  9983. })(BABYLON || (BABYLON = {}));
  9984. //# sourceMappingURL=babylon.abstractMesh.js.map
  9985. var BABYLON;
  9986. (function (BABYLON) {
  9987. var _InstancesBatch = (function () {
  9988. function _InstancesBatch() {
  9989. this.mustReturn = false;
  9990. this.visibleInstances = new Array();
  9991. this.renderSelf = new Array();
  9992. }
  9993. return _InstancesBatch;
  9994. })();
  9995. BABYLON._InstancesBatch = _InstancesBatch;
  9996. var Mesh = (function (_super) {
  9997. __extends(Mesh, _super);
  9998. /**
  9999. * @constructor
  10000. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  10001. * @param {Scene} scene - The scene to add this mesh to.
  10002. * @param {Node} parent - The parent of this mesh, if it has one
  10003. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  10004. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  10005. * When false, achieved by calling a clone(), also passing False.
  10006. * This will make creation of children, recursive.
  10007. */
  10008. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  10009. if (parent === void 0) { parent = null; }
  10010. _super.call(this, name, scene);
  10011. // Members
  10012. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  10013. this.instances = new Array();
  10014. this._LODLevels = new Array();
  10015. this._onBeforeRenderCallbacks = new Array();
  10016. this._onAfterRenderCallbacks = new Array();
  10017. this._visibleInstances = {};
  10018. this._renderIdForInstances = new Array();
  10019. this._batchCache = new _InstancesBatch();
  10020. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  10021. if (source) {
  10022. // Geometry
  10023. if (source._geometry) {
  10024. source._geometry.applyToMesh(this);
  10025. }
  10026. // Deep copy
  10027. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton"], []);
  10028. // Material
  10029. this.material = source.material;
  10030. if (!doNotCloneChildren) {
  10031. for (var index = 0; index < scene.meshes.length; index++) {
  10032. var mesh = scene.meshes[index];
  10033. if (mesh.parent === source) {
  10034. // doNotCloneChildren is always going to be False
  10035. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  10036. }
  10037. }
  10038. }
  10039. for (index = 0; index < scene.particleSystems.length; index++) {
  10040. var system = scene.particleSystems[index];
  10041. if (system.emitter === source) {
  10042. system.clone(system.name, this);
  10043. }
  10044. }
  10045. this.computeWorldMatrix(true);
  10046. }
  10047. // Parent
  10048. if (parent !== null) {
  10049. this.parent = parent;
  10050. }
  10051. }
  10052. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  10053. // Methods
  10054. get: function () {
  10055. return this._LODLevels.length > 0;
  10056. },
  10057. enumerable: true,
  10058. configurable: true
  10059. });
  10060. Mesh.prototype._sortLODLevels = function () {
  10061. this._LODLevels.sort(function (a, b) {
  10062. if (a.distance < b.distance) {
  10063. return 1;
  10064. }
  10065. if (a.distance > b.distance) {
  10066. return -1;
  10067. }
  10068. return 0;
  10069. });
  10070. };
  10071. /**
  10072. * Add a mesh as LOD level triggered at the given distance.
  10073. * @param {number} distance - the distance from the center of the object to show this level
  10074. * @param {BABYLON.Mesh} mesh - the mesh to be added as LOD level
  10075. * @return {BABYLON.Mesh} this mesh (for chaining)
  10076. */
  10077. Mesh.prototype.addLODLevel = function (distance, mesh) {
  10078. if (mesh && mesh._masterMesh) {
  10079. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  10080. return this;
  10081. }
  10082. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  10083. this._LODLevels.push(level);
  10084. if (mesh) {
  10085. mesh._masterMesh = this;
  10086. }
  10087. this._sortLODLevels();
  10088. return this;
  10089. };
  10090. /**
  10091. * Remove a mesh from the LOD array
  10092. * @param {BABYLON.Mesh} mesh - the mesh to be removed.
  10093. * @return {BABYLON.Mesh} this mesh (for chaining)
  10094. */
  10095. Mesh.prototype.removeLODLevel = function (mesh) {
  10096. for (var index = 0; index < this._LODLevels.length; index++) {
  10097. if (this._LODLevels[index].mesh === mesh) {
  10098. this._LODLevels.splice(index, 1);
  10099. if (mesh) {
  10100. mesh._masterMesh = null;
  10101. }
  10102. }
  10103. }
  10104. this._sortLODLevels();
  10105. return this;
  10106. };
  10107. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  10108. if (!this._LODLevels || this._LODLevels.length === 0) {
  10109. return this;
  10110. }
  10111. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  10112. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  10113. return this;
  10114. }
  10115. for (var index = 0; index < this._LODLevels.length; index++) {
  10116. var level = this._LODLevels[index];
  10117. if (level.distance < distanceToCamera) {
  10118. if (level.mesh) {
  10119. level.mesh._preActivate();
  10120. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  10121. }
  10122. return level.mesh;
  10123. }
  10124. }
  10125. return this;
  10126. };
  10127. Object.defineProperty(Mesh.prototype, "geometry", {
  10128. get: function () {
  10129. return this._geometry;
  10130. },
  10131. enumerable: true,
  10132. configurable: true
  10133. });
  10134. Mesh.prototype.getTotalVertices = function () {
  10135. if (!this._geometry) {
  10136. return 0;
  10137. }
  10138. return this._geometry.getTotalVertices();
  10139. };
  10140. Mesh.prototype.getVerticesData = function (kind) {
  10141. if (!this._geometry) {
  10142. return null;
  10143. }
  10144. return this._geometry.getVerticesData(kind);
  10145. };
  10146. Mesh.prototype.getVertexBuffer = function (kind) {
  10147. if (!this._geometry) {
  10148. return undefined;
  10149. }
  10150. return this._geometry.getVertexBuffer(kind);
  10151. };
  10152. Mesh.prototype.isVerticesDataPresent = function (kind) {
  10153. if (!this._geometry) {
  10154. if (this._delayInfo) {
  10155. return this._delayInfo.indexOf(kind) !== -1;
  10156. }
  10157. return false;
  10158. }
  10159. return this._geometry.isVerticesDataPresent(kind);
  10160. };
  10161. Mesh.prototype.getVerticesDataKinds = function () {
  10162. if (!this._geometry) {
  10163. var result = [];
  10164. if (this._delayInfo) {
  10165. for (var kind in this._delayInfo) {
  10166. result.push(kind);
  10167. }
  10168. }
  10169. return result;
  10170. }
  10171. return this._geometry.getVerticesDataKinds();
  10172. };
  10173. Mesh.prototype.getTotalIndices = function () {
  10174. if (!this._geometry) {
  10175. return 0;
  10176. }
  10177. return this._geometry.getTotalIndices();
  10178. };
  10179. Mesh.prototype.getIndices = function () {
  10180. if (!this._geometry) {
  10181. return [];
  10182. }
  10183. return this._geometry.getIndices();
  10184. };
  10185. Object.defineProperty(Mesh.prototype, "isBlocked", {
  10186. get: function () {
  10187. return this._masterMesh !== null && this._masterMesh !== undefined;
  10188. },
  10189. enumerable: true,
  10190. configurable: true
  10191. });
  10192. Mesh.prototype.isReady = function () {
  10193. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  10194. return false;
  10195. }
  10196. return _super.prototype.isReady.call(this);
  10197. };
  10198. Mesh.prototype.isDisposed = function () {
  10199. return this._isDisposed;
  10200. };
  10201. // Methods
  10202. Mesh.prototype._preActivate = function () {
  10203. var sceneRenderId = this.getScene().getRenderId();
  10204. if (this._preActivateId == sceneRenderId) {
  10205. return;
  10206. }
  10207. this._preActivateId = sceneRenderId;
  10208. this._visibleInstances = null;
  10209. };
  10210. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  10211. if (!this._visibleInstances) {
  10212. this._visibleInstances = {};
  10213. this._visibleInstances.defaultRenderId = renderId;
  10214. this._visibleInstances.selfDefaultRenderId = this._renderId;
  10215. }
  10216. if (!this._visibleInstances[renderId]) {
  10217. this._visibleInstances[renderId] = new Array();
  10218. }
  10219. this._visibleInstances[renderId].push(instance);
  10220. };
  10221. Mesh.prototype.refreshBoundingInfo = function () {
  10222. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  10223. if (data) {
  10224. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  10225. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  10226. }
  10227. if (this.subMeshes) {
  10228. for (var index = 0; index < this.subMeshes.length; index++) {
  10229. this.subMeshes[index].refreshBoundingInfo();
  10230. }
  10231. }
  10232. this._updateBoundingInfo();
  10233. };
  10234. Mesh.prototype._createGlobalSubMesh = function () {
  10235. var totalVertices = this.getTotalVertices();
  10236. if (!totalVertices || !this.getIndices()) {
  10237. return null;
  10238. }
  10239. this.releaseSubMeshes();
  10240. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  10241. };
  10242. Mesh.prototype.subdivide = function (count) {
  10243. if (count < 1) {
  10244. return;
  10245. }
  10246. var totalIndices = this.getTotalIndices();
  10247. var subdivisionSize = (totalIndices / count) | 0;
  10248. var offset = 0;
  10249. while (subdivisionSize % 3 != 0) {
  10250. subdivisionSize++;
  10251. }
  10252. this.releaseSubMeshes();
  10253. for (var index = 0; index < count; index++) {
  10254. if (offset >= totalIndices) {
  10255. break;
  10256. }
  10257. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  10258. offset += subdivisionSize;
  10259. }
  10260. this.synchronizeInstances();
  10261. };
  10262. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  10263. if (kind instanceof Array) {
  10264. var temp = data;
  10265. data = kind;
  10266. kind = temp;
  10267. BABYLON.Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  10268. }
  10269. if (!this._geometry) {
  10270. var vertexData = new BABYLON.VertexData();
  10271. vertexData.set(data, kind);
  10272. var scene = this.getScene();
  10273. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  10274. }
  10275. else {
  10276. this._geometry.setVerticesData(kind, data, updatable, stride);
  10277. }
  10278. };
  10279. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  10280. if (!this._geometry) {
  10281. return;
  10282. }
  10283. if (!makeItUnique) {
  10284. this._geometry.updateVerticesData(kind, data, updateExtends);
  10285. }
  10286. else {
  10287. this.makeGeometryUnique();
  10288. this.updateVerticesData(kind, data, updateExtends, false);
  10289. }
  10290. };
  10291. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  10292. if (!this._geometry) {
  10293. return;
  10294. }
  10295. if (!makeItUnique) {
  10296. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  10297. }
  10298. else {
  10299. this.makeGeometryUnique();
  10300. this.updateVerticesDataDirectly(kind, data, offset, false);
  10301. }
  10302. };
  10303. Mesh.prototype.makeGeometryUnique = function () {
  10304. if (!this._geometry) {
  10305. return;
  10306. }
  10307. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  10308. geometry.applyToMesh(this);
  10309. };
  10310. Mesh.prototype.setIndices = function (indices, totalVertices) {
  10311. if (!this._geometry) {
  10312. var vertexData = new BABYLON.VertexData();
  10313. vertexData.indices = indices;
  10314. var scene = this.getScene();
  10315. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  10316. }
  10317. else {
  10318. this._geometry.setIndices(indices, totalVertices);
  10319. }
  10320. };
  10321. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  10322. var engine = this.getScene().getEngine();
  10323. // Wireframe
  10324. var indexToBind;
  10325. switch (fillMode) {
  10326. case BABYLON.Material.PointFillMode:
  10327. indexToBind = null;
  10328. break;
  10329. case BABYLON.Material.WireFrameFillMode:
  10330. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  10331. break;
  10332. default:
  10333. case BABYLON.Material.TriangleFillMode:
  10334. indexToBind = this._geometry.getIndexBuffer();
  10335. break;
  10336. }
  10337. // VBOs
  10338. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  10339. };
  10340. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  10341. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  10342. return;
  10343. }
  10344. var engine = this.getScene().getEngine();
  10345. switch (fillMode) {
  10346. case BABYLON.Material.PointFillMode:
  10347. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  10348. break;
  10349. case BABYLON.Material.WireFrameFillMode:
  10350. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  10351. break;
  10352. default:
  10353. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  10354. }
  10355. };
  10356. Mesh.prototype.registerBeforeRender = function (func) {
  10357. this._onBeforeRenderCallbacks.push(func);
  10358. };
  10359. Mesh.prototype.unregisterBeforeRender = function (func) {
  10360. var index = this._onBeforeRenderCallbacks.indexOf(func);
  10361. if (index > -1) {
  10362. this._onBeforeRenderCallbacks.splice(index, 1);
  10363. }
  10364. };
  10365. Mesh.prototype.registerAfterRender = function (func) {
  10366. this._onAfterRenderCallbacks.push(func);
  10367. };
  10368. Mesh.prototype.unregisterAfterRender = function (func) {
  10369. var index = this._onAfterRenderCallbacks.indexOf(func);
  10370. if (index > -1) {
  10371. this._onAfterRenderCallbacks.splice(index, 1);
  10372. }
  10373. };
  10374. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  10375. var scene = this.getScene();
  10376. this._batchCache.mustReturn = false;
  10377. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  10378. this._batchCache.visibleInstances[subMeshId] = null;
  10379. if (this._visibleInstances) {
  10380. var currentRenderId = scene.getRenderId();
  10381. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  10382. var selfRenderId = this._renderId;
  10383. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  10384. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  10385. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  10386. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  10387. }
  10388. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  10389. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  10390. this._batchCache.mustReturn = true;
  10391. return this._batchCache;
  10392. }
  10393. if (currentRenderId !== selfRenderId) {
  10394. this._batchCache.renderSelf[subMeshId] = false;
  10395. }
  10396. }
  10397. this._renderIdForInstances[subMeshId] = currentRenderId;
  10398. }
  10399. return this._batchCache;
  10400. };
  10401. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  10402. var visibleInstances = batch.visibleInstances[subMesh._id];
  10403. var matricesCount = visibleInstances.length + 1;
  10404. var bufferSize = matricesCount * 16 * 4;
  10405. while (this._instancesBufferSize < bufferSize) {
  10406. this._instancesBufferSize *= 2;
  10407. }
  10408. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  10409. if (this._worldMatricesInstancesBuffer) {
  10410. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  10411. }
  10412. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  10413. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  10414. }
  10415. var offset = 0;
  10416. var instancesCount = 0;
  10417. var world = this.getWorldMatrix();
  10418. if (batch.renderSelf[subMesh._id]) {
  10419. world.copyToArray(this._worldMatricesInstancesArray, offset);
  10420. offset += 16;
  10421. instancesCount++;
  10422. }
  10423. if (visibleInstances) {
  10424. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  10425. var instance = visibleInstances[instanceIndex];
  10426. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  10427. offset += 16;
  10428. instancesCount++;
  10429. }
  10430. }
  10431. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  10432. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  10433. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  10434. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  10435. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  10436. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  10437. this._draw(subMesh, fillMode, instancesCount);
  10438. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  10439. };
  10440. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  10441. var scene = this.getScene();
  10442. var engine = scene.getEngine();
  10443. if (hardwareInstancedRendering) {
  10444. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  10445. }
  10446. else {
  10447. if (batch.renderSelf[subMesh._id]) {
  10448. // Draw
  10449. if (onBeforeDraw) {
  10450. onBeforeDraw(false, this.getWorldMatrix());
  10451. }
  10452. this._draw(subMesh, fillMode);
  10453. }
  10454. if (batch.visibleInstances[subMesh._id]) {
  10455. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  10456. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  10457. // World
  10458. var world = instance.getWorldMatrix();
  10459. if (onBeforeDraw) {
  10460. onBeforeDraw(true, world);
  10461. }
  10462. // Draw
  10463. this._draw(subMesh, fillMode);
  10464. }
  10465. }
  10466. }
  10467. };
  10468. Mesh.prototype.render = function (subMesh) {
  10469. var scene = this.getScene();
  10470. // Managing instances
  10471. var batch = this._getInstancesRenderList(subMesh._id);
  10472. if (batch.mustReturn) {
  10473. return;
  10474. }
  10475. // Checking geometry state
  10476. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  10477. return;
  10478. }
  10479. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  10480. this._onBeforeRenderCallbacks[callbackIndex]();
  10481. }
  10482. var engine = scene.getEngine();
  10483. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  10484. // Material
  10485. var effectiveMaterial = subMesh.getMaterial();
  10486. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  10487. return;
  10488. }
  10489. // Outline - step 1
  10490. var savedDepthWrite = engine.getDepthWrite();
  10491. if (this.renderOutline) {
  10492. engine.setDepthWrite(false);
  10493. scene.getOutlineRenderer().render(subMesh, batch);
  10494. engine.setDepthWrite(savedDepthWrite);
  10495. }
  10496. effectiveMaterial._preBind();
  10497. var effect = effectiveMaterial.getEffect();
  10498. // Bind
  10499. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  10500. this._bind(subMesh, effect, fillMode);
  10501. var world = this.getWorldMatrix();
  10502. effectiveMaterial.bind(world, this);
  10503. // Draw
  10504. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  10505. if (isInstance) {
  10506. effectiveMaterial.bindOnlyWorldMatrix(world);
  10507. }
  10508. });
  10509. // Unbind
  10510. effectiveMaterial.unbind();
  10511. // Outline - step 2
  10512. if (this.renderOutline && savedDepthWrite) {
  10513. engine.setDepthWrite(true);
  10514. engine.setColorWrite(false);
  10515. scene.getOutlineRenderer().render(subMesh, batch);
  10516. engine.setColorWrite(true);
  10517. }
  10518. // Overlay
  10519. if (this.renderOverlay) {
  10520. var currentMode = engine.getAlphaMode();
  10521. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  10522. scene.getOutlineRenderer().render(subMesh, batch, true);
  10523. engine.setAlphaMode(currentMode);
  10524. }
  10525. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  10526. this._onAfterRenderCallbacks[callbackIndex]();
  10527. }
  10528. };
  10529. Mesh.prototype.getEmittedParticleSystems = function () {
  10530. var results = new Array();
  10531. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  10532. var particleSystem = this.getScene().particleSystems[index];
  10533. if (particleSystem.emitter === this) {
  10534. results.push(particleSystem);
  10535. }
  10536. }
  10537. return results;
  10538. };
  10539. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  10540. var results = new Array();
  10541. var descendants = this.getDescendants();
  10542. descendants.push(this);
  10543. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  10544. var particleSystem = this.getScene().particleSystems[index];
  10545. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  10546. results.push(particleSystem);
  10547. }
  10548. }
  10549. return results;
  10550. };
  10551. Mesh.prototype.getChildren = function () {
  10552. var results = [];
  10553. for (var index = 0; index < this.getScene().meshes.length; index++) {
  10554. var mesh = this.getScene().meshes[index];
  10555. if (mesh.parent === this) {
  10556. results.push(mesh);
  10557. }
  10558. }
  10559. return results;
  10560. };
  10561. Mesh.prototype._checkDelayState = function () {
  10562. var _this = this;
  10563. var that = this;
  10564. var scene = this.getScene();
  10565. if (this._geometry) {
  10566. this._geometry.load(scene);
  10567. }
  10568. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  10569. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  10570. scene._addPendingData(that);
  10571. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1) ? true : false;
  10572. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  10573. if (data instanceof ArrayBuffer) {
  10574. _this._delayLoadingFunction(data, _this);
  10575. }
  10576. else {
  10577. _this._delayLoadingFunction(JSON.parse(data), _this);
  10578. }
  10579. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  10580. scene._removePendingData(_this);
  10581. }, function () {
  10582. }, scene.database, getBinaryData);
  10583. }
  10584. };
  10585. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  10586. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  10587. return false;
  10588. }
  10589. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  10590. return false;
  10591. }
  10592. this._checkDelayState();
  10593. return true;
  10594. };
  10595. Mesh.prototype.setMaterialByID = function (id) {
  10596. var materials = this.getScene().materials;
  10597. for (var index = 0; index < materials.length; index++) {
  10598. if (materials[index].id === id) {
  10599. this.material = materials[index];
  10600. return;
  10601. }
  10602. }
  10603. // Multi
  10604. var multiMaterials = this.getScene().multiMaterials;
  10605. for (index = 0; index < multiMaterials.length; index++) {
  10606. if (multiMaterials[index].id === id) {
  10607. this.material = multiMaterials[index];
  10608. return;
  10609. }
  10610. }
  10611. };
  10612. Mesh.prototype.getAnimatables = function () {
  10613. var results = [];
  10614. if (this.material) {
  10615. results.push(this.material);
  10616. }
  10617. if (this.skeleton) {
  10618. results.push(this.skeleton);
  10619. }
  10620. return results;
  10621. };
  10622. // Geometry
  10623. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  10624. // Position
  10625. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  10626. return;
  10627. }
  10628. this._resetPointsArrayCache();
  10629. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  10630. var temp = [];
  10631. for (var index = 0; index < data.length; index += 3) {
  10632. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  10633. }
  10634. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  10635. // Normals
  10636. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  10637. return;
  10638. }
  10639. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  10640. for (index = 0; index < data.length; index += 3) {
  10641. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  10642. }
  10643. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  10644. };
  10645. // Cache
  10646. Mesh.prototype._resetPointsArrayCache = function () {
  10647. this._positions = null;
  10648. };
  10649. Mesh.prototype._generatePointsArray = function () {
  10650. if (this._positions)
  10651. return true;
  10652. this._positions = [];
  10653. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  10654. if (!data) {
  10655. return false;
  10656. }
  10657. for (var index = 0; index < data.length; index += 3) {
  10658. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  10659. }
  10660. return true;
  10661. };
  10662. // Clone
  10663. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  10664. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  10665. };
  10666. // Dispose
  10667. Mesh.prototype.dispose = function (doNotRecurse) {
  10668. if (this._geometry) {
  10669. this._geometry.releaseForMesh(this, true);
  10670. }
  10671. // Instances
  10672. if (this._worldMatricesInstancesBuffer) {
  10673. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  10674. this._worldMatricesInstancesBuffer = null;
  10675. }
  10676. while (this.instances.length) {
  10677. this.instances[0].dispose();
  10678. }
  10679. _super.prototype.dispose.call(this, doNotRecurse);
  10680. };
  10681. // Geometric tools
  10682. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  10683. var _this = this;
  10684. var scene = this.getScene();
  10685. var onload = function (img) {
  10686. // Getting height map data
  10687. var canvas = document.createElement("canvas");
  10688. var context = canvas.getContext("2d");
  10689. var heightMapWidth = img.width;
  10690. var heightMapHeight = img.height;
  10691. canvas.width = heightMapWidth;
  10692. canvas.height = heightMapHeight;
  10693. context.drawImage(img, 0, 0);
  10694. // Create VertexData from map data
  10695. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  10696. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  10697. //execute success callback, if set
  10698. if (onSuccess) {
  10699. onSuccess(_this);
  10700. }
  10701. };
  10702. BABYLON.Tools.LoadImage(url, onload, function () {
  10703. }, scene.database);
  10704. };
  10705. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  10706. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  10707. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  10708. return;
  10709. }
  10710. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  10711. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  10712. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  10713. var position = BABYLON.Vector3.Zero();
  10714. var normal = BABYLON.Vector3.Zero();
  10715. var uv = BABYLON.Vector2.Zero();
  10716. for (var index = 0; index < positions.length; index += 3) {
  10717. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  10718. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  10719. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  10720. // Compute height
  10721. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  10722. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  10723. var pos = (u + v * heightMapWidth) * 4;
  10724. var r = buffer[pos] / 255.0;
  10725. var g = buffer[pos + 1] / 255.0;
  10726. var b = buffer[pos + 2] / 255.0;
  10727. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  10728. normal.normalize();
  10729. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  10730. position = position.add(normal);
  10731. position.toArray(positions, index);
  10732. }
  10733. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  10734. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  10735. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  10736. };
  10737. Mesh.prototype.convertToFlatShadedMesh = function () {
  10738. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  10739. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  10740. var kinds = this.getVerticesDataKinds();
  10741. var vbs = [];
  10742. var data = [];
  10743. var newdata = [];
  10744. var updatableNormals = false;
  10745. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  10746. var kind = kinds[kindIndex];
  10747. var vertexBuffer = this.getVertexBuffer(kind);
  10748. if (kind === BABYLON.VertexBuffer.NormalKind) {
  10749. updatableNormals = vertexBuffer.isUpdatable();
  10750. kinds.splice(kindIndex, 1);
  10751. kindIndex--;
  10752. continue;
  10753. }
  10754. vbs[kind] = vertexBuffer;
  10755. data[kind] = vbs[kind].getData();
  10756. newdata[kind] = [];
  10757. }
  10758. // Save previous submeshes
  10759. var previousSubmeshes = this.subMeshes.slice(0);
  10760. var indices = this.getIndices();
  10761. var totalIndices = this.getTotalIndices();
  10762. for (var index = 0; index < totalIndices; index++) {
  10763. var vertexIndex = indices[index];
  10764. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  10765. kind = kinds[kindIndex];
  10766. var stride = vbs[kind].getStrideSize();
  10767. for (var offset = 0; offset < stride; offset++) {
  10768. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  10769. }
  10770. }
  10771. }
  10772. // Updating faces & normal
  10773. var normals = [];
  10774. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  10775. for (index = 0; index < totalIndices; index += 3) {
  10776. indices[index] = index;
  10777. indices[index + 1] = index + 1;
  10778. indices[index + 2] = index + 2;
  10779. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  10780. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  10781. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  10782. var p1p2 = p1.subtract(p2);
  10783. var p3p2 = p3.subtract(p2);
  10784. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  10785. for (var localIndex = 0; localIndex < 3; localIndex++) {
  10786. normals.push(normal.x);
  10787. normals.push(normal.y);
  10788. normals.push(normal.z);
  10789. }
  10790. }
  10791. this.setIndices(indices);
  10792. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  10793. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  10794. kind = kinds[kindIndex];
  10795. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  10796. }
  10797. // Updating submeshes
  10798. this.releaseSubMeshes();
  10799. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  10800. var previousOne = previousSubmeshes[submeshIndex];
  10801. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  10802. }
  10803. this.synchronizeInstances();
  10804. };
  10805. // Instances
  10806. Mesh.prototype.createInstance = function (name) {
  10807. return new BABYLON.InstancedMesh(name, this);
  10808. };
  10809. Mesh.prototype.synchronizeInstances = function () {
  10810. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  10811. var instance = this.instances[instanceIndex];
  10812. instance._syncSubMeshes();
  10813. }
  10814. };
  10815. /**
  10816. * Simplify the mesh according to the given array of settings.
  10817. * Function will return immediately and will simplify async.
  10818. * @param settings a collection of simplification settings.
  10819. * @param parallelProcessing should all levels calculate parallel or one after the other.
  10820. * @param type the type of simplification to run.
  10821. * successCallback optional success callback to be called after the simplification finished processing all settings.
  10822. */
  10823. Mesh.prototype.simplify = function (settings, parallelProcessing, type, successCallback) {
  10824. var _this = this;
  10825. if (parallelProcessing === void 0) { parallelProcessing = true; }
  10826. if (type === void 0) { type = 0 /* QUADRATIC */; }
  10827. var getSimplifier = function () {
  10828. switch (type) {
  10829. case 0 /* QUADRATIC */:
  10830. default:
  10831. return new BABYLON.QuadraticErrorSimplification(_this);
  10832. }
  10833. };
  10834. if (parallelProcessing) {
  10835. //parallel simplifier
  10836. settings.forEach(function (setting) {
  10837. var simplifier = getSimplifier();
  10838. simplifier.simplify(setting, function (newMesh) {
  10839. _this.addLODLevel(setting.distance, newMesh);
  10840. //check if it is the last
  10841. if (setting.quality === settings[settings.length - 1].quality && successCallback) {
  10842. //all done, run the success callback.
  10843. successCallback();
  10844. }
  10845. });
  10846. });
  10847. }
  10848. else {
  10849. //single simplifier.
  10850. var simplifier = getSimplifier();
  10851. var runDecimation = function (setting, callback) {
  10852. simplifier.simplify(setting, function (newMesh) {
  10853. _this.addLODLevel(setting.distance, newMesh);
  10854. //run the next quality level
  10855. callback();
  10856. });
  10857. };
  10858. BABYLON.AsyncLoop.Run(settings.length, function (loop) {
  10859. runDecimation(settings[loop.index], function () {
  10860. loop.executeNext();
  10861. });
  10862. }, function () {
  10863. //execution ended, run the success callback.
  10864. if (successCallback) {
  10865. successCallback();
  10866. }
  10867. });
  10868. }
  10869. };
  10870. // Statics
  10871. Mesh.CreateBox = function (name, size, scene, updatable) {
  10872. var box = new Mesh(name, scene);
  10873. var vertexData = BABYLON.VertexData.CreateBox(size);
  10874. vertexData.applyToMesh(box, updatable);
  10875. return box;
  10876. };
  10877. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable) {
  10878. var sphere = new Mesh(name, scene);
  10879. var vertexData = BABYLON.VertexData.CreateSphere(segments, diameter);
  10880. vertexData.applyToMesh(sphere, updatable);
  10881. return sphere;
  10882. };
  10883. // Cylinder and cone (Code inspired by SharpDX.org)
  10884. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable) {
  10885. // subdivisions is a new parameter, we need to support old signature
  10886. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  10887. if (scene !== undefined) {
  10888. updatable = scene;
  10889. }
  10890. scene = subdivisions;
  10891. subdivisions = 1;
  10892. }
  10893. var cylinder = new Mesh(name, scene);
  10894. var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions);
  10895. vertexData.applyToMesh(cylinder, updatable);
  10896. return cylinder;
  10897. };
  10898. // Torus (Code from SharpDX.org)
  10899. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable) {
  10900. var torus = new Mesh(name, scene);
  10901. var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation);
  10902. vertexData.applyToMesh(torus, updatable);
  10903. return torus;
  10904. };
  10905. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable) {
  10906. var torusKnot = new Mesh(name, scene);
  10907. var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q);
  10908. vertexData.applyToMesh(torusKnot, updatable);
  10909. return torusKnot;
  10910. };
  10911. // Lines
  10912. Mesh.CreateLines = function (name, points, scene, updatable) {
  10913. var lines = new BABYLON.LinesMesh(name, scene, updatable);
  10914. var vertexData = BABYLON.VertexData.CreateLines(points);
  10915. vertexData.applyToMesh(lines, updatable);
  10916. return lines;
  10917. };
  10918. // Plane & ground
  10919. Mesh.CreatePlane = function (name, size, scene, updatable) {
  10920. var plane = new Mesh(name, scene);
  10921. var vertexData = BABYLON.VertexData.CreatePlane(size);
  10922. vertexData.applyToMesh(plane, updatable);
  10923. return plane;
  10924. };
  10925. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  10926. var ground = new BABYLON.GroundMesh(name, scene);
  10927. ground._setReady(false);
  10928. ground._subdivisions = subdivisions;
  10929. var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
  10930. vertexData.applyToMesh(ground, updatable);
  10931. ground._setReady(true);
  10932. return ground;
  10933. };
  10934. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  10935. var tiledGround = new Mesh(name, scene);
  10936. var vertexData = BABYLON.VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  10937. vertexData.applyToMesh(tiledGround, updatable);
  10938. return tiledGround;
  10939. };
  10940. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  10941. var ground = new BABYLON.GroundMesh(name, scene);
  10942. ground._subdivisions = subdivisions;
  10943. ground._setReady(false);
  10944. var onload = function (img) {
  10945. // Getting height map data
  10946. var canvas = document.createElement("canvas");
  10947. var context = canvas.getContext("2d");
  10948. var heightMapWidth = img.width;
  10949. var heightMapHeight = img.height;
  10950. canvas.width = heightMapWidth;
  10951. canvas.height = heightMapHeight;
  10952. context.drawImage(img, 0, 0);
  10953. // Create VertexData from map data
  10954. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  10955. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  10956. vertexData.applyToMesh(ground, updatable);
  10957. ground._setReady(true);
  10958. //execute ready callback, if set
  10959. if (onReady) {
  10960. onReady(ground);
  10961. }
  10962. };
  10963. BABYLON.Tools.LoadImage(url, onload, function () {
  10964. }, scene.database);
  10965. return ground;
  10966. };
  10967. // Tools
  10968. Mesh.MinMax = function (meshes) {
  10969. var minVector = null;
  10970. var maxVector = null;
  10971. for (var i in meshes) {
  10972. var mesh = meshes[i];
  10973. var boundingBox = mesh.getBoundingInfo().boundingBox;
  10974. if (!minVector) {
  10975. minVector = boundingBox.minimumWorld;
  10976. maxVector = boundingBox.maximumWorld;
  10977. continue;
  10978. }
  10979. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  10980. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  10981. }
  10982. return {
  10983. min: minVector,
  10984. max: maxVector
  10985. };
  10986. };
  10987. Mesh.Center = function (meshesOrMinMaxVector) {
  10988. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  10989. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  10990. };
  10991. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices) {
  10992. if (disposeSource === void 0) { disposeSource = true; }
  10993. var source = meshes[0];
  10994. var material = source.material;
  10995. var scene = source.getScene();
  10996. if (!allow32BitsIndices) {
  10997. var totalVertices = 0;
  10998. for (var index = 0; index < meshes.length; index++) {
  10999. totalVertices += meshes[index].getTotalVertices();
  11000. if (totalVertices > 65536) {
  11001. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  11002. return null;
  11003. }
  11004. }
  11005. }
  11006. // Merge
  11007. var vertexData = BABYLON.VertexData.ExtractFromMesh(source);
  11008. vertexData.transform(source.getWorldMatrix());
  11009. for (index = 1; index < meshes.length; index++) {
  11010. var otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index]);
  11011. otherVertexData.transform(meshes[index].getWorldMatrix());
  11012. vertexData.merge(otherVertexData);
  11013. }
  11014. var newMesh = new Mesh(source.name + "_merged", scene);
  11015. vertexData.applyToMesh(newMesh);
  11016. // Setting properties
  11017. newMesh.material = material;
  11018. newMesh.checkCollisions = source.checkCollisions;
  11019. // Cleaning
  11020. if (disposeSource) {
  11021. for (index = 0; index < meshes.length; index++) {
  11022. meshes[index].dispose();
  11023. }
  11024. }
  11025. return newMesh;
  11026. };
  11027. return Mesh;
  11028. })(BABYLON.AbstractMesh);
  11029. BABYLON.Mesh = Mesh;
  11030. })(BABYLON || (BABYLON = {}));
  11031. //# sourceMappingURL=babylon.mesh.js.map
  11032. var BABYLON;
  11033. (function (BABYLON) {
  11034. var GroundMesh = (function (_super) {
  11035. __extends(GroundMesh, _super);
  11036. function GroundMesh(name, scene) {
  11037. _super.call(this, name, scene);
  11038. this.generateOctree = false;
  11039. this._worldInverse = new BABYLON.Matrix();
  11040. }
  11041. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  11042. get: function () {
  11043. return this._subdivisions;
  11044. },
  11045. enumerable: true,
  11046. configurable: true
  11047. });
  11048. GroundMesh.prototype.optimize = function (chunksCount) {
  11049. this.subdivide(this._subdivisions);
  11050. this.createOrUpdateSubmeshesOctree(32);
  11051. };
  11052. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  11053. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  11054. this.getWorldMatrix().invertToRef(this._worldInverse);
  11055. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  11056. var pickInfo = this.intersects(ray);
  11057. if (pickInfo.hit) {
  11058. return pickInfo.pickedPoint.y;
  11059. }
  11060. return 0;
  11061. };
  11062. return GroundMesh;
  11063. })(BABYLON.Mesh);
  11064. BABYLON.GroundMesh = GroundMesh;
  11065. })(BABYLON || (BABYLON = {}));
  11066. //# sourceMappingURL=babylon.groundMesh.js.map
  11067. var BABYLON;
  11068. (function (BABYLON) {
  11069. /**
  11070. * Creates an instance based on a source mesh.
  11071. */
  11072. var InstancedMesh = (function (_super) {
  11073. __extends(InstancedMesh, _super);
  11074. function InstancedMesh(name, source) {
  11075. _super.call(this, name, source.getScene());
  11076. source.instances.push(this);
  11077. this._sourceMesh = source;
  11078. this.position.copyFrom(source.position);
  11079. this.rotation.copyFrom(source.rotation);
  11080. this.scaling.copyFrom(source.scaling);
  11081. if (source.rotationQuaternion) {
  11082. this.rotationQuaternion = source.rotationQuaternion.clone();
  11083. }
  11084. this.infiniteDistance = source.infiniteDistance;
  11085. this.setPivotMatrix(source.getPivotMatrix());
  11086. this.refreshBoundingInfo();
  11087. this._syncSubMeshes();
  11088. }
  11089. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  11090. // Methods
  11091. get: function () {
  11092. return this._sourceMesh.receiveShadows;
  11093. },
  11094. enumerable: true,
  11095. configurable: true
  11096. });
  11097. Object.defineProperty(InstancedMesh.prototype, "material", {
  11098. get: function () {
  11099. return this._sourceMesh.material;
  11100. },
  11101. enumerable: true,
  11102. configurable: true
  11103. });
  11104. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  11105. get: function () {
  11106. return this._sourceMesh.visibility;
  11107. },
  11108. enumerable: true,
  11109. configurable: true
  11110. });
  11111. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  11112. get: function () {
  11113. return this._sourceMesh.skeleton;
  11114. },
  11115. enumerable: true,
  11116. configurable: true
  11117. });
  11118. InstancedMesh.prototype.getTotalVertices = function () {
  11119. return this._sourceMesh.getTotalVertices();
  11120. };
  11121. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  11122. get: function () {
  11123. return this._sourceMesh;
  11124. },
  11125. enumerable: true,
  11126. configurable: true
  11127. });
  11128. InstancedMesh.prototype.getVerticesData = function (kind) {
  11129. return this._sourceMesh.getVerticesData(kind);
  11130. };
  11131. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  11132. return this._sourceMesh.isVerticesDataPresent(kind);
  11133. };
  11134. InstancedMesh.prototype.getIndices = function () {
  11135. return this._sourceMesh.getIndices();
  11136. };
  11137. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  11138. get: function () {
  11139. return this._sourceMesh._positions;
  11140. },
  11141. enumerable: true,
  11142. configurable: true
  11143. });
  11144. InstancedMesh.prototype.refreshBoundingInfo = function () {
  11145. var data = this._sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11146. if (data) {
  11147. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._sourceMesh.getTotalVertices());
  11148. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  11149. }
  11150. this._updateBoundingInfo();
  11151. };
  11152. InstancedMesh.prototype._preActivate = function () {
  11153. if (this._currentLOD) {
  11154. this._currentLOD._preActivate();
  11155. }
  11156. };
  11157. InstancedMesh.prototype._activate = function (renderId) {
  11158. if (this._currentLOD) {
  11159. this._currentLOD._registerInstanceForRenderId(this, renderId);
  11160. }
  11161. };
  11162. InstancedMesh.prototype.getLOD = function (camera) {
  11163. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  11164. if (this._currentLOD === this.sourceMesh) {
  11165. return this;
  11166. }
  11167. return this._currentLOD;
  11168. };
  11169. InstancedMesh.prototype._syncSubMeshes = function () {
  11170. this.releaseSubMeshes();
  11171. if (this._sourceMesh.subMeshes) {
  11172. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  11173. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  11174. }
  11175. }
  11176. };
  11177. InstancedMesh.prototype._generatePointsArray = function () {
  11178. return this._sourceMesh._generatePointsArray();
  11179. };
  11180. // Clone
  11181. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  11182. var result = this._sourceMesh.createInstance(name);
  11183. // Deep copy
  11184. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  11185. // Bounding info
  11186. this.refreshBoundingInfo();
  11187. // Parent
  11188. if (newParent) {
  11189. result.parent = newParent;
  11190. }
  11191. if (!doNotCloneChildren) {
  11192. for (var index = 0; index < this.getScene().meshes.length; index++) {
  11193. var mesh = this.getScene().meshes[index];
  11194. if (mesh.parent === this) {
  11195. mesh.clone(mesh.name, result);
  11196. }
  11197. }
  11198. }
  11199. result.computeWorldMatrix(true);
  11200. return result;
  11201. };
  11202. // Dispoe
  11203. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  11204. // Remove from mesh
  11205. var index = this._sourceMesh.instances.indexOf(this);
  11206. this._sourceMesh.instances.splice(index, 1);
  11207. _super.prototype.dispose.call(this, doNotRecurse);
  11208. };
  11209. return InstancedMesh;
  11210. })(BABYLON.AbstractMesh);
  11211. BABYLON.InstancedMesh = InstancedMesh;
  11212. })(BABYLON || (BABYLON = {}));
  11213. //# sourceMappingURL=babylon.instancedMesh.js.mapvar BABYLON;
  11214. (function (BABYLON) {
  11215. var SubMesh = (function () {
  11216. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  11217. if (createBoundingBox === void 0) { createBoundingBox = true; }
  11218. this.materialIndex = materialIndex;
  11219. this.verticesStart = verticesStart;
  11220. this.verticesCount = verticesCount;
  11221. this.indexStart = indexStart;
  11222. this.indexCount = indexCount;
  11223. this._renderId = 0;
  11224. this._mesh = mesh;
  11225. this._renderingMesh = renderingMesh || mesh;
  11226. mesh.subMeshes.push(this);
  11227. this._id = mesh.subMeshes.length - 1;
  11228. if (createBoundingBox) {
  11229. this.refreshBoundingInfo();
  11230. }
  11231. }
  11232. SubMesh.prototype.getBoundingInfo = function () {
  11233. return this._boundingInfo;
  11234. };
  11235. SubMesh.prototype.getMesh = function () {
  11236. return this._mesh;
  11237. };
  11238. SubMesh.prototype.getRenderingMesh = function () {
  11239. return this._renderingMesh;
  11240. };
  11241. SubMesh.prototype.getMaterial = function () {
  11242. var rootMaterial = this._renderingMesh.material;
  11243. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  11244. var multiMaterial = rootMaterial;
  11245. return multiMaterial.getSubMaterial(this.materialIndex);
  11246. }
  11247. if (!rootMaterial) {
  11248. return this._mesh.getScene().defaultMaterial;
  11249. }
  11250. return rootMaterial;
  11251. };
  11252. // Methods
  11253. SubMesh.prototype.refreshBoundingInfo = function () {
  11254. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11255. if (!data) {
  11256. this._boundingInfo = this._mesh._boundingInfo;
  11257. return;
  11258. }
  11259. var indices = this._renderingMesh.getIndices();
  11260. var extend;
  11261. if (this.indexStart === 0 && this.indexCount === indices.length) {
  11262. extend = BABYLON.Tools.ExtractMinAndMax(data, this.verticesStart, this.verticesCount);
  11263. }
  11264. else {
  11265. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  11266. }
  11267. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  11268. };
  11269. SubMesh.prototype._checkCollision = function (collider) {
  11270. return this._boundingInfo._checkCollision(collider);
  11271. };
  11272. SubMesh.prototype.updateBoundingInfo = function (world) {
  11273. if (!this._boundingInfo) {
  11274. this.refreshBoundingInfo();
  11275. }
  11276. this._boundingInfo._update(world);
  11277. };
  11278. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  11279. return this._boundingInfo.isInFrustum(frustumPlanes);
  11280. };
  11281. SubMesh.prototype.render = function () {
  11282. this._renderingMesh.render(this);
  11283. };
  11284. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  11285. if (!this._linesIndexBuffer) {
  11286. var linesIndices = [];
  11287. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  11288. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  11289. }
  11290. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  11291. this.linesIndexCount = linesIndices.length;
  11292. }
  11293. return this._linesIndexBuffer;
  11294. };
  11295. SubMesh.prototype.canIntersects = function (ray) {
  11296. return ray.intersectsBox(this._boundingInfo.boundingBox);
  11297. };
  11298. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  11299. var intersectInfo = null;
  11300. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  11301. var p0 = positions[indices[index]];
  11302. var p1 = positions[indices[index + 1]];
  11303. var p2 = positions[indices[index + 2]];
  11304. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  11305. if (currentIntersectInfo) {
  11306. if (currentIntersectInfo.distance < 0) {
  11307. continue;
  11308. }
  11309. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  11310. intersectInfo = currentIntersectInfo;
  11311. intersectInfo.faceId = index / 3;
  11312. if (fastCheck) {
  11313. break;
  11314. }
  11315. }
  11316. }
  11317. }
  11318. return intersectInfo;
  11319. };
  11320. // Clone
  11321. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  11322. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  11323. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  11324. return result;
  11325. };
  11326. // Dispose
  11327. SubMesh.prototype.dispose = function () {
  11328. if (this._linesIndexBuffer) {
  11329. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  11330. this._linesIndexBuffer = null;
  11331. }
  11332. // Remove from mesh
  11333. var index = this._mesh.subMeshes.indexOf(this);
  11334. this._mesh.subMeshes.splice(index, 1);
  11335. };
  11336. // Statics
  11337. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  11338. var minVertexIndex = Number.MAX_VALUE;
  11339. var maxVertexIndex = -Number.MAX_VALUE;
  11340. renderingMesh = renderingMesh || mesh;
  11341. var indices = renderingMesh.getIndices();
  11342. for (var index = startIndex; index < startIndex + indexCount; index++) {
  11343. var vertexIndex = indices[index];
  11344. if (vertexIndex < minVertexIndex)
  11345. minVertexIndex = vertexIndex;
  11346. if (vertexIndex > maxVertexIndex)
  11347. maxVertexIndex = vertexIndex;
  11348. }
  11349. return new BABYLON.SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  11350. };
  11351. return SubMesh;
  11352. })();
  11353. BABYLON.SubMesh = SubMesh;
  11354. })(BABYLON || (BABYLON = {}));
  11355. //# sourceMappingURL=babylon.subMesh.js.mapvar BABYLON;
  11356. (function (BABYLON) {
  11357. var BaseTexture = (function () {
  11358. function BaseTexture(scene) {
  11359. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  11360. this.hasAlpha = false;
  11361. this.getAlphaFromRGB = false;
  11362. this.level = 1;
  11363. this.isCube = false;
  11364. this.isRenderTarget = false;
  11365. this.animations = new Array();
  11366. this.coordinatesIndex = 0;
  11367. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  11368. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  11369. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  11370. this.anisotropicFilteringLevel = 4;
  11371. this._scene = scene;
  11372. this._scene.textures.push(this);
  11373. }
  11374. BaseTexture.prototype.getScene = function () {
  11375. return this._scene;
  11376. };
  11377. BaseTexture.prototype.getTextureMatrix = function () {
  11378. return null;
  11379. };
  11380. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  11381. return null;
  11382. };
  11383. BaseTexture.prototype.getInternalTexture = function () {
  11384. return this._texture;
  11385. };
  11386. BaseTexture.prototype.isReady = function () {
  11387. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  11388. return true;
  11389. }
  11390. if (this._texture) {
  11391. return this._texture.isReady;
  11392. }
  11393. return false;
  11394. };
  11395. BaseTexture.prototype.getSize = function () {
  11396. if (this._texture._width) {
  11397. return { width: this._texture._width, height: this._texture._height };
  11398. }
  11399. if (this._texture._size) {
  11400. return { width: this._texture._size, height: this._texture._size };
  11401. }
  11402. return { width: 0, height: 0 };
  11403. };
  11404. BaseTexture.prototype.getBaseSize = function () {
  11405. if (!this.isReady())
  11406. return { width: 0, height: 0 };
  11407. if (this._texture._size) {
  11408. return { width: this._texture._size, height: this._texture._size };
  11409. }
  11410. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  11411. };
  11412. BaseTexture.prototype.scale = function (ratio) {
  11413. };
  11414. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  11415. get: function () {
  11416. return false;
  11417. },
  11418. enumerable: true,
  11419. configurable: true
  11420. });
  11421. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  11422. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  11423. for (var index = 0; index < texturesCache.length; index++) {
  11424. var texturesCacheEntry = texturesCache[index];
  11425. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  11426. texturesCache.splice(index, 1);
  11427. return;
  11428. }
  11429. }
  11430. };
  11431. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  11432. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  11433. for (var index = 0; index < texturesCache.length; index++) {
  11434. var texturesCacheEntry = texturesCache[index];
  11435. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  11436. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  11437. texturesCacheEntry.references++;
  11438. return texturesCacheEntry;
  11439. }
  11440. }
  11441. }
  11442. return null;
  11443. };
  11444. BaseTexture.prototype.delayLoad = function () {
  11445. };
  11446. BaseTexture.prototype.releaseInternalTexture = function () {
  11447. if (!this._texture) {
  11448. return;
  11449. }
  11450. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  11451. this._texture.references--;
  11452. // Final reference ?
  11453. if (this._texture.references === 0) {
  11454. var index = texturesCache.indexOf(this._texture);
  11455. texturesCache.splice(index, 1);
  11456. this._scene.getEngine()._releaseTexture(this._texture);
  11457. delete this._texture;
  11458. }
  11459. };
  11460. BaseTexture.prototype.clone = function () {
  11461. return null;
  11462. };
  11463. BaseTexture.prototype.dispose = function () {
  11464. // Remove from scene
  11465. var index = this._scene.textures.indexOf(this);
  11466. if (index >= 0) {
  11467. this._scene.textures.splice(index, 1);
  11468. }
  11469. if (this._texture === undefined) {
  11470. return;
  11471. }
  11472. this.releaseInternalTexture();
  11473. // Callback
  11474. if (this.onDispose) {
  11475. this.onDispose();
  11476. }
  11477. };
  11478. return BaseTexture;
  11479. })();
  11480. BABYLON.BaseTexture = BaseTexture;
  11481. })(BABYLON || (BABYLON = {}));
  11482. //# sourceMappingURL=babylon.baseTexture.js.mapvar BABYLON;
  11483. (function (BABYLON) {
  11484. var RenderingGroup = (function () {
  11485. function RenderingGroup(index, scene) {
  11486. this.index = index;
  11487. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  11488. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  11489. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  11490. this._scene = scene;
  11491. }
  11492. RenderingGroup.prototype.render = function (customRenderFunction) {
  11493. if (customRenderFunction) {
  11494. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  11495. return true;
  11496. }
  11497. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  11498. return false;
  11499. }
  11500. var engine = this._scene.getEngine();
  11501. // Opaque
  11502. var subIndex;
  11503. var submesh;
  11504. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  11505. submesh = this._opaqueSubMeshes.data[subIndex];
  11506. submesh.render();
  11507. }
  11508. // Alpha test
  11509. engine.setAlphaTesting(true);
  11510. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  11511. submesh = this._alphaTestSubMeshes.data[subIndex];
  11512. submesh.render();
  11513. }
  11514. engine.setAlphaTesting(false);
  11515. // Transparent
  11516. if (this._transparentSubMeshes.length) {
  11517. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  11518. submesh = this._transparentSubMeshes.data[subIndex];
  11519. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  11520. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.position).length();
  11521. }
  11522. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  11523. sortedArray.sort(function (a, b) {
  11524. // Alpha index first
  11525. if (a._alphaIndex > b._alphaIndex) {
  11526. return 1;
  11527. }
  11528. if (a._alphaIndex < b._alphaIndex) {
  11529. return -1;
  11530. }
  11531. // Then distance to camera
  11532. if (a._distanceToCamera < b._distanceToCamera) {
  11533. return 1;
  11534. }
  11535. if (a._distanceToCamera > b._distanceToCamera) {
  11536. return -1;
  11537. }
  11538. return 0;
  11539. });
  11540. // Rendering
  11541. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  11542. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  11543. submesh = sortedArray[subIndex];
  11544. submesh.render();
  11545. }
  11546. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  11547. }
  11548. return true;
  11549. };
  11550. RenderingGroup.prototype.prepare = function () {
  11551. this._opaqueSubMeshes.reset();
  11552. this._transparentSubMeshes.reset();
  11553. this._alphaTestSubMeshes.reset();
  11554. };
  11555. RenderingGroup.prototype.dispatch = function (subMesh) {
  11556. var material = subMesh.getMaterial();
  11557. var mesh = subMesh.getMesh();
  11558. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  11559. this._transparentSubMeshes.push(subMesh);
  11560. }
  11561. else if (material.needAlphaTesting()) {
  11562. this._alphaTestSubMeshes.push(subMesh);
  11563. }
  11564. else {
  11565. this._opaqueSubMeshes.push(subMesh); // Opaque
  11566. }
  11567. };
  11568. return RenderingGroup;
  11569. })();
  11570. BABYLON.RenderingGroup = RenderingGroup;
  11571. })(BABYLON || (BABYLON = {}));
  11572. //# sourceMappingURL=babylon.renderingGroup.js.mapvar BABYLON;
  11573. (function (BABYLON) {
  11574. var RenderingManager = (function () {
  11575. function RenderingManager(scene) {
  11576. this._renderingGroups = new Array();
  11577. this._scene = scene;
  11578. }
  11579. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  11580. if (this._scene._activeParticleSystems.length === 0) {
  11581. return;
  11582. }
  11583. // Particles
  11584. var beforeParticlesDate = BABYLON.Tools.Now;
  11585. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  11586. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  11587. if (particleSystem.renderingGroupId !== index) {
  11588. continue;
  11589. }
  11590. this._clearDepthBuffer();
  11591. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  11592. this._scene._activeParticles += particleSystem.render();
  11593. }
  11594. }
  11595. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  11596. };
  11597. RenderingManager.prototype._renderSprites = function (index) {
  11598. if (this._scene.spriteManagers.length === 0) {
  11599. return;
  11600. }
  11601. // Sprites
  11602. var beforeSpritessDate = BABYLON.Tools.Now;
  11603. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  11604. var spriteManager = this._scene.spriteManagers[id];
  11605. if (spriteManager.renderingGroupId === index) {
  11606. this._clearDepthBuffer();
  11607. spriteManager.render();
  11608. }
  11609. }
  11610. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  11611. };
  11612. RenderingManager.prototype._clearDepthBuffer = function () {
  11613. if (this._depthBufferAlreadyCleaned) {
  11614. return;
  11615. }
  11616. this._scene.getEngine().clear(0, false, true);
  11617. this._depthBufferAlreadyCleaned = true;
  11618. };
  11619. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  11620. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  11621. this._depthBufferAlreadyCleaned = false;
  11622. var renderingGroup = this._renderingGroups[index];
  11623. if (renderingGroup) {
  11624. this._clearDepthBuffer();
  11625. if (!renderingGroup.render(customRenderFunction)) {
  11626. this._renderingGroups.splice(index, 1);
  11627. }
  11628. }
  11629. if (renderSprites) {
  11630. this._renderSprites(index);
  11631. }
  11632. if (renderParticles) {
  11633. this._renderParticles(index, activeMeshes);
  11634. }
  11635. }
  11636. };
  11637. RenderingManager.prototype.reset = function () {
  11638. for (var index in this._renderingGroups) {
  11639. var renderingGroup = this._renderingGroups[index];
  11640. renderingGroup.prepare();
  11641. }
  11642. };
  11643. RenderingManager.prototype.dispatch = function (subMesh) {
  11644. var mesh = subMesh.getMesh();
  11645. var renderingGroupId = mesh.renderingGroupId || 0;
  11646. if (!this._renderingGroups[renderingGroupId]) {
  11647. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  11648. }
  11649. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  11650. };
  11651. RenderingManager.MAX_RENDERINGGROUPS = 4;
  11652. return RenderingManager;
  11653. })();
  11654. BABYLON.RenderingManager = RenderingManager;
  11655. })(BABYLON || (BABYLON = {}));
  11656. //# sourceMappingURL=babylon.renderingManager.js.map
  11657. var BABYLON;
  11658. (function (BABYLON) {
  11659. var Texture = (function (_super) {
  11660. __extends(Texture, _super);
  11661. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  11662. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  11663. if (onLoad === void 0) { onLoad = null; }
  11664. if (onError === void 0) { onError = null; }
  11665. if (buffer === void 0) { buffer = null; }
  11666. if (deleteBuffer === void 0) { deleteBuffer = false; }
  11667. _super.call(this, scene);
  11668. this.uOffset = 0;
  11669. this.vOffset = 0;
  11670. this.uScale = 1.0;
  11671. this.vScale = 1.0;
  11672. this.uAng = 0;
  11673. this.vAng = 0;
  11674. this.wAng = 0;
  11675. this.name = url;
  11676. this.url = url;
  11677. this._noMipmap = noMipmap;
  11678. this._invertY = invertY;
  11679. this._samplingMode = samplingMode;
  11680. this._buffer = buffer;
  11681. this._deleteBuffer = deleteBuffer;
  11682. if (!url) {
  11683. return;
  11684. }
  11685. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  11686. if (!this._texture) {
  11687. if (!scene.useDelayedTextureLoading) {
  11688. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  11689. if (deleteBuffer) {
  11690. delete this._buffer;
  11691. }
  11692. }
  11693. else {
  11694. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  11695. }
  11696. }
  11697. }
  11698. Texture.prototype.delayLoad = function () {
  11699. if (this.delayLoadState != BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  11700. return;
  11701. }
  11702. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  11703. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  11704. if (!this._texture) {
  11705. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  11706. if (this._deleteBuffer) {
  11707. delete this._buffer;
  11708. }
  11709. }
  11710. };
  11711. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  11712. x -= this.uOffset + 0.5;
  11713. y -= this.vOffset + 0.5;
  11714. z -= 0.5;
  11715. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  11716. t.x *= this.uScale;
  11717. t.y *= this.vScale;
  11718. t.x += 0.5;
  11719. t.y += 0.5;
  11720. t.z += 0.5;
  11721. };
  11722. Texture.prototype.getTextureMatrix = function () {
  11723. if (this.uOffset === this._cachedUOffset && this.vOffset === this._cachedVOffset && this.uScale === this._cachedUScale && this.vScale === this._cachedVScale && this.uAng === this._cachedUAng && this.vAng === this._cachedVAng && this.wAng === this._cachedWAng) {
  11724. return this._cachedTextureMatrix;
  11725. }
  11726. this._cachedUOffset = this.uOffset;
  11727. this._cachedVOffset = this.vOffset;
  11728. this._cachedUScale = this.uScale;
  11729. this._cachedVScale = this.vScale;
  11730. this._cachedUAng = this.uAng;
  11731. this._cachedVAng = this.vAng;
  11732. this._cachedWAng = this.wAng;
  11733. if (!this._cachedTextureMatrix) {
  11734. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  11735. this._rowGenerationMatrix = new BABYLON.Matrix();
  11736. this._t0 = BABYLON.Vector3.Zero();
  11737. this._t1 = BABYLON.Vector3.Zero();
  11738. this._t2 = BABYLON.Vector3.Zero();
  11739. }
  11740. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  11741. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  11742. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  11743. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  11744. this._t1.subtractInPlace(this._t0);
  11745. this._t2.subtractInPlace(this._t0);
  11746. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  11747. this._cachedTextureMatrix.m[0] = this._t1.x;
  11748. this._cachedTextureMatrix.m[1] = this._t1.y;
  11749. this._cachedTextureMatrix.m[2] = this._t1.z;
  11750. this._cachedTextureMatrix.m[4] = this._t2.x;
  11751. this._cachedTextureMatrix.m[5] = this._t2.y;
  11752. this._cachedTextureMatrix.m[6] = this._t2.z;
  11753. this._cachedTextureMatrix.m[8] = this._t0.x;
  11754. this._cachedTextureMatrix.m[9] = this._t0.y;
  11755. this._cachedTextureMatrix.m[10] = this._t0.z;
  11756. return this._cachedTextureMatrix;
  11757. };
  11758. Texture.prototype.getReflectionTextureMatrix = function () {
  11759. if (this.uOffset === this._cachedUOffset && this.vOffset === this._cachedVOffset && this.uScale === this._cachedUScale && this.vScale === this._cachedVScale && this.coordinatesMode === this._cachedCoordinatesMode) {
  11760. return this._cachedTextureMatrix;
  11761. }
  11762. if (!this._cachedTextureMatrix) {
  11763. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  11764. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  11765. }
  11766. this._cachedCoordinatesMode = this.coordinatesMode;
  11767. switch (this.coordinatesMode) {
  11768. case BABYLON.Texture.SPHERICAL_MODE:
  11769. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  11770. this._cachedTextureMatrix[0] = -0.5 * this.uScale;
  11771. this._cachedTextureMatrix[5] = -0.5 * this.vScale;
  11772. this._cachedTextureMatrix[12] = 0.5 + this.uOffset;
  11773. this._cachedTextureMatrix[13] = 0.5 + this.vOffset;
  11774. break;
  11775. case BABYLON.Texture.PLANAR_MODE:
  11776. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  11777. this._cachedTextureMatrix[0] = this.uScale;
  11778. this._cachedTextureMatrix[5] = this.vScale;
  11779. this._cachedTextureMatrix[12] = this.uOffset;
  11780. this._cachedTextureMatrix[13] = this.vOffset;
  11781. break;
  11782. case BABYLON.Texture.PROJECTION_MODE:
  11783. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  11784. this._projectionModeMatrix.m[0] = 0.5;
  11785. this._projectionModeMatrix.m[5] = -0.5;
  11786. this._projectionModeMatrix.m[10] = 0.0;
  11787. this._projectionModeMatrix.m[12] = 0.5;
  11788. this._projectionModeMatrix.m[13] = 0.5;
  11789. this._projectionModeMatrix.m[14] = 1.0;
  11790. this._projectionModeMatrix.m[15] = 1.0;
  11791. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  11792. break;
  11793. default:
  11794. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  11795. break;
  11796. }
  11797. return this._cachedTextureMatrix;
  11798. };
  11799. Texture.prototype.clone = function () {
  11800. var newTexture = new BABYLON.Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY, this._samplingMode);
  11801. // Base texture
  11802. newTexture.hasAlpha = this.hasAlpha;
  11803. newTexture.level = this.level;
  11804. newTexture.wrapU = this.wrapU;
  11805. newTexture.wrapV = this.wrapV;
  11806. newTexture.coordinatesIndex = this.coordinatesIndex;
  11807. newTexture.coordinatesMode = this.coordinatesMode;
  11808. // Texture
  11809. newTexture.uOffset = this.uOffset;
  11810. newTexture.vOffset = this.vOffset;
  11811. newTexture.uScale = this.uScale;
  11812. newTexture.vScale = this.vScale;
  11813. newTexture.uAng = this.uAng;
  11814. newTexture.vAng = this.vAng;
  11815. newTexture.wAng = this.wAng;
  11816. return newTexture;
  11817. };
  11818. // Statics
  11819. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  11820. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  11821. if (onLoad === void 0) { onLoad = null; }
  11822. if (onError === void 0) { onError = null; }
  11823. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  11824. };
  11825. // Constants
  11826. Texture.NEAREST_SAMPLINGMODE = 1;
  11827. Texture.BILINEAR_SAMPLINGMODE = 2;
  11828. Texture.TRILINEAR_SAMPLINGMODE = 3;
  11829. Texture.EXPLICIT_MODE = 0;
  11830. Texture.SPHERICAL_MODE = 1;
  11831. Texture.PLANAR_MODE = 2;
  11832. Texture.CUBIC_MODE = 3;
  11833. Texture.PROJECTION_MODE = 4;
  11834. Texture.SKYBOX_MODE = 5;
  11835. Texture.CLAMP_ADDRESSMODE = 0;
  11836. Texture.WRAP_ADDRESSMODE = 1;
  11837. Texture.MIRROR_ADDRESSMODE = 2;
  11838. return Texture;
  11839. })(BABYLON.BaseTexture);
  11840. BABYLON.Texture = Texture;
  11841. })(BABYLON || (BABYLON = {}));
  11842. //# sourceMappingURL=babylon.texture.js.map
  11843. var BABYLON;
  11844. (function (BABYLON) {
  11845. var CubeTexture = (function (_super) {
  11846. __extends(CubeTexture, _super);
  11847. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  11848. _super.call(this, scene);
  11849. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  11850. this.name = rootUrl;
  11851. this.url = rootUrl;
  11852. this._noMipmap = noMipmap;
  11853. this.hasAlpha = false;
  11854. this._texture = this._getFromCache(rootUrl, noMipmap);
  11855. if (!extensions) {
  11856. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  11857. }
  11858. this._extensions = extensions;
  11859. if (!this._texture) {
  11860. if (!scene.useDelayedTextureLoading) {
  11861. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  11862. }
  11863. else {
  11864. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  11865. }
  11866. }
  11867. this.isCube = true;
  11868. this._textureMatrix = BABYLON.Matrix.Identity();
  11869. }
  11870. CubeTexture.prototype.clone = function () {
  11871. var newTexture = new BABYLON.CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  11872. // Base texture
  11873. newTexture.level = this.level;
  11874. newTexture.wrapU = this.wrapU;
  11875. newTexture.wrapV = this.wrapV;
  11876. newTexture.coordinatesIndex = this.coordinatesIndex;
  11877. newTexture.coordinatesMode = this.coordinatesMode;
  11878. return newTexture;
  11879. };
  11880. // Methods
  11881. CubeTexture.prototype.delayLoad = function () {
  11882. if (this.delayLoadState != BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  11883. return;
  11884. }
  11885. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  11886. this._texture = this._getFromCache(this.url, this._noMipmap);
  11887. if (!this._texture) {
  11888. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  11889. }
  11890. };
  11891. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  11892. return this._textureMatrix;
  11893. };
  11894. return CubeTexture;
  11895. })(BABYLON.BaseTexture);
  11896. BABYLON.CubeTexture = CubeTexture;
  11897. })(BABYLON || (BABYLON = {}));
  11898. //# sourceMappingURL=babylon.cubeTexture.js.map
  11899. var BABYLON;
  11900. (function (BABYLON) {
  11901. var RenderTargetTexture = (function (_super) {
  11902. __extends(RenderTargetTexture, _super);
  11903. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type) {
  11904. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  11905. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  11906. _super.call(this, null, scene, !generateMipMaps);
  11907. this.renderList = new Array();
  11908. this.renderParticles = true;
  11909. this.renderSprites = false;
  11910. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  11911. this._currentRefreshId = -1;
  11912. this._refreshRate = 1;
  11913. this.name = name;
  11914. this.isRenderTarget = true;
  11915. this._size = size;
  11916. this._generateMipMaps = generateMipMaps;
  11917. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  11918. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  11919. // Rendering groups
  11920. this._renderingManager = new BABYLON.RenderingManager(scene);
  11921. }
  11922. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  11923. this._currentRefreshId = -1;
  11924. };
  11925. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  11926. get: function () {
  11927. return this._refreshRate;
  11928. },
  11929. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  11930. set: function (value) {
  11931. this._refreshRate = value;
  11932. this.resetRefreshCounter();
  11933. },
  11934. enumerable: true,
  11935. configurable: true
  11936. });
  11937. RenderTargetTexture.prototype._shouldRender = function () {
  11938. if (this._currentRefreshId === -1) {
  11939. this._currentRefreshId = 1;
  11940. return true;
  11941. }
  11942. if (this.refreshRate === this._currentRefreshId) {
  11943. this._currentRefreshId = 1;
  11944. return true;
  11945. }
  11946. this._currentRefreshId++;
  11947. return false;
  11948. };
  11949. RenderTargetTexture.prototype.isReady = function () {
  11950. if (!this.getScene().renderTargetsEnabled) {
  11951. return false;
  11952. }
  11953. return _super.prototype.isReady.call(this);
  11954. };
  11955. RenderTargetTexture.prototype.getRenderSize = function () {
  11956. return this._size;
  11957. };
  11958. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  11959. get: function () {
  11960. return true;
  11961. },
  11962. enumerable: true,
  11963. configurable: true
  11964. });
  11965. RenderTargetTexture.prototype.scale = function (ratio) {
  11966. var newSize = this._size * ratio;
  11967. this.resize(newSize, this._generateMipMaps);
  11968. };
  11969. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  11970. this.releaseInternalTexture();
  11971. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  11972. };
  11973. RenderTargetTexture.prototype.render = function (useCameraPostProcess) {
  11974. var scene = this.getScene();
  11975. var engine = scene.getEngine();
  11976. if (this._waitingRenderList) {
  11977. this.renderList = [];
  11978. for (var index = 0; index < this._waitingRenderList.length; index++) {
  11979. var id = this._waitingRenderList[index];
  11980. this.renderList.push(scene.getMeshByID(id));
  11981. }
  11982. delete this._waitingRenderList;
  11983. }
  11984. if (this.renderList && this.renderList.length === 0) {
  11985. return;
  11986. }
  11987. // Bind
  11988. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  11989. engine.bindFramebuffer(this._texture);
  11990. }
  11991. this._renderingManager.reset();
  11992. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  11993. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  11994. var mesh = currentRenderList[meshIndex];
  11995. if (mesh) {
  11996. if (!mesh.isReady()) {
  11997. // Reset _currentRefreshId
  11998. this.resetRefreshCounter();
  11999. continue;
  12000. }
  12001. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  12002. mesh._activate(scene.getRenderId());
  12003. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  12004. var subMesh = mesh.subMeshes[subIndex];
  12005. scene._activeVertices += subMesh.indexCount;
  12006. this._renderingManager.dispatch(subMesh);
  12007. }
  12008. }
  12009. }
  12010. }
  12011. if (this.onBeforeRender) {
  12012. this.onBeforeRender();
  12013. }
  12014. // Clear
  12015. engine.clear(scene.clearColor, true, true);
  12016. if (!this._doNotChangeAspectRatio) {
  12017. scene.updateTransformMatrix(true);
  12018. }
  12019. // Render
  12020. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  12021. if (useCameraPostProcess) {
  12022. scene.postProcessManager._finalizeFrame(false, this._texture);
  12023. }
  12024. if (!this._doNotChangeAspectRatio) {
  12025. scene.updateTransformMatrix(true);
  12026. }
  12027. if (this.onAfterRender) {
  12028. this.onAfterRender();
  12029. }
  12030. // Unbind
  12031. engine.unBindFramebuffer(this._texture);
  12032. };
  12033. RenderTargetTexture.prototype.clone = function () {
  12034. var textureSize = this.getSize();
  12035. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  12036. // Base texture
  12037. newTexture.hasAlpha = this.hasAlpha;
  12038. newTexture.level = this.level;
  12039. // RenderTarget Texture
  12040. newTexture.coordinatesMode = this.coordinatesMode;
  12041. newTexture.renderList = this.renderList.slice(0);
  12042. return newTexture;
  12043. };
  12044. return RenderTargetTexture;
  12045. })(BABYLON.Texture);
  12046. BABYLON.RenderTargetTexture = RenderTargetTexture;
  12047. })(BABYLON || (BABYLON = {}));
  12048. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  12049. var BABYLON;
  12050. (function (BABYLON) {
  12051. var ProceduralTexture = (function (_super) {
  12052. __extends(ProceduralTexture, _super);
  12053. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps) {
  12054. if (generateMipMaps === void 0) { generateMipMaps = true; }
  12055. _super.call(this, null, scene, !generateMipMaps);
  12056. this._currentRefreshId = -1;
  12057. this._refreshRate = 1;
  12058. this._vertexDeclaration = [2];
  12059. this._vertexStrideSize = 2 * 4;
  12060. this._uniforms = new Array();
  12061. this._samplers = new Array();
  12062. this._textures = new Array();
  12063. this._floats = new Array();
  12064. this._floatsArrays = {};
  12065. this._colors3 = new Array();
  12066. this._colors4 = new Array();
  12067. this._vectors2 = new Array();
  12068. this._vectors3 = new Array();
  12069. this._matrices = new Array();
  12070. this._fallbackTextureUsed = false;
  12071. scene._proceduralTextures.push(this);
  12072. this.name = name;
  12073. this.isRenderTarget = true;
  12074. this._size = size;
  12075. this._generateMipMaps = generateMipMaps;
  12076. this.setFragment(fragment);
  12077. this._fallbackTexture = fallbackTexture;
  12078. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  12079. // VBO
  12080. var vertices = [];
  12081. vertices.push(1, 1);
  12082. vertices.push(-1, 1);
  12083. vertices.push(-1, -1);
  12084. vertices.push(1, -1);
  12085. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  12086. // Indices
  12087. var indices = [];
  12088. indices.push(0);
  12089. indices.push(1);
  12090. indices.push(2);
  12091. indices.push(0);
  12092. indices.push(2);
  12093. indices.push(3);
  12094. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  12095. }
  12096. ProceduralTexture.prototype.reset = function () {
  12097. if (this._effect === undefined) {
  12098. return;
  12099. }
  12100. var engine = this.getScene().getEngine();
  12101. engine._releaseEffect(this._effect);
  12102. };
  12103. ProceduralTexture.prototype.isReady = function () {
  12104. var _this = this;
  12105. var engine = this.getScene().getEngine();
  12106. var shaders;
  12107. if (!this._fragment) {
  12108. return false;
  12109. }
  12110. if (this._fallbackTextureUsed) {
  12111. return true;
  12112. }
  12113. if (this._fragment.fragmentElement !== undefined) {
  12114. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  12115. }
  12116. else {
  12117. shaders = { vertex: "procedural", fragment: this._fragment };
  12118. }
  12119. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  12120. _this.releaseInternalTexture();
  12121. if (_this._fallbackTexture) {
  12122. _this._texture = _this._fallbackTexture._texture;
  12123. _this._texture.references++;
  12124. }
  12125. _this._fallbackTextureUsed = true;
  12126. });
  12127. return this._effect.isReady();
  12128. };
  12129. ProceduralTexture.prototype.resetRefreshCounter = function () {
  12130. this._currentRefreshId = -1;
  12131. };
  12132. ProceduralTexture.prototype.setFragment = function (fragment) {
  12133. this._fragment = fragment;
  12134. };
  12135. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  12136. get: function () {
  12137. return this._refreshRate;
  12138. },
  12139. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  12140. set: function (value) {
  12141. this._refreshRate = value;
  12142. this.resetRefreshCounter();
  12143. },
  12144. enumerable: true,
  12145. configurable: true
  12146. });
  12147. ProceduralTexture.prototype._shouldRender = function () {
  12148. if (!this.isReady() || !this._texture) {
  12149. return false;
  12150. }
  12151. if (this._fallbackTextureUsed) {
  12152. return false;
  12153. }
  12154. if (this._currentRefreshId === -1) {
  12155. this._currentRefreshId = 1;
  12156. return true;
  12157. }
  12158. if (this.refreshRate === this._currentRefreshId) {
  12159. this._currentRefreshId = 1;
  12160. return true;
  12161. }
  12162. this._currentRefreshId++;
  12163. return false;
  12164. };
  12165. ProceduralTexture.prototype.getRenderSize = function () {
  12166. return this._size;
  12167. };
  12168. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  12169. if (this._fallbackTextureUsed) {
  12170. return;
  12171. }
  12172. this.releaseInternalTexture();
  12173. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  12174. };
  12175. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  12176. if (this._uniforms.indexOf(uniformName) === -1) {
  12177. this._uniforms.push(uniformName);
  12178. }
  12179. };
  12180. ProceduralTexture.prototype.setTexture = function (name, texture) {
  12181. if (this._samplers.indexOf(name) === -1) {
  12182. this._samplers.push(name);
  12183. }
  12184. this._textures[name] = texture;
  12185. return this;
  12186. };
  12187. ProceduralTexture.prototype.setFloat = function (name, value) {
  12188. this._checkUniform(name);
  12189. this._floats[name] = value;
  12190. return this;
  12191. };
  12192. ProceduralTexture.prototype.setFloats = function (name, value) {
  12193. this._checkUniform(name);
  12194. this._floatsArrays[name] = value;
  12195. return this;
  12196. };
  12197. ProceduralTexture.prototype.setColor3 = function (name, value) {
  12198. this._checkUniform(name);
  12199. this._colors3[name] = value;
  12200. return this;
  12201. };
  12202. ProceduralTexture.prototype.setColor4 = function (name, value) {
  12203. this._checkUniform(name);
  12204. this._colors4[name] = value;
  12205. return this;
  12206. };
  12207. ProceduralTexture.prototype.setVector2 = function (name, value) {
  12208. this._checkUniform(name);
  12209. this._vectors2[name] = value;
  12210. return this;
  12211. };
  12212. ProceduralTexture.prototype.setVector3 = function (name, value) {
  12213. this._checkUniform(name);
  12214. this._vectors3[name] = value;
  12215. return this;
  12216. };
  12217. ProceduralTexture.prototype.setMatrix = function (name, value) {
  12218. this._checkUniform(name);
  12219. this._matrices[name] = value;
  12220. return this;
  12221. };
  12222. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  12223. var scene = this.getScene();
  12224. var engine = scene.getEngine();
  12225. engine.bindFramebuffer(this._texture);
  12226. // Clear
  12227. engine.clear(scene.clearColor, true, true);
  12228. // Render
  12229. engine.enableEffect(this._effect);
  12230. engine.setState(false);
  12231. for (var name in this._textures) {
  12232. this._effect.setTexture(name, this._textures[name]);
  12233. }
  12234. for (name in this._floats) {
  12235. this._effect.setFloat(name, this._floats[name]);
  12236. }
  12237. for (name in this._floatsArrays) {
  12238. this._effect.setArray(name, this._floatsArrays[name]);
  12239. }
  12240. for (name in this._colors3) {
  12241. this._effect.setColor3(name, this._colors3[name]);
  12242. }
  12243. for (name in this._colors4) {
  12244. var color = this._colors4[name];
  12245. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  12246. }
  12247. for (name in this._vectors2) {
  12248. this._effect.setVector2(name, this._vectors2[name]);
  12249. }
  12250. for (name in this._vectors3) {
  12251. this._effect.setVector3(name, this._vectors3[name]);
  12252. }
  12253. for (name in this._matrices) {
  12254. this._effect.setMatrix(name, this._matrices[name]);
  12255. }
  12256. // VBOs
  12257. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  12258. // Draw order
  12259. engine.draw(true, 0, 6);
  12260. // Unbind
  12261. engine.unBindFramebuffer(this._texture);
  12262. };
  12263. ProceduralTexture.prototype.clone = function () {
  12264. var textureSize = this.getSize();
  12265. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  12266. // Base texture
  12267. newTexture.hasAlpha = this.hasAlpha;
  12268. newTexture.level = this.level;
  12269. // RenderTarget Texture
  12270. newTexture.coordinatesMode = this.coordinatesMode;
  12271. return newTexture;
  12272. };
  12273. ProceduralTexture.prototype.dispose = function () {
  12274. var index = this.getScene()._proceduralTextures.indexOf(this);
  12275. if (index >= 0) {
  12276. this.getScene()._proceduralTextures.splice(index, 1);
  12277. }
  12278. _super.prototype.dispose.call(this);
  12279. };
  12280. return ProceduralTexture;
  12281. })(BABYLON.Texture);
  12282. BABYLON.ProceduralTexture = ProceduralTexture;
  12283. })(BABYLON || (BABYLON = {}));
  12284. //# sourceMappingURL=babylon.proceduralTexture.js.map
  12285. var BABYLON;
  12286. (function (BABYLON) {
  12287. var WoodProceduralTexture = (function (_super) {
  12288. __extends(WoodProceduralTexture, _super);
  12289. function WoodProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12290. _super.call(this, name, size, "wood", scene, fallbackTexture, generateMipMaps);
  12291. this._ampScale = 100.0;
  12292. this._woodColor = new BABYLON.Color3(0.32, 0.17, 0.09);
  12293. this.updateShaderUniforms();
  12294. this.refreshRate = 0;
  12295. }
  12296. WoodProceduralTexture.prototype.updateShaderUniforms = function () {
  12297. this.setFloat("ampScale", this._ampScale);
  12298. this.setColor3("woodColor", this._woodColor);
  12299. };
  12300. Object.defineProperty(WoodProceduralTexture.prototype, "ampScale", {
  12301. get: function () {
  12302. return this._ampScale;
  12303. },
  12304. set: function (value) {
  12305. this._ampScale = value;
  12306. this.updateShaderUniforms();
  12307. },
  12308. enumerable: true,
  12309. configurable: true
  12310. });
  12311. Object.defineProperty(WoodProceduralTexture.prototype, "woodColor", {
  12312. get: function () {
  12313. return this._woodColor;
  12314. },
  12315. set: function (value) {
  12316. this._woodColor = value;
  12317. this.updateShaderUniforms();
  12318. },
  12319. enumerable: true,
  12320. configurable: true
  12321. });
  12322. return WoodProceduralTexture;
  12323. })(BABYLON.ProceduralTexture);
  12324. BABYLON.WoodProceduralTexture = WoodProceduralTexture;
  12325. var FireProceduralTexture = (function (_super) {
  12326. __extends(FireProceduralTexture, _super);
  12327. function FireProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12328. _super.call(this, name, size, "fire", scene, fallbackTexture, generateMipMaps);
  12329. this._time = 0.0;
  12330. this._speed = new BABYLON.Vector2(0.5, 0.3);
  12331. this._shift = 1.6;
  12332. this._autoGenerateTime = true;
  12333. this._alphaThreshold = 0.5;
  12334. this._fireColors = FireProceduralTexture.RedFireColors;
  12335. this.updateShaderUniforms();
  12336. this.refreshRate = 1;
  12337. }
  12338. FireProceduralTexture.prototype.updateShaderUniforms = function () {
  12339. this.setFloat("time", this._time);
  12340. this.setVector2("speed", this._speed);
  12341. this.setFloat("shift", this._shift);
  12342. this.setColor3("c1", this._fireColors[0]);
  12343. this.setColor3("c2", this._fireColors[1]);
  12344. this.setColor3("c3", this._fireColors[2]);
  12345. this.setColor3("c4", this._fireColors[3]);
  12346. this.setColor3("c5", this._fireColors[4]);
  12347. this.setColor3("c6", this._fireColors[5]);
  12348. this.setFloat("alphaThreshold", this._alphaThreshold);
  12349. };
  12350. FireProceduralTexture.prototype.render = function (useCameraPostProcess) {
  12351. if (this._autoGenerateTime) {
  12352. this._time += this.getScene().getAnimationRatio() * 0.03;
  12353. this.updateShaderUniforms();
  12354. }
  12355. _super.prototype.render.call(this, useCameraPostProcess);
  12356. };
  12357. Object.defineProperty(FireProceduralTexture, "PurpleFireColors", {
  12358. get: function () {
  12359. return [
  12360. new BABYLON.Color3(0.5, 0.0, 1.0),
  12361. new BABYLON.Color3(0.9, 0.0, 1.0),
  12362. new BABYLON.Color3(0.2, 0.0, 1.0),
  12363. new BABYLON.Color3(1.0, 0.9, 1.0),
  12364. new BABYLON.Color3(0.1, 0.1, 1.0),
  12365. new BABYLON.Color3(0.9, 0.9, 1.0)
  12366. ];
  12367. },
  12368. enumerable: true,
  12369. configurable: true
  12370. });
  12371. Object.defineProperty(FireProceduralTexture, "GreenFireColors", {
  12372. get: function () {
  12373. return [
  12374. new BABYLON.Color3(0.5, 1.0, 0.0),
  12375. new BABYLON.Color3(0.5, 1.0, 0.0),
  12376. new BABYLON.Color3(0.3, 0.4, 0.0),
  12377. new BABYLON.Color3(0.5, 1.0, 0.0),
  12378. new BABYLON.Color3(0.2, 0.0, 0.0),
  12379. new BABYLON.Color3(0.5, 1.0, 0.0)
  12380. ];
  12381. },
  12382. enumerable: true,
  12383. configurable: true
  12384. });
  12385. Object.defineProperty(FireProceduralTexture, "RedFireColors", {
  12386. get: function () {
  12387. return [
  12388. new BABYLON.Color3(0.5, 0.0, 0.1),
  12389. new BABYLON.Color3(0.9, 0.0, 0.0),
  12390. new BABYLON.Color3(0.2, 0.0, 0.0),
  12391. new BABYLON.Color3(1.0, 0.9, 0.0),
  12392. new BABYLON.Color3(0.1, 0.1, 0.1),
  12393. new BABYLON.Color3(0.9, 0.9, 0.9)
  12394. ];
  12395. },
  12396. enumerable: true,
  12397. configurable: true
  12398. });
  12399. Object.defineProperty(FireProceduralTexture, "BlueFireColors", {
  12400. get: function () {
  12401. return [
  12402. new BABYLON.Color3(0.1, 0.0, 0.5),
  12403. new BABYLON.Color3(0.0, 0.0, 0.5),
  12404. new BABYLON.Color3(0.1, 0.0, 0.2),
  12405. new BABYLON.Color3(0.0, 0.0, 1.0),
  12406. new BABYLON.Color3(0.1, 0.2, 0.3),
  12407. new BABYLON.Color3(0.0, 0.2, 0.9)
  12408. ];
  12409. },
  12410. enumerable: true,
  12411. configurable: true
  12412. });
  12413. Object.defineProperty(FireProceduralTexture.prototype, "fireColors", {
  12414. get: function () {
  12415. return this._fireColors;
  12416. },
  12417. set: function (value) {
  12418. this._fireColors = value;
  12419. this.updateShaderUniforms();
  12420. },
  12421. enumerable: true,
  12422. configurable: true
  12423. });
  12424. Object.defineProperty(FireProceduralTexture.prototype, "time", {
  12425. get: function () {
  12426. return this._time;
  12427. },
  12428. set: function (value) {
  12429. this._time = value;
  12430. this.updateShaderUniforms();
  12431. },
  12432. enumerable: true,
  12433. configurable: true
  12434. });
  12435. Object.defineProperty(FireProceduralTexture.prototype, "speed", {
  12436. get: function () {
  12437. return this._speed;
  12438. },
  12439. set: function (value) {
  12440. this._speed = value;
  12441. this.updateShaderUniforms();
  12442. },
  12443. enumerable: true,
  12444. configurable: true
  12445. });
  12446. Object.defineProperty(FireProceduralTexture.prototype, "shift", {
  12447. get: function () {
  12448. return this._shift;
  12449. },
  12450. set: function (value) {
  12451. this._shift = value;
  12452. this.updateShaderUniforms();
  12453. },
  12454. enumerable: true,
  12455. configurable: true
  12456. });
  12457. Object.defineProperty(FireProceduralTexture.prototype, "alphaThreshold", {
  12458. get: function () {
  12459. return this._alphaThreshold;
  12460. },
  12461. set: function (value) {
  12462. this._alphaThreshold = value;
  12463. this.updateShaderUniforms();
  12464. },
  12465. enumerable: true,
  12466. configurable: true
  12467. });
  12468. return FireProceduralTexture;
  12469. })(BABYLON.ProceduralTexture);
  12470. BABYLON.FireProceduralTexture = FireProceduralTexture;
  12471. var CloudProceduralTexture = (function (_super) {
  12472. __extends(CloudProceduralTexture, _super);
  12473. function CloudProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12474. _super.call(this, name, size, "cloud", scene, fallbackTexture, generateMipMaps);
  12475. this._skyColor = new BABYLON.Color3(0.15, 0.68, 1.0);
  12476. this._cloudColor = new BABYLON.Color3(1, 1, 1);
  12477. this.updateShaderUniforms();
  12478. this.refreshRate = 0;
  12479. }
  12480. CloudProceduralTexture.prototype.updateShaderUniforms = function () {
  12481. this.setColor3("skyColor", this._skyColor);
  12482. this.setColor3("cloudColor", this._cloudColor);
  12483. };
  12484. Object.defineProperty(CloudProceduralTexture.prototype, "skyColor", {
  12485. get: function () {
  12486. return this._skyColor;
  12487. },
  12488. set: function (value) {
  12489. this._skyColor = value;
  12490. this.updateShaderUniforms();
  12491. },
  12492. enumerable: true,
  12493. configurable: true
  12494. });
  12495. Object.defineProperty(CloudProceduralTexture.prototype, "cloudColor", {
  12496. get: function () {
  12497. return this._cloudColor;
  12498. },
  12499. set: function (value) {
  12500. this._cloudColor = value;
  12501. this.updateShaderUniforms();
  12502. },
  12503. enumerable: true,
  12504. configurable: true
  12505. });
  12506. return CloudProceduralTexture;
  12507. })(BABYLON.ProceduralTexture);
  12508. BABYLON.CloudProceduralTexture = CloudProceduralTexture;
  12509. var GrassProceduralTexture = (function (_super) {
  12510. __extends(GrassProceduralTexture, _super);
  12511. function GrassProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12512. _super.call(this, name, size, "grass", scene, fallbackTexture, generateMipMaps);
  12513. this._herb1 = new BABYLON.Color3(0.29, 0.38, 0.02);
  12514. this._herb2 = new BABYLON.Color3(0.36, 0.49, 0.09);
  12515. this._herb3 = new BABYLON.Color3(0.51, 0.6, 0.28);
  12516. this._groundColor = new BABYLON.Color3(1, 1, 1);
  12517. this._grassColors = [
  12518. new BABYLON.Color3(0.29, 0.38, 0.02),
  12519. new BABYLON.Color3(0.36, 0.49, 0.09),
  12520. new BABYLON.Color3(0.51, 0.6, 0.28)
  12521. ];
  12522. this.updateShaderUniforms();
  12523. this.refreshRate = 0;
  12524. }
  12525. GrassProceduralTexture.prototype.updateShaderUniforms = function () {
  12526. this.setColor3("herb1Color", this._grassColors[0]);
  12527. this.setColor3("herb2Color", this._grassColors[1]);
  12528. this.setColor3("herb3Color", this._grassColors[2]);
  12529. this.setColor3("groundColor", this._groundColor);
  12530. };
  12531. Object.defineProperty(GrassProceduralTexture.prototype, "grassColors", {
  12532. get: function () {
  12533. return this._grassColors;
  12534. },
  12535. set: function (value) {
  12536. this._grassColors = value;
  12537. this.updateShaderUniforms();
  12538. },
  12539. enumerable: true,
  12540. configurable: true
  12541. });
  12542. Object.defineProperty(GrassProceduralTexture.prototype, "groundColor", {
  12543. get: function () {
  12544. return this._groundColor;
  12545. },
  12546. set: function (value) {
  12547. this.groundColor = value;
  12548. this.updateShaderUniforms();
  12549. },
  12550. enumerable: true,
  12551. configurable: true
  12552. });
  12553. return GrassProceduralTexture;
  12554. })(BABYLON.ProceduralTexture);
  12555. BABYLON.GrassProceduralTexture = GrassProceduralTexture;
  12556. var RoadProceduralTexture = (function (_super) {
  12557. __extends(RoadProceduralTexture, _super);
  12558. function RoadProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12559. _super.call(this, name, size, "road", scene, fallbackTexture, generateMipMaps);
  12560. this._roadColor = new BABYLON.Color3(0.53, 0.53, 0.53);
  12561. this.updateShaderUniforms();
  12562. this.refreshRate = 0;
  12563. }
  12564. RoadProceduralTexture.prototype.updateShaderUniforms = function () {
  12565. this.setColor3("roadColor", this._roadColor);
  12566. };
  12567. Object.defineProperty(RoadProceduralTexture.prototype, "roadColor", {
  12568. get: function () {
  12569. return this._roadColor;
  12570. },
  12571. set: function (value) {
  12572. this._roadColor = value;
  12573. this.updateShaderUniforms();
  12574. },
  12575. enumerable: true,
  12576. configurable: true
  12577. });
  12578. return RoadProceduralTexture;
  12579. })(BABYLON.ProceduralTexture);
  12580. BABYLON.RoadProceduralTexture = RoadProceduralTexture;
  12581. var BrickProceduralTexture = (function (_super) {
  12582. __extends(BrickProceduralTexture, _super);
  12583. function BrickProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12584. _super.call(this, name, size, "brick", scene, fallbackTexture, generateMipMaps);
  12585. this._numberOfBricksHeight = 15;
  12586. this._numberOfBricksWidth = 5;
  12587. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  12588. this._brickColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  12589. this.updateShaderUniforms();
  12590. this.refreshRate = 0;
  12591. }
  12592. BrickProceduralTexture.prototype.updateShaderUniforms = function () {
  12593. this.setFloat("numberOfBricksHeight", this._numberOfBricksHeight);
  12594. this.setFloat("numberOfBricksWidth", this._numberOfBricksWidth);
  12595. this.setColor3("brickColor", this._brickColor);
  12596. this.setColor3("jointColor", this._jointColor);
  12597. };
  12598. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksHeight", {
  12599. get: function () {
  12600. return this._numberOfBricksHeight;
  12601. },
  12602. enumerable: true,
  12603. configurable: true
  12604. });
  12605. Object.defineProperty(BrickProceduralTexture.prototype, "cloudColor", {
  12606. set: function (value) {
  12607. this._numberOfBricksHeight = value;
  12608. this.updateShaderUniforms();
  12609. },
  12610. enumerable: true,
  12611. configurable: true
  12612. });
  12613. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksWidth", {
  12614. get: function () {
  12615. return this._numberOfBricksWidth;
  12616. },
  12617. set: function (value) {
  12618. this._numberOfBricksHeight = value;
  12619. this.updateShaderUniforms();
  12620. },
  12621. enumerable: true,
  12622. configurable: true
  12623. });
  12624. Object.defineProperty(BrickProceduralTexture.prototype, "jointColor", {
  12625. get: function () {
  12626. return this._jointColor;
  12627. },
  12628. set: function (value) {
  12629. this._jointColor = value;
  12630. this.updateShaderUniforms();
  12631. },
  12632. enumerable: true,
  12633. configurable: true
  12634. });
  12635. Object.defineProperty(BrickProceduralTexture.prototype, "brickColor", {
  12636. get: function () {
  12637. return this._brickColor;
  12638. },
  12639. set: function (value) {
  12640. this._brickColor = value;
  12641. this.updateShaderUniforms();
  12642. },
  12643. enumerable: true,
  12644. configurable: true
  12645. });
  12646. return BrickProceduralTexture;
  12647. })(BABYLON.ProceduralTexture);
  12648. BABYLON.BrickProceduralTexture = BrickProceduralTexture;
  12649. var MarbleProceduralTexture = (function (_super) {
  12650. __extends(MarbleProceduralTexture, _super);
  12651. function MarbleProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12652. _super.call(this, name, size, "marble", scene, fallbackTexture, generateMipMaps);
  12653. this._numberOfTilesHeight = 3;
  12654. this._numberOfTilesWidth = 3;
  12655. this._amplitude = 9.0;
  12656. this._marbleColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  12657. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  12658. this.updateShaderUniforms();
  12659. this.refreshRate = 0;
  12660. }
  12661. MarbleProceduralTexture.prototype.updateShaderUniforms = function () {
  12662. this.setFloat("numberOfTilesHeight", this._numberOfTilesHeight);
  12663. this.setFloat("numberOfTilesWidth", this._numberOfTilesWidth);
  12664. this.setFloat("amplitude", this._amplitude);
  12665. this.setColor3("marbleColor", this._marbleColor);
  12666. this.setColor3("jointColor", this._jointColor);
  12667. };
  12668. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesHeight", {
  12669. get: function () {
  12670. return this._numberOfTilesHeight;
  12671. },
  12672. set: function (value) {
  12673. this._numberOfTilesHeight = value;
  12674. this.updateShaderUniforms();
  12675. },
  12676. enumerable: true,
  12677. configurable: true
  12678. });
  12679. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesWidth", {
  12680. get: function () {
  12681. return this._numberOfTilesWidth;
  12682. },
  12683. set: function (value) {
  12684. this._numberOfTilesWidth = value;
  12685. this.updateShaderUniforms();
  12686. },
  12687. enumerable: true,
  12688. configurable: true
  12689. });
  12690. Object.defineProperty(MarbleProceduralTexture.prototype, "jointColor", {
  12691. get: function () {
  12692. return this._jointColor;
  12693. },
  12694. set: function (value) {
  12695. this._jointColor = value;
  12696. this.updateShaderUniforms();
  12697. },
  12698. enumerable: true,
  12699. configurable: true
  12700. });
  12701. Object.defineProperty(MarbleProceduralTexture.prototype, "marbleColor", {
  12702. get: function () {
  12703. return this._marbleColor;
  12704. },
  12705. set: function (value) {
  12706. this._marbleColor = value;
  12707. this.updateShaderUniforms();
  12708. },
  12709. enumerable: true,
  12710. configurable: true
  12711. });
  12712. return MarbleProceduralTexture;
  12713. })(BABYLON.ProceduralTexture);
  12714. BABYLON.MarbleProceduralTexture = MarbleProceduralTexture;
  12715. })(BABYLON || (BABYLON = {}));
  12716. //# sourceMappingURL=babylon.standardProceduralTexture.js.map
  12717. var BABYLON;
  12718. (function (BABYLON) {
  12719. var CustomProceduralTexture = (function (_super) {
  12720. __extends(CustomProceduralTexture, _super);
  12721. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  12722. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  12723. this._animate = true;
  12724. this._time = 0;
  12725. this._texturePath = texturePath;
  12726. //Try to load json
  12727. this.loadJson(texturePath);
  12728. this.refreshRate = 1;
  12729. }
  12730. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  12731. var _this = this;
  12732. var that = this;
  12733. function noConfigFile() {
  12734. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  12735. try {
  12736. that.setFragment(that._texturePath);
  12737. }
  12738. catch (ex) {
  12739. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  12740. }
  12741. }
  12742. var configFileUrl = jsonUrl + "/config.json";
  12743. var xhr = new XMLHttpRequest();
  12744. xhr.open("GET", configFileUrl, true);
  12745. xhr.addEventListener("load", function () {
  12746. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  12747. try {
  12748. _this._config = JSON.parse(xhr.response);
  12749. _this.updateShaderUniforms();
  12750. _this.updateTextures();
  12751. _this.setFragment(_this._texturePath + "/custom");
  12752. _this._animate = _this._config.animate;
  12753. _this.refreshRate = _this._config.refreshrate;
  12754. }
  12755. catch (ex) {
  12756. noConfigFile();
  12757. }
  12758. }
  12759. else {
  12760. noConfigFile();
  12761. }
  12762. }, false);
  12763. xhr.addEventListener("error", function () {
  12764. noConfigFile();
  12765. }, false);
  12766. try {
  12767. xhr.send();
  12768. }
  12769. catch (ex) {
  12770. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  12771. }
  12772. };
  12773. CustomProceduralTexture.prototype.isReady = function () {
  12774. if (!_super.prototype.isReady.call(this)) {
  12775. return false;
  12776. }
  12777. for (var name in this._textures) {
  12778. var texture = this._textures[name];
  12779. if (!texture.isReady()) {
  12780. return false;
  12781. }
  12782. }
  12783. return true;
  12784. };
  12785. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  12786. if (this._animate) {
  12787. this._time += this.getScene().getAnimationRatio() * 0.03;
  12788. this.updateShaderUniforms();
  12789. }
  12790. _super.prototype.render.call(this, useCameraPostProcess);
  12791. };
  12792. CustomProceduralTexture.prototype.updateTextures = function () {
  12793. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  12794. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  12795. }
  12796. };
  12797. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  12798. if (this._config) {
  12799. for (var j = 0; j < this._config.uniforms.length; j++) {
  12800. var uniform = this._config.uniforms[j];
  12801. switch (uniform.type) {
  12802. case "float":
  12803. this.setFloat(uniform.name, uniform.value);
  12804. break;
  12805. case "color3":
  12806. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  12807. break;
  12808. case "color4":
  12809. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  12810. break;
  12811. case "vector2":
  12812. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  12813. break;
  12814. case "vector3":
  12815. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  12816. break;
  12817. }
  12818. }
  12819. }
  12820. this.setFloat("time", this._time);
  12821. };
  12822. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  12823. get: function () {
  12824. return this._animate;
  12825. },
  12826. set: function (value) {
  12827. this._animate = value;
  12828. },
  12829. enumerable: true,
  12830. configurable: true
  12831. });
  12832. return CustomProceduralTexture;
  12833. })(BABYLON.ProceduralTexture);
  12834. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  12835. })(BABYLON || (BABYLON = {}));
  12836. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  12837. var BABYLON;
  12838. (function (BABYLON) {
  12839. var MirrorTexture = (function (_super) {
  12840. __extends(MirrorTexture, _super);
  12841. function MirrorTexture(name, size, scene, generateMipMaps) {
  12842. var _this = this;
  12843. _super.call(this, name, size, scene, generateMipMaps, true);
  12844. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  12845. this._transformMatrix = BABYLON.Matrix.Zero();
  12846. this._mirrorMatrix = BABYLON.Matrix.Zero();
  12847. this.onBeforeRender = function () {
  12848. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  12849. _this._savedViewMatrix = scene.getViewMatrix();
  12850. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  12851. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  12852. scene.clipPlane = _this.mirrorPlane;
  12853. scene.getEngine().cullBackFaces = false;
  12854. };
  12855. this.onAfterRender = function () {
  12856. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  12857. scene.getEngine().cullBackFaces = true;
  12858. delete scene.clipPlane;
  12859. };
  12860. }
  12861. MirrorTexture.prototype.clone = function () {
  12862. var textureSize = this.getSize();
  12863. var newTexture = new BABYLON.MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  12864. // Base texture
  12865. newTexture.hasAlpha = this.hasAlpha;
  12866. newTexture.level = this.level;
  12867. // Mirror Texture
  12868. newTexture.mirrorPlane = this.mirrorPlane.clone();
  12869. newTexture.renderList = this.renderList.slice(0);
  12870. return newTexture;
  12871. };
  12872. return MirrorTexture;
  12873. })(BABYLON.RenderTargetTexture);
  12874. BABYLON.MirrorTexture = MirrorTexture;
  12875. })(BABYLON || (BABYLON = {}));
  12876. //# sourceMappingURL=babylon.mirrorTexture.js.map
  12877. var BABYLON;
  12878. (function (BABYLON) {
  12879. var DynamicTexture = (function (_super) {
  12880. __extends(DynamicTexture, _super);
  12881. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  12882. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12883. _super.call(this, null, scene, !generateMipMaps);
  12884. this.name = name;
  12885. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  12886. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  12887. this._generateMipMaps = generateMipMaps;
  12888. if (options.getContext) {
  12889. this._canvas = options;
  12890. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  12891. }
  12892. else {
  12893. this._canvas = document.createElement("canvas");
  12894. if (options.width) {
  12895. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  12896. }
  12897. else {
  12898. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  12899. }
  12900. }
  12901. var textureSize = this.getSize();
  12902. this._canvas.width = textureSize.width;
  12903. this._canvas.height = textureSize.height;
  12904. this._context = this._canvas.getContext("2d");
  12905. }
  12906. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  12907. get: function () {
  12908. return true;
  12909. },
  12910. enumerable: true,
  12911. configurable: true
  12912. });
  12913. DynamicTexture.prototype.scale = function (ratio) {
  12914. var textureSize = this.getSize();
  12915. textureSize.width *= ratio;
  12916. textureSize.height *= ratio;
  12917. this._canvas.width = textureSize.width;
  12918. this._canvas.height = textureSize.height;
  12919. this.releaseInternalTexture();
  12920. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  12921. };
  12922. DynamicTexture.prototype.getContext = function () {
  12923. return this._context;
  12924. };
  12925. DynamicTexture.prototype.clear = function () {
  12926. var size = this.getSize();
  12927. this._context.fillRect(0, 0, size.width, size.height);
  12928. };
  12929. DynamicTexture.prototype.update = function (invertY) {
  12930. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  12931. };
  12932. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  12933. if (update === void 0) { update = true; }
  12934. var size = this.getSize();
  12935. if (clearColor) {
  12936. this._context.fillStyle = clearColor;
  12937. this._context.fillRect(0, 0, size.width, size.height);
  12938. }
  12939. this._context.font = font;
  12940. if (x === null) {
  12941. var textSize = this._context.measureText(text);
  12942. x = (size.width - textSize.width) / 2;
  12943. }
  12944. this._context.fillStyle = color;
  12945. this._context.fillText(text, x, y);
  12946. if (update) {
  12947. this.update(invertY);
  12948. }
  12949. };
  12950. DynamicTexture.prototype.clone = function () {
  12951. var textureSize = this.getSize();
  12952. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  12953. // Base texture
  12954. newTexture.hasAlpha = this.hasAlpha;
  12955. newTexture.level = this.level;
  12956. // Dynamic Texture
  12957. newTexture.wrapU = this.wrapU;
  12958. newTexture.wrapV = this.wrapV;
  12959. return newTexture;
  12960. };
  12961. return DynamicTexture;
  12962. })(BABYLON.Texture);
  12963. BABYLON.DynamicTexture = DynamicTexture;
  12964. })(BABYLON || (BABYLON = {}));
  12965. //# sourceMappingURL=babylon.dynamicTexture.js.map
  12966. var BABYLON;
  12967. (function (BABYLON) {
  12968. var VideoTexture = (function (_super) {
  12969. __extends(VideoTexture, _super);
  12970. function VideoTexture(name, urls, size, scene, generateMipMaps, invertY, samplingMode) {
  12971. var _this = this;
  12972. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12973. _super.call(this, null, scene, !generateMipMaps, invertY);
  12974. this._autoLaunch = true;
  12975. this.name = name;
  12976. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  12977. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  12978. var requiredWidth = size.width || size;
  12979. var requiredHeight = size.height || size;
  12980. this._texture = scene.getEngine().createDynamicTexture(requiredWidth, requiredHeight, generateMipMaps, samplingMode);
  12981. var textureSize = this.getSize();
  12982. this.video = document.createElement("video");
  12983. this.video.width = textureSize.width;
  12984. this.video.height = textureSize.height;
  12985. this.video.autoplay = false;
  12986. this.video.loop = true;
  12987. this.video.addEventListener("canplaythrough", function () {
  12988. if (_this._texture) {
  12989. _this._texture.isReady = true;
  12990. }
  12991. });
  12992. urls.forEach(function (url) {
  12993. var source = document.createElement("source");
  12994. source.src = url;
  12995. _this.video.appendChild(source);
  12996. });
  12997. this._lastUpdate = BABYLON.Tools.Now;
  12998. }
  12999. VideoTexture.prototype.update = function () {
  13000. if (this._autoLaunch) {
  13001. this._autoLaunch = false;
  13002. this.video.play();
  13003. }
  13004. var now = BABYLON.Tools.Now;
  13005. if (now - this._lastUpdate < 15) {
  13006. return false;
  13007. }
  13008. this._lastUpdate = now;
  13009. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  13010. return true;
  13011. };
  13012. return VideoTexture;
  13013. })(BABYLON.Texture);
  13014. BABYLON.VideoTexture = VideoTexture;
  13015. })(BABYLON || (BABYLON = {}));
  13016. //# sourceMappingURL=babylon.videoTexture.js.mapvar BABYLON;
  13017. (function (BABYLON) {
  13018. var EffectFallbacks = (function () {
  13019. function EffectFallbacks() {
  13020. this._defines = {};
  13021. this._currentRank = 32;
  13022. this._maxRank = -1;
  13023. }
  13024. EffectFallbacks.prototype.addFallback = function (rank, define) {
  13025. if (!this._defines[rank]) {
  13026. if (rank < this._currentRank) {
  13027. this._currentRank = rank;
  13028. }
  13029. if (rank > this._maxRank) {
  13030. this._maxRank = rank;
  13031. }
  13032. this._defines[rank] = new Array();
  13033. }
  13034. this._defines[rank].push(define);
  13035. };
  13036. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  13037. get: function () {
  13038. return this._currentRank <= this._maxRank;
  13039. },
  13040. enumerable: true,
  13041. configurable: true
  13042. });
  13043. EffectFallbacks.prototype.reduce = function (currentDefines) {
  13044. var currentFallbacks = this._defines[this._currentRank];
  13045. for (var index = 0; index < currentFallbacks.length; index++) {
  13046. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  13047. }
  13048. this._currentRank++;
  13049. return currentDefines;
  13050. };
  13051. return EffectFallbacks;
  13052. })();
  13053. BABYLON.EffectFallbacks = EffectFallbacks;
  13054. var Effect = (function () {
  13055. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  13056. var _this = this;
  13057. this._isReady = false;
  13058. this._compilationError = "";
  13059. this._valueCache = [];
  13060. this._engine = engine;
  13061. this.name = baseName;
  13062. this.defines = defines;
  13063. this._uniformsNames = uniformsNames.concat(samplers);
  13064. this._samplers = samplers;
  13065. this._attributesNames = attributesNames;
  13066. this.onError = onError;
  13067. this.onCompiled = onCompiled;
  13068. var vertexSource;
  13069. var fragmentSource;
  13070. if (baseName.vertexElement) {
  13071. vertexSource = document.getElementById(baseName.vertexElement);
  13072. if (!vertexSource) {
  13073. vertexSource = baseName.vertexElement;
  13074. }
  13075. }
  13076. else {
  13077. vertexSource = baseName.vertex || baseName;
  13078. }
  13079. if (baseName.fragmentElement) {
  13080. fragmentSource = document.getElementById(baseName.fragmentElement);
  13081. if (!fragmentSource) {
  13082. fragmentSource = baseName.fragmentElement;
  13083. }
  13084. }
  13085. else {
  13086. fragmentSource = baseName.fragment || baseName;
  13087. }
  13088. this._loadVertexShader(vertexSource, function (vertexCode) {
  13089. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  13090. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  13091. });
  13092. });
  13093. }
  13094. // Properties
  13095. Effect.prototype.isReady = function () {
  13096. return this._isReady;
  13097. };
  13098. Effect.prototype.getProgram = function () {
  13099. return this._program;
  13100. };
  13101. Effect.prototype.getAttributesNames = function () {
  13102. return this._attributesNames;
  13103. };
  13104. Effect.prototype.getAttributeLocation = function (index) {
  13105. return this._attributes[index];
  13106. };
  13107. Effect.prototype.getAttributeLocationByName = function (name) {
  13108. var index = this._attributesNames.indexOf(name);
  13109. return this._attributes[index];
  13110. };
  13111. Effect.prototype.getAttributesCount = function () {
  13112. return this._attributes.length;
  13113. };
  13114. Effect.prototype.getUniformIndex = function (uniformName) {
  13115. return this._uniformsNames.indexOf(uniformName);
  13116. };
  13117. Effect.prototype.getUniform = function (uniformName) {
  13118. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  13119. };
  13120. Effect.prototype.getSamplers = function () {
  13121. return this._samplers;
  13122. };
  13123. Effect.prototype.getCompilationError = function () {
  13124. return this._compilationError;
  13125. };
  13126. // Methods
  13127. Effect.prototype._loadVertexShader = function (vertex, callback) {
  13128. // DOM element ?
  13129. if (vertex instanceof HTMLElement) {
  13130. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  13131. callback(vertexCode);
  13132. return;
  13133. }
  13134. // Is in local store ?
  13135. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  13136. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  13137. return;
  13138. }
  13139. var vertexShaderUrl;
  13140. if (vertex[0] === ".") {
  13141. vertexShaderUrl = vertex;
  13142. }
  13143. else {
  13144. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  13145. }
  13146. // Vertex shader
  13147. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  13148. };
  13149. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  13150. // DOM element ?
  13151. if (fragment instanceof HTMLElement) {
  13152. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  13153. callback(fragmentCode);
  13154. return;
  13155. }
  13156. // Is in local store ?
  13157. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  13158. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  13159. return;
  13160. }
  13161. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  13162. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  13163. return;
  13164. }
  13165. var fragmentShaderUrl;
  13166. if (fragment[0] === ".") {
  13167. fragmentShaderUrl = fragment;
  13168. }
  13169. else {
  13170. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  13171. }
  13172. // Fragment shader
  13173. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  13174. };
  13175. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  13176. try {
  13177. var engine = this._engine;
  13178. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  13179. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  13180. this._attributes = engine.getAttributes(this._program, attributesNames);
  13181. for (var index = 0; index < this._samplers.length; index++) {
  13182. var sampler = this.getUniform(this._samplers[index]);
  13183. if (sampler == null) {
  13184. this._samplers.splice(index, 1);
  13185. index--;
  13186. }
  13187. }
  13188. engine.bindSamplers(this);
  13189. this._isReady = true;
  13190. if (this.onCompiled) {
  13191. this.onCompiled(this);
  13192. }
  13193. }
  13194. catch (e) {
  13195. // Is it a problem with precision?
  13196. if (e.message.indexOf("highp") !== -1) {
  13197. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  13198. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  13199. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  13200. return;
  13201. }
  13202. // Let's go through fallbacks then
  13203. if (fallbacks && fallbacks.isMoreFallbacks) {
  13204. defines = fallbacks.reduce(defines);
  13205. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  13206. }
  13207. else {
  13208. BABYLON.Tools.Error("Unable to compile effect: " + this.name);
  13209. BABYLON.Tools.Error("Defines: " + defines);
  13210. BABYLON.Tools.Error("Error: " + e.message);
  13211. this._compilationError = e.message;
  13212. if (this.onError) {
  13213. this.onError(this, this._compilationError);
  13214. }
  13215. }
  13216. }
  13217. };
  13218. Effect.prototype._bindTexture = function (channel, texture) {
  13219. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  13220. };
  13221. Effect.prototype.setTexture = function (channel, texture) {
  13222. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  13223. };
  13224. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  13225. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  13226. };
  13227. //public _cacheMatrix(uniformName, matrix) {
  13228. // if (!this._valueCache[uniformName]) {
  13229. // this._valueCache[uniformName] = new BABYLON.Matrix();
  13230. // }
  13231. // for (var index = 0; index < 16; index++) {
  13232. // this._valueCache[uniformName].m[index] = matrix.m[index];
  13233. // }
  13234. //};
  13235. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  13236. if (!this._valueCache[uniformName]) {
  13237. this._valueCache[uniformName] = [x, y];
  13238. return;
  13239. }
  13240. this._valueCache[uniformName][0] = x;
  13241. this._valueCache[uniformName][1] = y;
  13242. };
  13243. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  13244. if (!this._valueCache[uniformName]) {
  13245. this._valueCache[uniformName] = [x, y, z];
  13246. return;
  13247. }
  13248. this._valueCache[uniformName][0] = x;
  13249. this._valueCache[uniformName][1] = y;
  13250. this._valueCache[uniformName][2] = z;
  13251. };
  13252. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  13253. if (!this._valueCache[uniformName]) {
  13254. this._valueCache[uniformName] = [x, y, z, w];
  13255. return;
  13256. }
  13257. this._valueCache[uniformName][0] = x;
  13258. this._valueCache[uniformName][1] = y;
  13259. this._valueCache[uniformName][2] = z;
  13260. this._valueCache[uniformName][3] = w;
  13261. };
  13262. Effect.prototype.setArray = function (uniformName, array) {
  13263. this._engine.setArray(this.getUniform(uniformName), array);
  13264. return this;
  13265. };
  13266. Effect.prototype.setArray2 = function (uniformName, array) {
  13267. this._engine.setArray2(this.getUniform(uniformName), array);
  13268. return this;
  13269. };
  13270. Effect.prototype.setArray3 = function (uniformName, array) {
  13271. this._engine.setArray3(this.getUniform(uniformName), array);
  13272. return this;
  13273. };
  13274. Effect.prototype.setArray4 = function (uniformName, array) {
  13275. this._engine.setArray4(this.getUniform(uniformName), array);
  13276. return this;
  13277. };
  13278. Effect.prototype.setMatrices = function (uniformName, matrices) {
  13279. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  13280. return this;
  13281. };
  13282. Effect.prototype.setMatrix = function (uniformName, matrix) {
  13283. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  13284. // return;
  13285. //this._cacheMatrix(uniformName, matrix);
  13286. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  13287. return this;
  13288. };
  13289. Effect.prototype.setFloat = function (uniformName, value) {
  13290. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  13291. return this;
  13292. this._valueCache[uniformName] = value;
  13293. this._engine.setFloat(this.getUniform(uniformName), value);
  13294. return this;
  13295. };
  13296. Effect.prototype.setBool = function (uniformName, bool) {
  13297. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  13298. return this;
  13299. this._valueCache[uniformName] = bool;
  13300. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  13301. return this;
  13302. };
  13303. Effect.prototype.setVector2 = function (uniformName, vector2) {
  13304. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  13305. return this;
  13306. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  13307. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  13308. return this;
  13309. };
  13310. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  13311. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  13312. return this;
  13313. this._cacheFloat2(uniformName, x, y);
  13314. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  13315. return this;
  13316. };
  13317. Effect.prototype.setVector3 = function (uniformName, vector3) {
  13318. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  13319. return this;
  13320. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  13321. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  13322. return this;
  13323. };
  13324. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  13325. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  13326. return this;
  13327. this._cacheFloat3(uniformName, x, y, z);
  13328. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  13329. return this;
  13330. };
  13331. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  13332. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  13333. return this;
  13334. this._cacheFloat4(uniformName, x, y, z, w);
  13335. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  13336. return this;
  13337. };
  13338. Effect.prototype.setColor3 = function (uniformName, color3) {
  13339. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  13340. return this;
  13341. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  13342. this._engine.setColor3(this.getUniform(uniformName), color3);
  13343. return this;
  13344. };
  13345. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  13346. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b && this._valueCache[uniformName][3] === alpha)
  13347. return this;
  13348. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  13349. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  13350. return this;
  13351. };
  13352. // Statics
  13353. Effect.ShadersStore={anaglyphPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\n\nvoid main(void)\n{\n vec4 leftFrag = texture2D(leftSampler, vUV);\n leftFrag = vec4(1.0, leftFrag.g, leftFrag.b, 1.0);\n\n vec4 rightFrag = texture2D(textureSampler, vUV);\n rightFrag = vec4(rightFrag.r, 1.0, 1.0, 1.0);\n\n gl_FragColor = vec4(rightFrag.rgb * leftFrag.rgb, 1.0);\n}",
  13354. blackAndWhitePixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nvoid main(void) \n{\n float luminance = dot(texture2D(textureSampler, vUV).rgb, vec3(0.3, 0.59, 0.11));\n gl_FragColor = vec4(luminance, luminance, luminance, 1.0);\n}",
  13355. blurPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\n// Parameters\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nvoid main(void)\n{\n float weights[7];\n weights[0] = 0.05;\n weights[1] = 0.1;\n weights[2] = 0.2;\n weights[3] = 0.3;\n weights[4] = 0.2;\n weights[5] = 0.1;\n weights[6] = 0.05;\n\n vec2 texelSize = vec2(1.0 / screenSize.x, 1.0 / screenSize.y);\n vec2 texelStep = texelSize * direction * blurWidth;\n vec2 start = vUV - 3.0 * texelStep;\n\n vec4 baseColor = vec4(0., 0., 0., 0.);\n vec2 texelOffset = vec2(0., 0.);\n\n for (int i = 0; i < 7; i++)\n {\n baseColor += texture2D(textureSampler, start + texelOffset) * weights[i];\n texelOffset += texelStep;\n }\n\n gl_FragColor = baseColor;\n}",
  13356. brickPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\n\nuniform float numberOfBricksHeight;\nuniform float numberOfBricksWidth;\nuniform vec3 brickColor;\nuniform vec3 jointColor;\n\nfloat rand(vec2 n) {\n return fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\n const vec2 d = vec2(0.0, 1.0);\n vec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\n return mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\n}\n\nfloat fbm(vec2 n) {\n float total = 0.0, amplitude = 1.0;\n for (int i = 0; i < 4; i++) {\n total += noise(n) * amplitude;\n n += n;\n amplitude *= 0.5;\n }\n return total;\n}\n\nfloat round(float number){\n return sign(number)*floor(abs(number) + 0.5);\n}\n\nvoid main(void)\n{\n float brickW = 1.0 / numberOfBricksWidth;\n float brickH = 1.0 / numberOfBricksHeight;\n float jointWPercentage = 0.01;\n float jointHPercentage = 0.05;\n vec3 color = brickColor;\n float yi = vUV.y / brickH;\n float nyi = round(yi);\n float xi = vUV.x / brickW;\n\n if (mod(floor(yi), 2.0) == 0.0){\n xi = xi - 0.5;\n }\n\n float nxi = round(xi);\n vec2 brickvUV = vec2((xi - floor(xi)) / brickH, (yi - floor(yi)) / brickW);\n\n if (yi < nyi + jointHPercentage && yi > nyi - jointHPercentage){\n color = mix(jointColor, vec3(0.37, 0.25, 0.25), (yi - nyi) / jointHPercentage + 0.2);\n }\n else if (xi < nxi + jointWPercentage && xi > nxi - jointWPercentage){\n color = mix(jointColor, vec3(0.44, 0.44, 0.44), (xi - nxi) / jointWPercentage + 0.2);\n }\n else {\n float brickColorSwitch = mod(floor(yi) + floor(xi), 3.0);\n\n if (brickColorSwitch == 0.0)\n color = mix(color, vec3(0.33, 0.33, 0.33), 0.3);\n else if (brickColorSwitch == 2.0)\n color = mix(color, vec3(0.11, 0.11, 0.11), 0.3);\n }\n\n gl_FragColor = vec4(color, 1.0);\n}",
  13357. cloudPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vUV;\n\nuniform vec3 skyColor;\nuniform vec3 cloudColor;\n\nfloat rand(vec2 n) {\n return fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\n const vec2 d = vec2(0.0, 1.0);\n vec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\n return mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\n}\n\nfloat fbm(vec2 n) {\n float total = 0.0, amplitude = 1.0;\n for (int i = 0; i < 4; i++) {\n total += noise(n) * amplitude;\n n += n;\n amplitude *= 0.5;\n }\n return total;\n}\n\nvoid main() {\n\n vec2 p = vUV * 12.0;\n vec3 c = mix(skyColor, cloudColor, fbm(p));\n gl_FragColor = vec4(c, 1);\n\n}",
  13358. colorPixelShader:"precision highp float;\n\nuniform vec4 color;\n\nvoid main(void) {\n gl_FragColor = color;\n}",
  13359. colorVertexShader:"precision highp float;\n\n// Attributes\nattribute vec3 position;\n\n// Uniforms\nuniform mat4 worldViewProjection;\n\nvoid main(void) {\n gl_Position = worldViewProjection * vec4(position, 1.0);\n}",
  13360. convolutionPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform float kernel[9];\n\nvoid main(void)\n{\n vec2 onePixel = vec2(1.0, 1.0) / screenSize;\n vec4 colorSum =\n texture2D(textureSampler, vUV + onePixel * vec2(-1, -1)) * kernel[0] +\n texture2D(textureSampler, vUV + onePixel * vec2(0, -1)) * kernel[1] +\n texture2D(textureSampler, vUV + onePixel * vec2(1, -1)) * kernel[2] +\n texture2D(textureSampler, vUV + onePixel * vec2(-1, 0)) * kernel[3] +\n texture2D(textureSampler, vUV + onePixel * vec2(0, 0)) * kernel[4] +\n texture2D(textureSampler, vUV + onePixel * vec2(1, 0)) * kernel[5] +\n texture2D(textureSampler, vUV + onePixel * vec2(-1, 1)) * kernel[6] +\n texture2D(textureSampler, vUV + onePixel * vec2(0, 1)) * kernel[7] +\n texture2D(textureSampler, vUV + onePixel * vec2(1, 1)) * kernel[8];\n\n float kernelWeight =\n kernel[0] +\n kernel[1] +\n kernel[2] +\n kernel[3] +\n kernel[4] +\n kernel[5] +\n kernel[6] +\n kernel[7] +\n kernel[8];\n\n if (kernelWeight <= 0.0) {\n kernelWeight = 1.0;\n }\n\n gl_FragColor = vec4((colorSum / kernelWeight).rgb, 1);\n}",
  13361. defaultPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#define MAP_EXPLICIT 0.\n#define MAP_SPHERICAL 1.\n#define MAP_PLANAR 2.\n#define MAP_CUBIC 3.\n#define MAP_PROJECTION 4.\n#define MAP_SKYBOX 5.\n\n// Constants\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vDiffuseColor;\nuniform vec4 vSpecularColor;\nuniform vec3 vEmissiveColor;\n\n// Input\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n// Lights\n#ifdef LIGHT0\nuniform vec4 vLightData0;\nuniform vec4 vLightDiffuse0;\nuniform vec3 vLightSpecular0;\n#ifdef SHADOW0\nvarying vec4 vPositionFromLight0;\nuniform sampler2D shadowSampler0;\nuniform float darkness0;\n#endif\n#ifdef SPOTLIGHT0\nuniform vec4 vLightDirection0;\n#endif\n#ifdef HEMILIGHT0\nuniform vec3 vLightGround0;\n#endif\n#endif\n\n#ifdef LIGHT1\nuniform vec4 vLightData1;\nuniform vec4 vLightDiffuse1;\nuniform vec3 vLightSpecular1;\n#ifdef SHADOW1\nvarying vec4 vPositionFromLight1;\nuniform sampler2D shadowSampler1;\nuniform float darkness1;\n#endif\n#ifdef SPOTLIGHT1\nuniform vec4 vLightDirection1;\n#endif\n#ifdef HEMILIGHT1\nuniform vec3 vLightGround1;\n#endif\n#endif\n\n#ifdef LIGHT2\nuniform vec4 vLightData2;\nuniform vec4 vLightDiffuse2;\nuniform vec3 vLightSpecular2;\n#ifdef SHADOW2\nvarying vec4 vPositionFromLight2;\nuniform sampler2D shadowSampler2;\nuniform float darkness2;\n#endif\n#ifdef SPOTLIGHT2\nuniform vec4 vLightDirection2;\n#endif\n#ifdef HEMILIGHT2\nuniform vec3 vLightGround2;\n#endif\n#endif\n\n#ifdef LIGHT3\nuniform vec4 vLightData3;\nuniform vec4 vLightDiffuse3;\nuniform vec3 vLightSpecular3;\n#ifdef SHADOW3\nvarying vec4 vPositionFromLight3;\nuniform sampler2D shadowSampler3;\nuniform float darkness3;\n#endif\n#ifdef SPOTLIGHT3\nuniform vec4 vLightDirection3;\n#endif\n#ifdef HEMILIGHT3\nuniform vec3 vLightGround3;\n#endif\n#endif\n\n// Samplers\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n\n#ifdef SPECULAR\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform sampler2D specularSampler;\n#endif\n\n// Fresnel\n#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\n{\n float fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\n return clamp(fresnelTerm, 0., 1.);\n}\n#endif\n\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n// Reflection\n#ifdef REFLECTION\nvarying vec3 vPositionUVW;\nuniform samplerCube reflectionCubeSampler;\nuniform sampler2D reflection2DSampler;\nuniform vec3 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform mat4 view;\n\nvec3 computeReflectionCoords(float mode, vec4 worldPos, vec3 worldNormal)\n{\n if (mode == MAP_SPHERICAL)\n {\n vec3 coords = vec3(view * vec4(worldNormal, 0.0));\n\n return vec3(reflectionMatrix * vec4(coords, 1.0));\n }\n else if (mode == MAP_PLANAR)\n {\n vec3 viewDir = worldPos.xyz - vEyePosition;\n vec3 coords = normalize(reflect(viewDir, worldNormal));\n\n return vec3(reflectionMatrix * vec4(coords, 1));\n }\n else if (mode == MAP_CUBIC)\n {\n vec3 viewDir = worldPos.xyz - vEyePosition;\n vec3 coords = reflect(viewDir, worldNormal);\n\n return vec3(reflectionMatrix * vec4(coords, 0));\n }\n else if (mode == MAP_PROJECTION)\n {\n return vec3(reflectionMatrix * (view * worldPos));\n }\n else if (mode == MAP_SKYBOX)\n {\n return vPositionUVW;\n }\n\n return vec3(0, 0, 0);\n}\n#endif\n\n// Shadows\n#ifdef SHADOWS\n\nfloat unpack(vec4 color)\n{\n const vec4 bitShift = vec4(1. / (255. * 255. * 255.), 1. / (255. * 255.), 1. / 255., 1.);\n return dot(color, bitShift);\n}\n\nfloat unpackHalf(vec2 color)\n{\n return color.x + (color.y / 255.0);\n}\n\nfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler, float darkness)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n vec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n float shadow = unpack(texture2D(shadowSampler, uv));\n\n if (depth.z > shadow)\n {\n return darkness;\n }\n return 1.;\n}\n\nfloat computeShadowWithPCF(vec4 vPositionFromLight, sampler2D shadowSampler)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n vec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n float visibility = 1.;\n\n vec2 poissonDisk[4];\n poissonDisk[0] = vec2(-0.94201624, -0.39906216);\n poissonDisk[1] = vec2(0.94558609, -0.76890725);\n poissonDisk[2] = vec2(-0.094184101, -0.92938870);\n poissonDisk[3] = vec2(0.34495938, 0.29387760);\n\n // Poisson Sampling\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[0] / 1500.0)) < depth.z) visibility -= 0.2;\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[1] / 1500.0)) < depth.z) visibility -= 0.2;\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[2] / 1500.0)) < depth.z) visibility -= 0.2;\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[3] / 1500.0)) < depth.z) visibility -= 0.2;\n\n return visibility;\n}\n\n// Thanks to http://devmaster.net/\nfloat ChebychevInequality(vec2 moments, float t)\n{\n if (t <= moments.x)\n {\n return 1.0;\n }\n\n float variance = moments.y - (moments.x * moments.x);\n variance = max(variance, 0.);\n\n float d = t - moments.x;\n return variance / (variance + d * d);\n}\n\nfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n vec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n vec4 texel = texture2D(shadowSampler, uv);\n\n vec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\n return clamp(1.0 - ChebychevInequality(moments, depth.z), 0., 1.0);\n}\n#endif\n\n// Bump\n#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\nvarying vec2 vBumpUV;\nuniform vec2 vBumpInfos;\nuniform sampler2D bumpSampler;\n\n// Thanks to http://www.thetenthplanet.de/archives/1180\nmat3 cotangent_frame(vec3 normal, vec3 p, vec2 uv)\n{\n // get edge vectors of the pixel triangle\n vec3 dp1 = dFdx(p);\n vec3 dp2 = dFdy(p);\n vec2 duv1 = dFdx(uv);\n vec2 duv2 = dFdy(uv);\n\n // solve the linear system\n vec3 dp2perp = cross(dp2, normal);\n vec3 dp1perp = cross(normal, dp1);\n vec3 tangent = dp2perp * duv1.x + dp1perp * duv2.x;\n vec3 binormal = dp2perp * duv1.y + dp1perp * duv2.y;\n\n // construct a scale-invariant frame \n float invmax = inversesqrt(max(dot(tangent, tangent), dot(binormal, binormal)));\n return mat3(tangent * invmax, binormal * invmax, normal);\n}\n\nvec3 perturbNormal(vec3 viewDir)\n{\n vec3 map = texture2D(bumpSampler, vBumpUV).xyz;\n map = map * 255. / 127. - 128. / 127.;\n mat3 TBN = cotangent_frame(vNormalW * vBumpInfos.y, -viewDir, vBumpUV);\n return normalize(TBN * map);\n}\n#endif\n\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\n\n// Fog\n#ifdef FOG\n\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\n\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying float fFogDistance;\n\nfloat CalcFogFactor()\n{\n float fogCoeff = 1.0;\n float fogStart = vFogInfos.y;\n float fogEnd = vFogInfos.z;\n float fogDensity = vFogInfos.w;\n\n if (FOGMODE_LINEAR == vFogInfos.x)\n {\n fogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\n }\n else if (FOGMODE_EXP == vFogInfos.x)\n {\n fogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\n }\n else if (FOGMODE_EXP2 == vFogInfos.x)\n {\n fogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\n }\n\n return clamp(fogCoeff, 0.0, 1.0);\n}\n#endif\n\n// Light Computing\nstruct lightingInfo\n{\n vec3 diffuse;\n vec3 specular;\n};\n\nlightingInfo computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, float range) {\n lightingInfo result;\n\n vec3 lightVectorW;\n float attenuation = 1.0;\n if (lightData.w == 0.)\n {\n vec3 direction = lightData.xyz - vPositionW;\n\n attenuation = max(0., 1.0 - length(direction) / range);\n lightVectorW = normalize(direction);\n }\n else\n {\n lightVectorW = normalize(-lightData.xyz);\n }\n\n // diffuse\n float ndl = max(0., dot(vNormal, lightVectorW));\n\n // Specular\n vec3 angleW = normalize(viewDirectionW + lightVectorW);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, max(1., vSpecularColor.a));\n\n result.diffuse = ndl * diffuseColor * attenuation;\n result.specular = specComp * specularColor * attenuation;\n\n return result;\n}\n\nlightingInfo computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec3 diffuseColor, vec3 specularColor, float range) {\n lightingInfo result;\n\n vec3 direction = lightData.xyz - vPositionW;\n vec3 lightVectorW = normalize(direction);\n float attenuation = max(0., 1.0 - length(direction) / range);\n\n // diffuse\n float cosAngle = max(0., dot(-lightDirection.xyz, lightVectorW));\n float spotAtten = 0.0;\n\n if (cosAngle >= lightDirection.w)\n {\n cosAngle = max(0., pow(cosAngle, lightData.w));\n spotAtten = max(0., (cosAngle - lightDirection.w) / (1. - cosAngle));\n\n // Diffuse\n float ndl = max(0., dot(vNormal, -lightDirection.xyz));\n\n // Specular\n vec3 angleW = normalize(viewDirectionW - lightDirection.xyz);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, vSpecularColor.a);\n\n result.diffuse = ndl * spotAtten * diffuseColor * attenuation;\n result.specular = specComp * specularColor * spotAtten * attenuation;\n\n return result;\n }\n\n result.diffuse = vec3(0.);\n result.specular = vec3(0.);\n\n return result;\n}\n\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, vec3 groundColor) {\n lightingInfo result;\n\n // Diffuse\n float ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\n\n // Specular\n vec3 angleW = normalize(viewDirectionW + lightData.xyz);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, vSpecularColor.a);\n\n result.diffuse = mix(groundColor, diffuseColor, ndl);\n result.specular = specComp * specularColor;\n\n return result;\n}\n\nvoid main(void) {\n // Clip plane\n#ifdef CLIPPLANE\n if (fClipDistance > 0.0)\n discard;\n#endif\n\n vec3 viewDirectionW = normalize(vEyePosition - vPositionW);\n\n // Base color\n vec4 baseColor = vec4(1., 1., 1., 1.);\n vec3 diffuseColor = vDiffuseColor.rgb;\n\n // Alpha\n float alpha = vDiffuseColor.a;\n\n#ifdef VERTEXCOLOR\n baseColor.rgb *= vColor.rgb;\n#endif\n\n#ifdef DIFFUSE\n baseColor = texture2D(diffuseSampler, vDiffuseUV);\n\n#ifdef ALPHATEST\n if (baseColor.a < 0.4)\n discard;\n#endif\n\n#ifdef ALPHAFROMDIFFUSE\n alpha *= baseColor.a;\n#endif\n\n baseColor.rgb *= vDiffuseInfos.y;\n#endif\n\n // Bump\n vec3 normalW = normalize(vNormalW);\n\n#ifdef BUMP\n normalW = perturbNormal(viewDirectionW);\n#endif\n\n // Ambient color\n vec3 baseAmbientColor = vec3(1., 1., 1.);\n\n#ifdef AMBIENT\n baseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\n#endif\n\n // Lighting\n vec3 diffuseBase = vec3(0., 0., 0.);\n vec3 specularBase = vec3(0., 0., 0.);\n float shadow = 1.;\n\n#ifdef LIGHT0\n#ifdef SPOTLIGHT0\n lightingInfo info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a);\n#endif\n#ifdef HEMILIGHT0\n lightingInfo info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightGround0);\n#endif\n#ifdef POINTDIRLIGHT0\n lightingInfo info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a);\n#endif\n#ifdef SHADOW0\n#ifdef SHADOWVSM0\n shadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0);\n#else\n #ifdef SHADOWPCF0\n shadow = computeShadowWithPCF(vPositionFromLight0, shadowSampler0);\n #else\n shadow = computeShadow(vPositionFromLight0, shadowSampler0, darkness0);\n #endif\n#endif\n#else\n shadow = 1.;\n#endif\n diffuseBase += info.diffuse * shadow;\n specularBase += info.specular * shadow;\n#endif\n\n#ifdef LIGHT1\n#ifdef SPOTLIGHT1\n info = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a);\n#endif\n#ifdef HEMILIGHT1\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightGround1);\n#endif\n#ifdef POINTDIRLIGHT1\n info = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a);\n#endif\n#ifdef SHADOW1\n#ifdef SHADOWVSM1\n shadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1);\n#else\n #ifdef SHADOWPCF1\n shadow = computeShadowWithPCF(vPositionFromLight1, shadowSampler1);\n #else\n shadow = computeShadow(vPositionFromLight1, shadowSampler1, darkness1);\n #endif\n#endif\n#else\n shadow = 1.;\n#endif\n diffuseBase += info.diffuse * shadow;\n specularBase += info.specular * shadow;\n#endif\n\n#ifdef LIGHT2\n#ifdef SPOTLIGHT2\n info = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a);\n#endif\n#ifdef HEMILIGHT2\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightGround2);\n#endif\n#ifdef POINTDIRLIGHT2\n info = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a);\n#endif\n#ifdef SHADOW2\n#ifdef SHADOWVSM2\n shadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2);\n#else\n #ifdef SHADOWPCF2\n shadow = computeShadowWithPCF(vPositionFromLight2, shadowSampler2);\n #else\n shadow = computeShadow(vPositionFromLight2, shadowSampler2, darkness2);\n #endif \n#endif \n#else\n shadow = 1.;\n#endif\n diffuseBase += info.diffuse * shadow;\n specularBase += info.specular * shadow;\n#endif\n\n#ifdef LIGHT3\n#ifdef SPOTLIGHT3\n info = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a);\n#endif\n#ifdef HEMILIGHT3\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightGround3);\n#endif\n#ifdef POINTDIRLIGHT3\n info = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a);\n#endif\n#ifdef SHADOW3\n#ifdef SHADOWVSM3\n shadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3);\n#else\n #ifdef SHADOWPCF3\n shadow = computeShadowWithPCF(vPositionFromLight3, shadowSampler3);\n #else\n shadow = computeShadow(vPositionFromLight3, shadowSampler3, darkness3);\n #endif \n#endif \n#else\n shadow = 1.;\n#endif\n diffuseBase += info.diffuse * shadow;\n specularBase += info.specular * shadow;\n#endif\n\n // Reflection\n vec3 reflectionColor = vec3(0., 0., 0.);\n\n#ifdef REFLECTION\n vec3 vReflectionUVW = computeReflectionCoords(vReflectionInfos.x, vec4(vPositionW, 1.0), normalW);\n\n if (vReflectionInfos.z != 0.0)\n {\n reflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).rgb * vReflectionInfos.y * shadow;\n }\n else\n {\n vec2 coords = vReflectionUVW.xy;\n\n if (vReflectionInfos.x == MAP_PROJECTION)\n {\n coords /= vReflectionUVW.z;\n }\n\n coords.y = 1.0 - coords.y;\n\n reflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.y * shadow;\n }\n\n#ifdef REFLECTIONFRESNEL\n float reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\n\n reflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\n#endif\n#endif\n\n#ifdef OPACITY\n vec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\n\n#ifdef OPACITYRGB\n opacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\n alpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\n#else\n alpha *= opacityMap.a * vOpacityInfos.y;\n#endif\n\n#endif\n\n#ifdef VERTEXALPHA\n alpha *= vColor.a;\n#endif\n\n#ifdef OPACITYFRESNEL\n float opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\n\n alpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\n#endif\n\n // Emissive\n vec3 emissiveColor = vEmissiveColor;\n#ifdef EMISSIVE\n emissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\n#endif\n\n#ifdef EMISSIVEFRESNEL\n float emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\n\n emissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\n#endif\n\n // Specular map\n vec3 specularColor = vSpecularColor.rgb;\n#ifdef SPECULAR\n specularColor = texture2D(specularSampler, vSpecularUV).rgb * vSpecularInfos.y;\n#endif\n\n // Fresnel\n#ifdef DIFFUSEFRESNEL\n float diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\n\n diffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\n#endif\n\n // Composition\n vec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\n vec3 finalSpecular = specularBase * specularColor;\n\n#ifdef SPECULAROVERALPHA\n alpha = clamp(alpha + dot(finalSpecular, vec3(0.3, 0.59, 0.11)), 0., 1.);\n#endif\n\n vec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor, alpha);\n\n#ifdef FOG\n float fog = CalcFogFactor();\n color.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\n#endif\n\n gl_FragColor = color;\n}",
  13362. defaultVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attributes\nattribute vec3 position;\nattribute vec3 normal;\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#ifdef BONES\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#endif\n\n// Uniforms\n\n#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif\n\nuniform mat4 view;\nuniform mat4 viewProjection;\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n\n#ifdef SPECULAR\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec2 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n\n#ifdef BONES\nuniform mat4 mBones[BonesPerMesh];\n#endif\n\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n// Output\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif\n\n#ifdef FOG\nvarying float fFogDistance;\n#endif\n\n#ifdef SHADOWS\n#ifdef LIGHT0\nuniform mat4 lightMatrix0;\nvarying vec4 vPositionFromLight0;\n#endif\n#ifdef LIGHT1\nuniform mat4 lightMatrix1;\nvarying vec4 vPositionFromLight1;\n#endif\n#ifdef LIGHT2\nuniform mat4 lightMatrix2;\nvarying vec4 vPositionFromLight2;\n#endif\n#ifdef LIGHT3\nuniform mat4 lightMatrix3;\nvarying vec4 vPositionFromLight3;\n#endif\n#endif\n\n#ifdef REFLECTION\nvarying vec3 vPositionUVW;\n#endif\n\nvoid main(void) {\n mat4 finalWorld;\n\n#ifdef REFLECTION\n vPositionUVW = position;\n#endif \n\n#ifdef INSTANCES\n finalWorld = mat4(world0, world1, world2, world3);\n#else\n finalWorld = world;\n#endif\n\n#ifdef BONES\n mat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\n mat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\n mat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\n\n#ifdef BONES4\n mat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\n finalWorld = finalWorld * (m0 + m1 + m2 + m3);\n#else\n finalWorld = finalWorld * (m0 + m1 + m2);\n#endif \n\n#endif\n gl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n\n vec4 worldPos = finalWorld * vec4(position, 1.0);\n vPositionW = vec3(worldPos);\n vNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\n\n // Texture coordinates\n#ifndef UV1\n vec2 uv = vec2(0., 0.);\n#endif\n#ifndef UV2\n vec2 uv2 = vec2(0., 0.);\n#endif\n\n#ifdef DIFFUSE\n if (vDiffuseInfos.x == 0.)\n {\n vDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef AMBIENT\n if (vAmbientInfos.x == 0.)\n {\n vAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef OPACITY\n if (vOpacityInfos.x == 0.)\n {\n vOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef EMISSIVE\n if (vEmissiveInfos.x == 0.)\n {\n vEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef SPECULAR\n if (vSpecularInfos.x == 0.)\n {\n vSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef BUMP\n if (vBumpInfos.x == 0.)\n {\n vBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n // Clip plane\n#ifdef CLIPPLANE\n fClipDistance = dot(worldPos, vClipPlane);\n#endif\n\n // Fog\n#ifdef FOG\n fFogDistance = (view * worldPos).z;\n#endif\n\n // Shadows\n#ifdef SHADOWS\n#ifdef LIGHT0\n vPositionFromLight0 = lightMatrix0 * worldPos;\n#endif\n#ifdef LIGHT1\n vPositionFromLight1 = lightMatrix1 * worldPos;\n#endif\n#ifdef LIGHT2\n vPositionFromLight2 = lightMatrix2 * worldPos;\n#endif\n#ifdef LIGHT3\n vPositionFromLight3 = lightMatrix3 * worldPos;\n#endif\n#endif\n\n // Vertex color\n#ifdef VERTEXCOLOR\n vColor = color;\n#endif\n\n // Point size\n#ifdef POINTSIZE\n gl_PointSize = pointSize;\n#endif\n}",
  13363. depthPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n\nuniform float far;\n\nvoid main(void)\n{\n#ifdef ALPHATEST\n if (texture2D(diffuseSampler, vUV).a < 0.4)\n discard;\n#endif\n\n float depth = (gl_FragCoord.z / gl_FragCoord.w) / far;\n gl_FragColor = vec4(depth, depth * depth, 0.0, 1.0);\n}",
  13364. depthVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attribute\nattribute vec3 position;\n#ifdef BONES\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#endif\n\n// Uniform\n#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif\n\nuniform mat4 viewProjection;\n#ifdef BONES\nuniform mat4 mBones[BonesPerMesh];\n#endif\n\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n\nvoid main(void)\n{\n#ifdef INSTANCES\n mat4 finalWorld = mat4(world0, world1, world2, world3);\n#else\n mat4 finalWorld = world;\n#endif\n\n#ifdef BONES\n mat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\n mat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\n mat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\n mat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\n finalWorld = finalWorld * (m0 + m1 + m2 + m3);\n gl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n#else\n gl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n#endif\n\n#ifdef ALPHATEST\n#ifdef UV1\n vUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\n#endif\n#ifdef UV2\n vUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\n#endif\n#endif\n}",
  13365. displayPassPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\n\nvoid main(void)\n{\n gl_FragColor = texture2D(passSampler, vUV);\n}",
  13366. filterPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform mat4 kernelMatrix;\n\nvoid main(void)\n{\n vec3 baseColor = texture2D(textureSampler, vUV).rgb;\n vec3 updatedColor = (kernelMatrix * vec4(baseColor, 1.0)).rgb;\n\n gl_FragColor = vec4(updatedColor, 1.0);\n}",
  13367. firePixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nuniform float time;\nuniform vec3 c1;\nuniform vec3 c2;\nuniform vec3 c3;\nuniform vec3 c4;\nuniform vec3 c5;\nuniform vec3 c6;\nuniform vec2 speed;\nuniform float shift;\nuniform float alphaThreshold;\n\nvarying vec2 vUV;\n\nfloat rand(vec2 n) {\n return fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\n const vec2 d = vec2(0.0, 1.0);\n vec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\n return mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\n}\n\nfloat fbm(vec2 n) {\n float total = 0.0, amplitude = 1.0;\n for (int i = 0; i < 4; i++) {\n total += noise(n) * amplitude;\n n += n;\n amplitude *= 0.5;\n }\n return total;\n}\n\nvoid main() {\n vec2 p = vUV * 8.0;\n float q = fbm(p - time * 0.1);\n vec2 r = vec2(fbm(p + q + time * speed.x - p.x - p.y), fbm(p + q - time * speed.y));\n vec3 c = mix(c1, c2, fbm(p + r)) + mix(c3, c4, r.x) - mix(c5, c6, r.y);\n vec3 color = c * cos(shift * vUV.y);\n float luminance = dot(color.rgb, vec3(0.3, 0.59, 0.11));\n\n gl_FragColor = vec4(color, luminance * alphaThreshold + (1.0 - alphaThreshold));\n}",
  13368. fxaaPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#define FXAA_REDUCE_MIN (1.0/128.0)\n#define FXAA_REDUCE_MUL (1.0/8.0)\n#define FXAA_SPAN_MAX 8.0\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 texelSize;\n\nvoid main(){\n vec2 localTexelSize = texelSize;\n vec4 rgbNW = texture2D(textureSampler, (vUV + vec2(-1.0, -1.0) * localTexelSize));\n vec4 rgbNE = texture2D(textureSampler, (vUV + vec2(1.0, -1.0) * localTexelSize));\n vec4 rgbSW = texture2D(textureSampler, (vUV + vec2(-1.0, 1.0) * localTexelSize));\n vec4 rgbSE = texture2D(textureSampler, (vUV + vec2(1.0, 1.0) * localTexelSize));\n vec4 rgbM = texture2D(textureSampler, vUV);\n vec4 luma = vec4(0.299, 0.587, 0.114, 1.0);\n float lumaNW = dot(rgbNW, luma);\n float lumaNE = dot(rgbNE, luma);\n float lumaSW = dot(rgbSW, luma);\n float lumaSE = dot(rgbSE, luma);\n float lumaM = dot(rgbM, luma);\n float lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE)));\n float lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE)));\n\n vec2 dir = vec2(-((lumaNW + lumaNE) - (lumaSW + lumaSE)), ((lumaNW + lumaSW) - (lumaNE + lumaSE)));\n\n float dirReduce = max(\n (lumaNW + lumaNE + lumaSW + lumaSE) * (0.25 * FXAA_REDUCE_MUL),\n FXAA_REDUCE_MIN);\n\n float rcpDirMin = 1.0 / (min(abs(dir.x), abs(dir.y)) + dirReduce);\n dir = min(vec2(FXAA_SPAN_MAX, FXAA_SPAN_MAX),\n max(vec2(-FXAA_SPAN_MAX, -FXAA_SPAN_MAX),\n dir * rcpDirMin)) * localTexelSize;\n\n vec4 rgbA = 0.5 * (\n texture2D(textureSampler, vUV + dir * (1.0 / 3.0 - 0.5)) +\n texture2D(textureSampler, vUV + dir * (2.0 / 3.0 - 0.5)));\n\n vec4 rgbB = rgbA * 0.5 + 0.25 * (\n texture2D(textureSampler, vUV + dir * -0.5) +\n texture2D(textureSampler, vUV + dir * 0.5));\n float lumaB = dot(rgbB, luma);\n if ((lumaB < lumaMin) || (lumaB > lumaMax)) {\n gl_FragColor = rgbA;\n }\n else {\n gl_FragColor = rgbB;\n }\n}",
  13369. grassPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\n\nuniform vec3 herb1Color;\nuniform vec3 herb2Color;\nuniform vec3 herb3Color;\nuniform vec3 groundColor;\n\nfloat rand(vec2 n) {\n return fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\n const vec2 d = vec2(0.0, 1.0);\n vec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\n return mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\n}\n\nfloat fbm(vec2 n) {\n float total = 0.0, amplitude = 1.0;\n for (int i = 0; i < 4; i++) {\n total += noise(n) * amplitude;\n n += n;\n amplitude *= 0.5;\n }\n return total;\n}\n\nvoid main(void) {\n vec3 color = mix(groundColor, herb1Color, rand(gl_FragCoord.xy * 4.0));\n color = mix(color, herb2Color, rand(gl_FragCoord.xy * 8.0));\n color = mix(color, herb3Color, rand(gl_FragCoord.xy));\n color = mix(color, herb1Color, fbm(gl_FragCoord.xy * 16.0));\n gl_FragColor = vec4(color, 1.0);\n}",
  13370. layerPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\n// Color\nuniform vec4 color;\n\nvoid main(void) {\n vec4 baseColor = texture2D(textureSampler, vUV);\n\n gl_FragColor = baseColor * color;\n}",
  13371. layerVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attributes\nattribute vec2 position;\n\n// Uniforms\nuniform mat4 textureMatrix;\n\n// Output\nvarying vec2 vUV;\n\nconst vec2 madd = vec2(0.5, 0.5);\n\nvoid main(void) { \n\n vUV = vec2(textureMatrix * vec4(position * madd + madd, 1.0, 0.0));\n gl_Position = vec4(position, 0.0, 1.0);\n}",
  13372. legacydefaultPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#define MAP_PROJECTION 4.\n\n// Constants\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vDiffuseColor;\nuniform vec4 vSpecularColor;\nuniform vec3 vEmissiveColor;\n\n// Input\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n// Lights\n#ifdef LIGHT0\nuniform vec4 vLightData0;\nuniform vec4 vLightDiffuse0;\nuniform vec3 vLightSpecular0;\n#ifdef SHADOW0\nvarying vec4 vPositionFromLight0;\nuniform sampler2D shadowSampler0;\n#endif\n#ifdef SPOTLIGHT0\nuniform vec4 vLightDirection0;\n#endif\n#ifdef HEMILIGHT0\nuniform vec3 vLightGround0;\n#endif\n#endif\n\n#ifdef LIGHT1\nuniform vec4 vLightData1;\nuniform vec4 vLightDiffuse1;\nuniform vec3 vLightSpecular1;\n#ifdef SHADOW1\nvarying vec4 vPositionFromLight1;\nuniform sampler2D shadowSampler1;\n#endif\n#ifdef SPOTLIGHT1\nuniform vec4 vLightDirection1;\n#endif\n#ifdef HEMILIGHT1\nuniform vec3 vLightGround1;\n#endif\n#endif\n\n#ifdef LIGHT2\nuniform vec4 vLightData2;\nuniform vec4 vLightDiffuse2;\nuniform vec3 vLightSpecular2;\n#ifdef SHADOW2\nvarying vec4 vPositionFromLight2;\nuniform sampler2D shadowSampler2;\n#endif\n#ifdef SPOTLIGHT2\nuniform vec4 vLightDirection2;\n#endif\n#ifdef HEMILIGHT2\nuniform vec3 vLightGround2;\n#endif\n#endif\n\n#ifdef LIGHT3\nuniform vec4 vLightData3;\nuniform vec4 vLightDiffuse3;\nuniform vec3 vLightSpecular3;\n#ifdef SHADOW3\nvarying vec4 vPositionFromLight3;\nuniform sampler2D shadowSampler3;\n#endif\n#ifdef SPOTLIGHT3\nuniform vec4 vLightDirection3;\n#endif\n#ifdef HEMILIGHT3\nuniform vec3 vLightGround3;\n#endif\n#endif\n\n// Samplers\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n\n#ifdef REFLECTION\nvarying vec3 vReflectionUVW;\nuniform samplerCube reflectionCubeSampler;\nuniform sampler2D reflection2DSampler;\nuniform vec3 vReflectionInfos;\n#endif\n\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n\n#ifdef SPECULAR\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform sampler2D specularSampler;\n#endif\n\n// Fresnel\n#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\n{\n float fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\n return clamp(fresnelTerm, 0., 1.);\n}\n#endif\n\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n// Shadows\n#ifdef SHADOWS\n\nfloat unpack(vec4 color)\n{\n const vec4 bitShift = vec4(1. / (255. * 255. * 255.), 1. / (255. * 255.), 1. / 255., 1.);\n return dot(color, bitShift);\n}\n\nfloat unpackHalf(vec2 color)\n{\n return color.x + (color.y / 255.0);\n}\n\nfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n vec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n float shadow = unpack(texture2D(shadowSampler, uv));\n\n if (depth.z > shadow)\n {\n return 0.;\n }\n return 1.;\n}\n\n// Thanks to http://devmaster.net/\nfloat ChebychevInequality(vec2 moments, float t)\n{\n if (t <= moments.x)\n {\n return 1.0;\n }\n\n float variance = moments.y - (moments.x * moments.x);\n variance = max(variance, 0.);\n\n float d = t - moments.x;\n return variance / (variance + d * d);\n}\n\nfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n vec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n vec4 texel = texture2D(shadowSampler, uv);\n\n vec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\n return clamp(1.3 - ChebychevInequality(moments, depth.z), 0., 1.0);\n}\n#endif\n\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\n\n// Fog\n#ifdef FOG\n\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\n\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying float fFogDistance;\n\nfloat CalcFogFactor()\n{\n float fogCoeff = 1.0;\n float fogStart = vFogInfos.y;\n float fogEnd = vFogInfos.z;\n float fogDensity = vFogInfos.w;\n\n if (FOGMODE_LINEAR == vFogInfos.x)\n {\n fogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\n }\n else if (FOGMODE_EXP == vFogInfos.x)\n {\n fogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\n }\n else if (FOGMODE_EXP2 == vFogInfos.x)\n {\n fogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\n }\n\n return clamp(fogCoeff, 0.0, 1.0);\n}\n#endif\n\n// Light Computing\nmat3 computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 diffuseColor, vec3 specularColor) {\n mat3 result;\n\n vec3 lightVectorW;\n if (lightData.w == 0.)\n {\n lightVectorW = normalize(lightData.xyz - vPositionW);\n }\n else\n {\n lightVectorW = normalize(-lightData.xyz);\n }\n\n // diffuse\n float ndl = max(0., dot(vNormal, lightVectorW));\n\n // Specular\n vec3 angleW = normalize(viewDirectionW + lightVectorW);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = max(0., pow(specComp, max(1.0, vSpecularColor.a)));\n\n result[0] = ndl * diffuseColor.rgb;\n result[1] = specComp * specularColor;\n result[2] = vec3(0.);\n\n return result;\n}\n\nmat3 computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec4 diffuseColor, vec3 specularColor) {\n mat3 result;\n\n vec3 lightVectorW = normalize(lightData.xyz - vPositionW);\n\n // diffuse\n float cosAngle = max(0., dot(-lightDirection.xyz, lightVectorW));\n float spotAtten = 0.0;\n\n if (cosAngle >= lightDirection.w)\n {\n cosAngle = max(0., pow(cosAngle, lightData.w));\n spotAtten = max(0., (cosAngle - lightDirection.w) / (1. - cosAngle));\n\n // Diffuse\n float ndl = max(0., dot(vNormal, -lightDirection.xyz));\n\n // Specular\n vec3 angleW = normalize(viewDirectionW - lightDirection.xyz);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, vSpecularColor.a);\n\n result[0] = ndl * spotAtten * diffuseColor.rgb;\n result[1] = specComp * specularColor * spotAtten;\n result[2] = vec3(0.);\n\n return result;\n }\n\n result[0] = vec3(0.);\n result[1] = vec3(0.);\n result[2] = vec3(0.);\n\n return result;\n}\n\nmat3 computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 diffuseColor, vec3 specularColor, vec3 groundColor) {\n mat3 result;\n\n // Diffuse\n float ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\n\n // Specular\n vec3 angleW = normalize(viewDirectionW + lightData.xyz);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, vSpecularColor.a);\n\n result[0] = mix(groundColor, diffuseColor.rgb, ndl);\n result[1] = specComp * specularColor;\n result[2] = vec3(0.);\n\n return result;\n}\n\nvoid main(void) {\n // Clip plane\n#ifdef CLIPPLANE\n if (fClipDistance > 0.0)\n discard;\n#endif\n\n vec3 viewDirectionW = normalize(vEyePosition - vPositionW);\n\n // Base color\n vec4 baseColor = vec4(1., 1., 1., 1.);\n vec3 diffuseColor = vDiffuseColor.rgb;\n\n#ifdef VERTEXCOLOR\n baseColor.rgb *= vColor.rgb;\n#endif\n\n#ifdef DIFFUSE\n baseColor = texture2D(diffuseSampler, vDiffuseUV);\n\n#ifdef ALPHATEST\n if (baseColor.a < 0.4)\n discard;\n#endif\n\n baseColor.rgb *= vDiffuseInfos.y;\n#endif\n\n // Bump\n vec3 normalW = normalize(vNormalW);\n\n // Ambient color\n vec3 baseAmbientColor = vec3(1., 1., 1.);\n\n#ifdef AMBIENT\n baseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\n#endif\n\n // Lighting\n vec3 diffuseBase = vec3(0., 0., 0.);\n vec3 specularBase = vec3(0., 0., 0.);\n float shadow = 1.;\n\n#ifdef LIGHT0\n#ifdef SPOTLIGHT0\n mat3 info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0, vLightSpecular0);\n#endif\n#ifdef HEMILIGHT0\n mat3 info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0, vLightSpecular0, vLightGround0);\n#endif\n#ifdef POINTDIRLIGHT0\n mat3 info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0, vLightSpecular0);\n#endif\n#ifdef SHADOW0\n#ifdef SHADOWVSM0\n shadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0);\n#else\n shadow = computeShadow(vPositionFromLight0, shadowSampler0);\n#endif\n#else\n shadow = 1.;\n#endif\n diffuseBase += info[0] * shadow;\n specularBase += info[1] * shadow;\n#endif\n\n#ifdef LIGHT1\n#ifdef SPOTLIGHT1\n info = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1, vLightSpecular1);\n#endif\n#ifdef HEMILIGHT1\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1, vLightSpecular1, vLightGround1);\n#endif\n#ifdef POINTDIRLIGHT1\n info = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1, vLightSpecular1);\n#endif\n#ifdef SHADOW1\n#ifdef SHADOWVSM1\n shadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1);\n#else\n shadow = computeShadow(vPositionFromLight1, shadowSampler1);\n#endif\n#else\n shadow = 1.;\n#endif\n diffuseBase += info[0] * shadow;\n specularBase += info[1] * shadow;\n#endif\n\n#ifdef LIGHT2\n#ifdef SPOTLIGHT2\n info = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2, vLightSpecular2);\n#endif\n#ifdef HEMILIGHT2\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2, vLightSpecular2, vLightGround2);\n#endif\n#ifdef POINTDIRLIGHT2\n info = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2, vLightSpecular2);\n#endif\n#ifdef SHADOW2\n#ifdef SHADOWVSM2\n shadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2);\n#else\n shadow = computeShadow(vPositionFromLight2, shadowSampler2);\n#endif \n#else\n shadow = 1.;\n#endif\n diffuseBase += info[0] * shadow;\n specularBase += info[1] * shadow;\n#endif\n\n#ifdef LIGHT3\n#ifdef SPOTLIGHT3\n info = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3, vLightSpecular3);\n#endif\n#ifdef HEMILIGHT3\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3, vLightSpecular3, vLightGround3);\n#endif\n#ifdef POINTDIRLIGHT3\n info = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3, vLightSpecular3);\n#endif\n#ifdef SHADOW3\n#ifdef SHADOWVSM3\n shadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3);\n#else\n shadow = computeShadow(vPositionFromLight3, shadowSampler3);\n#endif \n#else\n shadow = 1.;\n#endif\n diffuseBase += info[0] * shadow;\n specularBase += info[1] * shadow;\n#endif\n\n // Reflection\n vec3 reflectionColor = vec3(0., 0., 0.);\n\n#ifdef REFLECTION\n if (vReflectionInfos.z != 0.0)\n {\n reflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).rgb * vReflectionInfos.y;\n }\n else\n {\n vec2 coords = vReflectionUVW.xy;\n\n if (vReflectionInfos.x == MAP_PROJECTION)\n {\n coords /= vReflectionUVW.z;\n }\n\n coords.y = 1.0 - coords.y;\n\n reflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.y;\n }\n\n#ifdef REFLECTIONFRESNEL\n float reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\n\n reflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\n#endif\n#endif\n\n // Alpha\n float alpha = vDiffuseColor.a;\n\n#ifdef OPACITY\n vec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\n#ifdef OPACITYRGB\n opacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\n alpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\n#else\n alpha *= opacityMap.a * vOpacityInfos.y;\n#endif\n#endif\n\n#ifdef VERTEXALPHA\n alpha *= vColor.a;\n#endif\n\n#ifdef OPACITYFRESNEL\n float opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\n\n alpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\n#endif\n\n // Emissive\n vec3 emissiveColor = vEmissiveColor;\n#ifdef EMISSIVE\n emissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\n#endif\n\n#ifdef EMISSIVEFRESNEL\n float emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\n\n emissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\n#endif\n\n // Specular map\n vec3 specularColor = vSpecularColor.rgb;\n#ifdef SPECULAR\n specularColor = texture2D(specularSampler, vSpecularUV).rgb * vSpecularInfos.y;\n#endif\n\n // Fresnel\n#ifdef DIFFUSEFRESNEL\n float diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\n\n diffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\n#endif\n\n // Composition\n vec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\n vec3 finalSpecular = specularBase * specularColor;\n\n vec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor, alpha);\n\n#ifdef FOG\n float fog = CalcFogFactor();\n color.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\n#endif\n\n gl_FragColor = color;\n}",
  13373. legacydefaultVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#define MAP_EXPLICIT 0.\n#define MAP_SPHERICAL 1.\n#define MAP_PLANAR 2.\n#define MAP_CUBIC 3.\n#define MAP_PROJECTION 4.\n#define MAP_SKYBOX 5.\n\n// Attributes\nattribute vec3 position;\nattribute vec3 normal;\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#ifdef BONES\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#endif\n\n// Uniforms\nuniform mat4 world;\nuniform mat4 view;\nuniform mat4 viewProjection;\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec3 vEyePosition;\nvarying vec3 vReflectionUVW;\nuniform vec3 vReflectionInfos;\nuniform mat4 reflectionMatrix;\n#endif\n\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n\n#ifdef SPECULAR\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec2 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n\n#ifdef BONES\nuniform mat4 mBones[BonesPerMesh];\n#endif\n\n// Output\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif\n\n#ifdef FOG\nvarying float fFogDistance;\n#endif\n\n#ifdef SHADOWS\n#ifdef LIGHT0\nuniform mat4 lightMatrix0;\nvarying vec4 vPositionFromLight0;\n#endif\n#ifdef LIGHT1\nuniform mat4 lightMatrix1;\nvarying vec4 vPositionFromLight1;\n#endif\n#ifdef LIGHT2\nuniform mat4 lightMatrix2;\nvarying vec4 vPositionFromLight2;\n#endif\n#ifdef LIGHT3\nuniform mat4 lightMatrix3;\nvarying vec4 vPositionFromLight3;\n#endif\n#endif\n\n#ifdef REFLECTION\nvec3 computeReflectionCoords(float mode, vec4 worldPos, vec3 worldNormal)\n{\n if (mode == MAP_SPHERICAL)\n {\n vec3 coords = vec3(view * vec4(worldNormal, 0.0));\n\n return vec3(reflectionMatrix * vec4(coords, 1.0));\n }\n else if (mode == MAP_PLANAR)\n {\n vec3 viewDir = worldPos.xyz - vEyePosition;\n vec3 coords = normalize(reflect(viewDir, worldNormal));\n\n return vec3(reflectionMatrix * vec4(coords, 1));\n }\n else if (mode == MAP_CUBIC)\n {\n vec3 viewDir = worldPos.xyz - vEyePosition;\n vec3 coords = reflect(viewDir, worldNormal);\n\n return vec3(reflectionMatrix * vec4(coords, 0));\n }\n else if (mode == MAP_PROJECTION)\n {\n return vec3(reflectionMatrix * (view * worldPos));\n }\n else if (mode == MAP_SKYBOX)\n {\n return position;\n }\n\n return vec3(0, 0, 0);\n}\n#endif\n\nvoid main(void) {\n mat4 finalWorld;\n\n#ifdef BONES\n mat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\n mat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\n mat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\n\n#ifdef BONES4\n mat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\n finalWorld = world * (m0 + m1 + m2 + m3);\n#else\n finalWorld = world * (m0 + m1 + m2);\n#endif \n\n#else\n finalWorld = world;\n#endif\n\n gl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n\n vec4 worldPos = finalWorld * vec4(position, 1.0);\n vPositionW = vec3(worldPos);\n vNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\n\n // Texture coordinates\n#ifndef UV1\n vec2 uv = vec2(0., 0.);\n#endif\n#ifndef UV2\n vec2 uv2 = vec2(0., 0.);\n#endif\n\n#ifdef DIFFUSE\n if (vDiffuseInfos.x == 0.)\n {\n vDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef AMBIENT\n if (vAmbientInfos.x == 0.)\n {\n vAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef OPACITY\n if (vOpacityInfos.x == 0.)\n {\n vOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef REFLECTION\n vReflectionUVW = computeReflectionCoords(vReflectionInfos.x, vec4(vPositionW, 1.0), vNormalW);\n#endif\n\n#ifdef EMISSIVE\n if (vEmissiveInfos.x == 0.)\n {\n vEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef SPECULAR\n if (vSpecularInfos.x == 0.)\n {\n vSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n#ifdef BUMP\n if (vBumpInfos.x == 0.)\n {\n vBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\n }\n else\n {\n vBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\n }\n#endif\n\n // Clip plane\n#ifdef CLIPPLANE\n fClipDistance = dot(worldPos, vClipPlane);\n#endif\n\n // Fog\n#ifdef FOG\n fFogDistance = (view * worldPos).z;\n#endif\n\n // Shadows\n#ifdef SHADOWS\n#ifdef LIGHT0\n vPositionFromLight0 = lightMatrix0 * worldPos;\n#endif\n#ifdef LIGHT1\n vPositionFromLight1 = lightMatrix1 * worldPos;\n#endif\n#ifdef LIGHT2\n vPositionFromLight2 = lightMatrix2 * worldPos;\n#endif\n#ifdef LIGHT3\n vPositionFromLight3 = lightMatrix3 * worldPos;\n#endif\n#endif\n\n // Vertex color\n#ifdef VERTEXCOLOR\n vColor = color;\n#endif\n}",
  13374. lensFlarePixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\n// Color\nuniform vec4 color;\n\nvoid main(void) {\n vec4 baseColor = texture2D(textureSampler, vUV);\n\n gl_FragColor = baseColor * color;\n}",
  13375. lensFlareVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attributes\nattribute vec2 position;\n\n// Uniforms\nuniform mat4 viewportMatrix;\n\n// Output\nvarying vec2 vUV;\n\nconst vec2 madd = vec2(0.5, 0.5);\n\nvoid main(void) { \n\n vUV = position * madd + madd;\n gl_Position = viewportMatrix * vec4(position, 0.0, 1.0);\n}",
  13376. marblePixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\n\nuniform float numberOfTilesHeight;\nuniform float numberOfTilesWidth;\nuniform float amplitude;\nuniform vec3 brickColor;\nuniform vec3 jointColor;\n\nconst vec3 tileSize = vec3(1.1, 1.0, 1.1);\nconst vec3 tilePct = vec3(0.98, 1.0, 0.98);\n\nfloat rand(vec2 n) {\n return fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\n const vec2 d = vec2(0.0, 1.0);\n vec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\n return mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\n}\n\nfloat turbulence(vec2 P)\n{\n float val = 0.0;\n float freq = 1.0;\n for (int i = 0; i < 4; i++)\n {\n val += abs(noise(P*freq) / freq);\n freq *= 2.07;\n }\n return val;\n}\n\nfloat round(float number){\n return sign(number)*floor(abs(number) + 0.5);\n}\n\nvec3 marble_color(float x)\n{\n vec3 col;\n x = 0.5*(x + 1.);\n x = sqrt(x); \n x = sqrt(x);\n x = sqrt(x);\n col = vec3(.2 + .75*x); \n col.b *= 0.95; \n return col;\n}\n\nvoid main()\n{\n float brickW = 1.0 / numberOfTilesWidth;\n float brickH = 1.0 / numberOfTilesHeight;\n float jointWPercentage = 0.01;\n float jointHPercentage = 0.01;\n vec3 color = brickColor;\n float yi = vUV.y / brickH;\n float nyi = round(yi);\n float xi = vUV.x / brickW;\n\n if (mod(floor(yi), 2.0) == 0.0){\n xi = xi - 0.5;\n }\n\n float nxi = round(xi);\n vec2 brickvUV = vec2((xi - floor(xi)) / brickH, (yi - floor(yi)) / brickW);\n\n if (yi < nyi + jointHPercentage && yi > nyi - jointHPercentage){\n color = mix(jointColor, vec3(0.37, 0.25, 0.25), (yi - nyi) / jointHPercentage + 0.2);\n }\n else if (xi < nxi + jointWPercentage && xi > nxi - jointWPercentage){\n color = mix(jointColor, vec3(0.44, 0.44, 0.44), (xi - nxi) / jointWPercentage + 0.2);\n }\n else {\n float t = 6.28 * brickvUV.x / (tileSize.x + noise(vec2(vUV)*6.0));\n t += amplitude * turbulence(brickvUV.xy);\n t = sin(t);\n color = marble_color(t);\n }\n\n gl_FragColor = vec4(color, 0.0);\n}",
  13377. oculusDistortionCorrectionPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\n\nvec2 HmdWarp(vec2 in01) {\n\n vec2 theta = (in01 - LensCenter) * ScaleIn; // Scales to [-1, 1]\n float rSq = theta.x * theta.x + theta.y * theta.y;\n vec2 rvector = theta * (HmdWarpParam.x + HmdWarpParam.y * rSq + HmdWarpParam.z * rSq * rSq + HmdWarpParam.w * rSq * rSq * rSq);\n return LensCenter + Scale * rvector;\n}\n\nvoid main(void)\n{\n vec2 tc = HmdWarp(vUV);\n if (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\n gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\n else{\n gl_FragColor = vec4(texture2D(textureSampler, tc).rgb, 1.0);\n }\n}",
  13378. outlinePixelShader:"precision highp float;\n\nuniform vec4 color;\n\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n\nvoid main(void) {\n#ifdef ALPHATEST\n if (texture2D(diffuseSampler, vUV).a < 0.4)\n discard;\n#endif\n\n gl_FragColor = color;\n}",
  13379. outlineVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attribute\nattribute vec3 position;\nattribute vec3 normal;\n\n#ifdef BONES\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#endif\n\n// Uniform\nuniform float offset;\n\n#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif\n\nuniform mat4 viewProjection;\n#ifdef BONES\nuniform mat4 mBones[BonesPerMesh];\n#endif\n\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n\nvoid main(void)\n{\n#ifdef INSTANCES\n mat4 finalWorld = mat4(world0, world1, world2, world3);\n#else\n mat4 finalWorld = world;\n#endif\n\n vec3 offsetPosition = position + normal * offset;\n\n#ifdef BONES\n mat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\n mat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\n mat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\n mat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\n finalWorld = finalWorld * (m0 + m1 + m2 + m3);\n gl_Position = viewProjection * finalWorld * vec4(offsetPosition, 1.0);\n#else\n gl_Position = viewProjection * finalWorld * vec4(offsetPosition, 1.0);\n#endif\n\n#ifdef ALPHATEST\n#ifdef UV1\n vUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\n#endif\n#ifdef UV2\n vUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\n#endif\n#endif\n}",
  13380. particlesPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\n\nvoid main(void) {\n#ifdef CLIPPLANE\n if (fClipDistance > 0.0)\n discard;\n#endif\n vec4 baseColor = texture2D(diffuseSampler, vUV);\n\n gl_FragColor = (baseColor * textureMask + (vec4(1., 1., 1., 1.) - textureMask)) * vColor;\n}",
  13381. particlesVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attributes\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\n\n// Uniforms\nuniform mat4 view;\nuniform mat4 projection;\n\n// Output\nvarying vec2 vUV;\nvarying vec4 vColor;\n\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\n\nvoid main(void) { \n vec3 viewPos = (view * vec4(position, 1.0)).xyz; \n vec3 cornerPos;\n float size = options.y;\n float angle = options.x;\n vec2 offset = options.zw;\n\n cornerPos = vec3(offset.x - 0.5, offset.y - 0.5, 0.) * size;\n\n // Rotate\n vec3 rotatedCorner;\n rotatedCorner.x = cornerPos.x * cos(angle) - cornerPos.y * sin(angle);\n rotatedCorner.y = cornerPos.x * sin(angle) + cornerPos.y * cos(angle);\n rotatedCorner.z = 0.;\n\n // Position\n viewPos += rotatedCorner;\n gl_Position = projection * vec4(viewPos, 1.0); \n \n vColor = color;\n vUV = offset;\n\n // Clip plane\n#ifdef CLIPPLANE\n vec4 worldPos = invView * vec4(viewPos, 1.0);\n fClipDistance = dot(worldPos, vClipPlane);\n#endif\n}",
  13382. passPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nvoid main(void) \n{\n gl_FragColor = texture2D(textureSampler, vUV);\n}",
  13383. postprocessVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attributes\nattribute vec2 position;\n\n// Output\nvarying vec2 vUV;\n\nconst vec2 madd = vec2(0.5, 0.5);\n\nvoid main(void) { \n\n vUV = position * madd + madd;\n gl_Position = vec4(position, 0.0, 1.0);\n}",
  13384. proceduralVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attributes\nattribute vec2 position;\n\n// Output\nvarying vec2 vPosition;\nvarying vec2 vUV;\n\nconst vec2 madd = vec2(0.5, 0.5);\n\nvoid main(void) { \n vPosition = position;\n vUV = position * madd + madd;\n gl_Position = vec4(position, 0.0, 1.0);\n}",
  13385. refractionPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\n// Parameters\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\n\nvoid main() {\n float ref = 1.0 - texture2D(refractionSampler, vUV).r;\n\n vec2 uv = vUV - vec2(0.5);\n vec2 offset = uv * depth * ref;\n vec3 sourceColor = texture2D(textureSampler, vUV - offset).rgb;\n\n gl_FragColor = vec4(sourceColor + sourceColor * ref * colorLevel, 1.0);\n}",
  13386. roadPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vUV; \nuniform vec3 roadColor;\n\nfloat rand(vec2 n) {\n return fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\n const vec2 d = vec2(0.0, 1.0);\n vec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\n return mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\n}\n\nfloat fbm(vec2 n) {\n float total = 0.0, amplitude = 1.0;\n for (int i = 0; i < 4; i++) {\n total += noise(n) * amplitude;\n n += n;\n amplitude *= 0.5;\n }\n return total;\n}\n\nvoid main(void) {\n float ratioy = mod(gl_FragCoord.y * 100.0 , fbm(vUV * 2.0));\n vec3 color = roadColor * ratioy;\n gl_FragColor = vec4(color, 1.0);\n}",
  13387. shadowMapPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvec4 pack(float depth)\n{\n const vec4 bitOffset = vec4(255. * 255. * 255., 255. * 255., 255., 1.);\n const vec4 bitMask = vec4(0., 1. / 255., 1. / 255., 1. / 255.);\n \n vec4 comp = mod(depth * bitOffset * vec4(254.), vec4(255.)) / vec4(254.);\n comp -= comp.xxyz * bitMask;\n \n return comp;\n}\n\n// Thanks to http://devmaster.net/\nvec2 packHalf(float depth) \n{ \n const vec2 bitOffset = vec2(1.0 / 255., 0.);\n vec2 color = vec2(depth, fract(depth * 255.));\n\n return color - (color.yy * bitOffset);\n}\n\n#ifndef VSM\nvarying vec4 vPosition;\n#endif\n\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n\nvoid main(void)\n{\n#ifdef ALPHATEST\n if (texture2D(diffuseSampler, vUV).a < 0.4)\n discard;\n#endif\n\n#ifdef VSM\n float moment1 = gl_FragCoord.z / gl_FragCoord.w;\n float moment2 = moment1 * moment1;\n gl_FragColor = vec4(packHalf(moment1), packHalf(moment2));\n#else\n gl_FragColor = pack(vPosition.z / vPosition.w);\n#endif\n}",
  13388. shadowMapVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attribute\nattribute vec3 position;\n#ifdef BONES\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#endif\n\n// Uniform\n#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif\n\nuniform mat4 viewProjection;\n#ifdef BONES\nuniform mat4 mBones[BonesPerMesh];\n#endif\n\n#ifndef VSM\nvarying vec4 vPosition;\n#endif\n\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n\nvoid main(void)\n{\n#ifdef INSTANCES\n mat4 finalWorld = mat4(world0, world1, world2, world3);\n#else\n mat4 finalWorld = world;\n#endif\n\n#ifdef BONES\n mat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\n mat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\n mat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\n mat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\n finalWorld = finalWorld * (m0 + m1 + m2 + m3);\n gl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n#else\n#ifndef VSM\n vPosition = viewProjection * finalWorld * vec4(position, 1.0);\n#endif\n gl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n#endif\n\n#ifdef ALPHATEST\n#ifdef UV1\n vUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\n#endif\n#ifdef UV2\n vUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\n#endif\n#endif\n}",
  13389. spritesPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nuniform bool alphaTest;\n\nvarying vec4 vColor;\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n// Fog\n#ifdef FOG\n\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\n\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying float fFogDistance;\n\nfloat CalcFogFactor()\n{\n float fogCoeff = 1.0;\n float fogStart = vFogInfos.y;\n float fogEnd = vFogInfos.z;\n float fogDensity = vFogInfos.w;\n\n if (FOGMODE_LINEAR == vFogInfos.x)\n {\n fogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\n }\n else if (FOGMODE_EXP == vFogInfos.x)\n {\n fogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\n }\n else if (FOGMODE_EXP2 == vFogInfos.x)\n {\n fogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\n }\n\n return min(1., max(0., fogCoeff));\n}\n#endif\n\n\nvoid main(void) {\n vec4 baseColor = texture2D(diffuseSampler, vUV);\n\n if (alphaTest) \n {\n if (baseColor.a < 0.95)\n discard;\n }\n\n baseColor *= vColor;\n\n#ifdef FOG\n float fog = CalcFogFactor();\n baseColor.rgb = fog * baseColor.rgb + (1.0 - fog) * vFogColor;\n#endif\n\n gl_FragColor = baseColor;\n}",
  13390. spritesVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attributes\nattribute vec3 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\n// Uniforms\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\n// Output\nvarying vec2 vUV;\nvarying vec4 vColor;\n\n#ifdef FOG\nvarying float fFogDistance;\n#endif\n\nvoid main(void) { \n vec3 viewPos = (view * vec4(position, 1.0)).xyz; \n vec3 cornerPos;\n \n float angle = options.x;\n float size = options.y;\n vec2 offset = options.zw;\n vec2 uvScale = textureInfos.xy;\n\n cornerPos = vec3(offset.x - 0.5, offset.y - 0.5, 0.) * size;\n\n // Rotate\n vec3 rotatedCorner;\n rotatedCorner.x = cornerPos.x * cos(angle) - cornerPos.y * sin(angle);\n rotatedCorner.y = cornerPos.x * sin(angle) + cornerPos.y * cos(angle);\n rotatedCorner.z = 0.;\n\n // Position\n viewPos += rotatedCorner;\n gl_Position = projection * vec4(viewPos, 1.0); \n\n // Color\n vColor = color;\n \n // Texture\n vec2 uvOffset = vec2(abs(offset.x - cellInfo.x), 1.0 - abs(offset.y - cellInfo.y));\n\n vUV = (uvOffset + cellInfo.zw) * uvScale;\n\n // Fog\n#ifdef FOG\n fFogDistance = viewPos.z;\n#endif\n}",
  13391. ssaoPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#define SAMPLES 16\n\nuniform sampler2D textureSampler;\nuniform sampler2D randomSampler;\n\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[16];\n\nvarying vec2 vUV;\n\nconst vec2 offset1 = vec2(0.0, 0.01);\nconst vec2 offset2 = vec2(0.01, 0.0);\n\nvec3 normalFromDepth(const float depth, const vec2 coords) {\n float depth1 = texture2D(textureSampler, coords + offset1).r;\n float depth2 = texture2D(textureSampler, coords + offset2).r;\n\n vec3 p1 = vec3(offset1, depth1 - depth);\n vec3 p2 = vec3(offset2, depth2 - depth);\n\n vec3 normal = cross(p1, p2);\n normal.z = -normal.z;\n\n return normalize(normal);\n}\n\nvoid main(void)\n{\n const float totalStrength = 1.0;\n const float base = 0.2;\n const float area = 0.0075;\n const float fallOff = 0.000001;\n const float radius = 0.0005;\n\n vec3 random = texture2D(randomSampler, vUV * randTextureTiles).rgb;\n float depth = texture2D(textureSampler, vUV).r;\n vec3 position = vec3(vUV, depth);\n vec3 normal = normalFromDepth(depth, vUV);\n float radiusDepth = radius / depth;\n float occlusion = 0.0;\n\n vec3 ray;\n vec3 hemiRay;\n float occlusionDepth;\n float difference;\n\n for (int i = 0; i < SAMPLES; i++)\n {\n ray = radiusDepth * reflect(sampleSphere[i], random);\n hemiRay = position + dot(ray, normal) * ray;\n\n occlusionDepth = texture2D(textureSampler, clamp(hemiRay.xy, 0.0, 1.0)).r;\n difference = depth - occlusionDepth;\n\n occlusion += step(fallOff, difference) * (1.0 - smoothstep(fallOff, area, difference));\n }\n\n float ao = 1.0 - totalStrength * occlusion * samplesFactor;\n\n float result = clamp(ao + base, 0.0, 1.0);\n gl_FragColor.r = result;\n gl_FragColor.g = result;\n gl_FragColor.b = result;\n gl_FragColor.a = 1.0;\n}",
  13392. ssaoCombinePixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nuniform sampler2D textureSampler;\nuniform sampler2D originalColor;\n\nvarying vec2 vUV;\n\nvoid main(void) {\n gl_FragColor = texture2D(originalColor, vUV) * texture2D(textureSampler, vUV);\n}",
  13393. volumetricLightScatteringPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nuniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\n\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\n\nvarying vec2 vUV;\n\nvoid main(void) {\n vec2 tc = vUV;\n vec2 deltaTexCoord = (tc - meshPositionOnScreen.xy);\n deltaTexCoord *= 1.0 / float(NUM_SAMPLES) * density;\n\n float illuminationDecay = 1.0;\n\n vec4 color = texture2D(lightScatteringSampler, tc) * 0.4;\n\n for(int i=0; i < NUM_SAMPLES; i++) {\n tc -= deltaTexCoord;\n vec4 sample = texture2D(lightScatteringSampler, tc) * 0.4;\n sample *= illuminationDecay * weight;\n color += sample;\n illuminationDecay *= decay;\n }\n\n vec4 realColor = texture2D(textureSampler, vUV);\n gl_FragColor = ((vec4((vec3(color.r, color.g, color.b) * exposure), 1)) + (realColor * (1.5 - 0.4)));\n}",
  13394. volumetricLightScatteringPassPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#if defined(ALPHATEST) || defined(BASIC_RENDER) || defined(OPACITY)\nvarying vec2 vUV;\n#endif\n\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\nuniform sampler2D diffuseSampler;\n#endif\n\n#if defined(OPACITY)\nuniform sampler2D opacitySampler;\n#endif\n\nvoid main(void)\n{\n#if defined(ALPHATEST) || defined(OPACITY) || defined(BASIC_RENDER)\n vec4 diffuseColor = texture2D(diffuseSampler, vUV);\n#endif\n\n#ifdef ALPHATEST\n if (diffuseColor.a < 0.4)\n discard;\n#endif\n\n#ifdef BASIC_RENDER\n#ifdef OPACITY\n gl_FragColor = diffuseColor * texture2D(opacitySampler, vUV);\n#else\n gl_FragColor = diffuseColor;\n#endif\n#else\n gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\n#endif\n\n}",
  13395. woodPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\n\nuniform float ampScale;\nuniform vec3 woodColor;\n\nfloat rand(vec2 n) {\n return fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\n const vec2 d = vec2(0.0, 1.0);\n vec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\n return mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\n}\n\nfloat fbm(vec2 n) {\n float total = 0.0, amplitude = 1.0;\n for (int i = 0; i < 4; i++) {\n total += noise(n) * amplitude;\n n += n;\n amplitude *= 0.5;\n }\n return total;\n}\n\nvoid main(void) {\n float ratioy = mod(vUV.x * ampScale, 2.0 + fbm(vUV * 0.8));\n vec3 wood = woodColor * ratioy;\n gl_FragColor = vec4(wood, 1.0);\n}",
  13396. };
  13397. return Effect;
  13398. })();
  13399. BABYLON.Effect = Effect;
  13400. })(BABYLON || (BABYLON = {}));
  13401. //# sourceMappingURL=babylon.effect.js.mapvar BABYLON;
  13402. (function (BABYLON) {
  13403. var Material = (function () {
  13404. function Material(name, scene, doNotAdd) {
  13405. this.name = name;
  13406. this.checkReadyOnEveryCall = true;
  13407. this.checkReadyOnlyOnce = false;
  13408. this.state = "";
  13409. this.alpha = 1.0;
  13410. this.backFaceCulling = true;
  13411. this._wasPreviouslyReady = false;
  13412. this._fillMode = Material.TriangleFillMode;
  13413. this.pointSize = 1.0;
  13414. this.id = name;
  13415. this._scene = scene;
  13416. if (!doNotAdd) {
  13417. scene.materials.push(this);
  13418. }
  13419. }
  13420. Object.defineProperty(Material, "TriangleFillMode", {
  13421. get: function () {
  13422. return Material._TriangleFillMode;
  13423. },
  13424. enumerable: true,
  13425. configurable: true
  13426. });
  13427. Object.defineProperty(Material, "WireFrameFillMode", {
  13428. get: function () {
  13429. return Material._WireFrameFillMode;
  13430. },
  13431. enumerable: true,
  13432. configurable: true
  13433. });
  13434. Object.defineProperty(Material, "PointFillMode", {
  13435. get: function () {
  13436. return Material._PointFillMode;
  13437. },
  13438. enumerable: true,
  13439. configurable: true
  13440. });
  13441. Object.defineProperty(Material.prototype, "wireframe", {
  13442. get: function () {
  13443. return this._fillMode === Material.WireFrameFillMode;
  13444. },
  13445. set: function (value) {
  13446. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  13447. },
  13448. enumerable: true,
  13449. configurable: true
  13450. });
  13451. Object.defineProperty(Material.prototype, "pointsCloud", {
  13452. get: function () {
  13453. return this._fillMode === Material.PointFillMode;
  13454. },
  13455. set: function (value) {
  13456. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  13457. },
  13458. enumerable: true,
  13459. configurable: true
  13460. });
  13461. Object.defineProperty(Material.prototype, "fillMode", {
  13462. get: function () {
  13463. return this._fillMode;
  13464. },
  13465. set: function (value) {
  13466. this._fillMode = value;
  13467. },
  13468. enumerable: true,
  13469. configurable: true
  13470. });
  13471. Material.prototype.isReady = function (mesh, useInstances) {
  13472. return true;
  13473. };
  13474. Material.prototype.getEffect = function () {
  13475. return this._effect;
  13476. };
  13477. Material.prototype.getScene = function () {
  13478. return this._scene;
  13479. };
  13480. Material.prototype.needAlphaBlending = function () {
  13481. return (this.alpha < 1.0);
  13482. };
  13483. Material.prototype.needAlphaTesting = function () {
  13484. return false;
  13485. };
  13486. Material.prototype.getAlphaTestTexture = function () {
  13487. return null;
  13488. };
  13489. Material.prototype.trackCreation = function (onCompiled, onError) {
  13490. };
  13491. Material.prototype._preBind = function () {
  13492. var engine = this._scene.getEngine();
  13493. engine.enableEffect(this._effect);
  13494. engine.setState(this.backFaceCulling);
  13495. };
  13496. Material.prototype.bind = function (world, mesh) {
  13497. this._scene._cachedMaterial = this;
  13498. if (this.onBind) {
  13499. this.onBind(this);
  13500. }
  13501. };
  13502. Material.prototype.bindOnlyWorldMatrix = function (world) {
  13503. };
  13504. Material.prototype.unbind = function () {
  13505. };
  13506. Material.prototype.dispose = function (forceDisposeEffect) {
  13507. // Remove from scene
  13508. var index = this._scene.materials.indexOf(this);
  13509. this._scene.materials.splice(index, 1);
  13510. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  13511. if (forceDisposeEffect && this._effect) {
  13512. this._scene.getEngine()._releaseEffect(this._effect);
  13513. this._effect = null;
  13514. }
  13515. // Callback
  13516. if (this.onDispose) {
  13517. this.onDispose();
  13518. }
  13519. };
  13520. Material._TriangleFillMode = 0;
  13521. Material._WireFrameFillMode = 1;
  13522. Material._PointFillMode = 2;
  13523. return Material;
  13524. })();
  13525. BABYLON.Material = Material;
  13526. })(BABYLON || (BABYLON = {}));
  13527. //# sourceMappingURL=babylon.material.js.map
  13528. var BABYLON;
  13529. (function (BABYLON) {
  13530. var maxSimultaneousLights = 4;
  13531. var FresnelParameters = (function () {
  13532. function FresnelParameters() {
  13533. this.isEnabled = true;
  13534. this.leftColor = BABYLON.Color3.White();
  13535. this.rightColor = BABYLON.Color3.Black();
  13536. this.bias = 0;
  13537. this.power = 1;
  13538. }
  13539. return FresnelParameters;
  13540. })();
  13541. BABYLON.FresnelParameters = FresnelParameters;
  13542. var StandardMaterial = (function (_super) {
  13543. __extends(StandardMaterial, _super);
  13544. function StandardMaterial(name, scene) {
  13545. var _this = this;
  13546. _super.call(this, name, scene);
  13547. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  13548. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  13549. this.specularColor = new BABYLON.Color3(1, 1, 1);
  13550. this.specularPower = 64;
  13551. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  13552. this.useAlphaFromDiffuseTexture = false;
  13553. this.useSpecularOverAlpha = true;
  13554. this.fogEnabled = true;
  13555. this._cachedDefines = null;
  13556. this._renderTargets = new BABYLON.SmartArray(16);
  13557. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  13558. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  13559. this._scaledDiffuse = new BABYLON.Color3();
  13560. this._scaledSpecular = new BABYLON.Color3();
  13561. this.getRenderTargetTextures = function () {
  13562. _this._renderTargets.reset();
  13563. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  13564. _this._renderTargets.push(_this.reflectionTexture);
  13565. }
  13566. return _this._renderTargets;
  13567. };
  13568. }
  13569. StandardMaterial.prototype.needAlphaBlending = function () {
  13570. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  13571. };
  13572. StandardMaterial.prototype.needAlphaTesting = function () {
  13573. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && !this.diffuseTexture.getAlphaFromRGB;
  13574. };
  13575. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  13576. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  13577. };
  13578. StandardMaterial.prototype.getAlphaTestTexture = function () {
  13579. return this.diffuseTexture;
  13580. };
  13581. // Methods
  13582. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  13583. if (this.checkReadyOnlyOnce) {
  13584. if (this._wasPreviouslyReady) {
  13585. return true;
  13586. }
  13587. }
  13588. var scene = this.getScene();
  13589. if (!this.checkReadyOnEveryCall) {
  13590. if (this._renderId === scene.getRenderId()) {
  13591. return true;
  13592. }
  13593. }
  13594. var engine = scene.getEngine();
  13595. var defines = [];
  13596. var fallbacks = new BABYLON.EffectFallbacks();
  13597. // Textures
  13598. if (scene.texturesEnabled) {
  13599. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  13600. if (!this.diffuseTexture.isReady()) {
  13601. return false;
  13602. }
  13603. else {
  13604. defines.push("#define DIFFUSE");
  13605. }
  13606. }
  13607. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  13608. if (!this.ambientTexture.isReady()) {
  13609. return false;
  13610. }
  13611. else {
  13612. defines.push("#define AMBIENT");
  13613. }
  13614. }
  13615. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  13616. if (!this.opacityTexture.isReady()) {
  13617. return false;
  13618. }
  13619. else {
  13620. defines.push("#define OPACITY");
  13621. if (this.opacityTexture.getAlphaFromRGB) {
  13622. defines.push("#define OPACITYRGB");
  13623. }
  13624. }
  13625. }
  13626. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  13627. if (!this.reflectionTexture.isReady()) {
  13628. return false;
  13629. }
  13630. else {
  13631. defines.push("#define REFLECTION");
  13632. fallbacks.addFallback(0, "REFLECTION");
  13633. }
  13634. }
  13635. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  13636. if (!this.emissiveTexture.isReady()) {
  13637. return false;
  13638. }
  13639. else {
  13640. defines.push("#define EMISSIVE");
  13641. }
  13642. }
  13643. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  13644. if (!this.specularTexture.isReady()) {
  13645. return false;
  13646. }
  13647. else {
  13648. defines.push("#define SPECULAR");
  13649. fallbacks.addFallback(0, "SPECULAR");
  13650. }
  13651. }
  13652. }
  13653. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  13654. if (!this.bumpTexture.isReady()) {
  13655. return false;
  13656. }
  13657. else {
  13658. defines.push("#define BUMP");
  13659. fallbacks.addFallback(0, "BUMP");
  13660. }
  13661. }
  13662. // Effect
  13663. if (this.useSpecularOverAlpha) {
  13664. defines.push("#define SPECULAROVERALPHA");
  13665. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  13666. }
  13667. if (scene.clipPlane) {
  13668. defines.push("#define CLIPPLANE");
  13669. }
  13670. if (engine.getAlphaTesting()) {
  13671. defines.push("#define ALPHATEST");
  13672. }
  13673. if (this._shouldUseAlphaFromDiffuseTexture()) {
  13674. defines.push("#define ALPHAFROMDIFFUSE");
  13675. }
  13676. // Point size
  13677. if (this.pointsCloud || scene.forcePointsCloud) {
  13678. defines.push("#define POINTSIZE");
  13679. }
  13680. // Fog
  13681. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  13682. defines.push("#define FOG");
  13683. fallbacks.addFallback(1, "FOG");
  13684. }
  13685. var shadowsActivated = false;
  13686. var lightIndex = 0;
  13687. if (scene.lightsEnabled) {
  13688. for (var index = 0; index < scene.lights.length; index++) {
  13689. var light = scene.lights[index];
  13690. if (!light.isEnabled()) {
  13691. continue;
  13692. }
  13693. // Excluded check
  13694. if (light._excludedMeshesIds.length > 0) {
  13695. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  13696. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  13697. if (excludedMesh) {
  13698. light.excludedMeshes.push(excludedMesh);
  13699. }
  13700. }
  13701. light._excludedMeshesIds = [];
  13702. }
  13703. // Included check
  13704. if (light._includedOnlyMeshesIds.length > 0) {
  13705. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  13706. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  13707. if (includedOnlyMesh) {
  13708. light.includedOnlyMeshes.push(includedOnlyMesh);
  13709. }
  13710. }
  13711. light._includedOnlyMeshesIds = [];
  13712. }
  13713. if (!light.canAffectMesh(mesh)) {
  13714. continue;
  13715. }
  13716. defines.push("#define LIGHT" + lightIndex);
  13717. if (lightIndex > 0) {
  13718. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  13719. }
  13720. var type;
  13721. if (light instanceof BABYLON.SpotLight) {
  13722. type = "#define SPOTLIGHT" + lightIndex;
  13723. }
  13724. else if (light instanceof BABYLON.HemisphericLight) {
  13725. type = "#define HEMILIGHT" + lightIndex;
  13726. }
  13727. else {
  13728. type = "#define POINTDIRLIGHT" + lightIndex;
  13729. }
  13730. defines.push(type);
  13731. if (lightIndex > 0) {
  13732. fallbacks.addFallback(lightIndex, type.replace("#define ", ""));
  13733. }
  13734. // Shadows
  13735. if (scene.shadowsEnabled) {
  13736. var shadowGenerator = light.getShadowGenerator();
  13737. if (mesh && mesh.receiveShadows && shadowGenerator) {
  13738. defines.push("#define SHADOW" + lightIndex);
  13739. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  13740. if (!shadowsActivated) {
  13741. defines.push("#define SHADOWS");
  13742. shadowsActivated = true;
  13743. }
  13744. if (shadowGenerator.useVarianceShadowMap) {
  13745. defines.push("#define SHADOWVSM" + lightIndex);
  13746. if (lightIndex > 0) {
  13747. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  13748. }
  13749. }
  13750. if (shadowGenerator.usePoissonSampling) {
  13751. defines.push("#define SHADOWPCF" + lightIndex);
  13752. if (lightIndex > 0) {
  13753. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  13754. }
  13755. }
  13756. }
  13757. }
  13758. lightIndex++;
  13759. if (lightIndex === maxSimultaneousLights)
  13760. break;
  13761. }
  13762. }
  13763. if (StandardMaterial.FresnelEnabled) {
  13764. // Fresnel
  13765. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled || this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled || this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  13766. var fresnelRank = 1;
  13767. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  13768. defines.push("#define DIFFUSEFRESNEL");
  13769. fallbacks.addFallback(fresnelRank, "DIFFUSEFRESNEL");
  13770. fresnelRank++;
  13771. }
  13772. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  13773. defines.push("#define OPACITYFRESNEL");
  13774. fallbacks.addFallback(fresnelRank, "OPACITYFRESNEL");
  13775. fresnelRank++;
  13776. }
  13777. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  13778. defines.push("#define REFLECTIONFRESNEL");
  13779. fallbacks.addFallback(fresnelRank, "REFLECTIONFRESNEL");
  13780. fresnelRank++;
  13781. }
  13782. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  13783. defines.push("#define EMISSIVEFRESNEL");
  13784. fallbacks.addFallback(fresnelRank, "EMISSIVEFRESNEL");
  13785. fresnelRank++;
  13786. }
  13787. defines.push("#define FRESNEL");
  13788. fallbacks.addFallback(fresnelRank - 1, "FRESNEL");
  13789. }
  13790. }
  13791. // Attribs
  13792. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  13793. if (mesh) {
  13794. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  13795. attribs.push(BABYLON.VertexBuffer.UVKind);
  13796. defines.push("#define UV1");
  13797. }
  13798. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  13799. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  13800. defines.push("#define UV2");
  13801. }
  13802. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  13803. attribs.push(BABYLON.VertexBuffer.ColorKind);
  13804. defines.push("#define VERTEXCOLOR");
  13805. if (mesh.hasVertexAlpha) {
  13806. defines.push("#define VERTEXALPHA");
  13807. }
  13808. }
  13809. if (mesh.useBones) {
  13810. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  13811. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  13812. defines.push("#define BONES");
  13813. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  13814. defines.push("#define BONES4");
  13815. fallbacks.addFallback(0, "BONES4");
  13816. }
  13817. // Instances
  13818. if (useInstances) {
  13819. defines.push("#define INSTANCES");
  13820. attribs.push("world0");
  13821. attribs.push("world1");
  13822. attribs.push("world2");
  13823. attribs.push("world3");
  13824. }
  13825. }
  13826. // Get correct effect
  13827. var join = defines.join("\n");
  13828. if (this._cachedDefines !== join) {
  13829. this._cachedDefines = join;
  13830. scene.resetCachedMaterial();
  13831. // Legacy browser patch
  13832. var shaderName = "default";
  13833. if (!scene.getEngine().getCaps().standardDerivatives) {
  13834. shaderName = "legacydefault";
  13835. }
  13836. this._effect = scene.getEngine().createEffect(shaderName, attribs, ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor", "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0", "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1", "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2", "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3", "vFogInfos", "vFogColor", "pointSize", "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "mBones", "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "darkness0", "darkness1", "darkness2", "darkness3", "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor"], ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"], join, fallbacks, this.onCompiled, this.onError);
  13837. }
  13838. if (!this._effect.isReady()) {
  13839. return false;
  13840. }
  13841. this._renderId = scene.getRenderId();
  13842. this._wasPreviouslyReady = true;
  13843. return true;
  13844. };
  13845. StandardMaterial.prototype.unbind = function () {
  13846. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  13847. this._effect.setTexture("reflection2DSampler", null);
  13848. }
  13849. };
  13850. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  13851. this._effect.setMatrix("world", world);
  13852. };
  13853. StandardMaterial.prototype.bind = function (world, mesh) {
  13854. var scene = this.getScene();
  13855. // Matrices
  13856. this.bindOnlyWorldMatrix(world);
  13857. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  13858. // Bones
  13859. if (mesh.useBones) {
  13860. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  13861. }
  13862. if (scene.getCachedMaterial() !== this) {
  13863. if (StandardMaterial.FresnelEnabled) {
  13864. // Fresnel
  13865. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  13866. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  13867. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  13868. }
  13869. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  13870. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  13871. }
  13872. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  13873. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  13874. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  13875. }
  13876. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  13877. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  13878. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  13879. }
  13880. }
  13881. // Textures
  13882. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  13883. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  13884. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  13885. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  13886. }
  13887. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  13888. this._effect.setTexture("ambientSampler", this.ambientTexture);
  13889. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  13890. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  13891. }
  13892. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  13893. this._effect.setTexture("opacitySampler", this.opacityTexture);
  13894. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  13895. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  13896. }
  13897. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  13898. if (this.reflectionTexture.isCube) {
  13899. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  13900. }
  13901. else {
  13902. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  13903. }
  13904. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  13905. this._effect.setFloat3("vReflectionInfos", this.reflectionTexture.coordinatesMode, this.reflectionTexture.level, this.reflectionTexture.isCube ? 1 : 0);
  13906. }
  13907. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  13908. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  13909. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  13910. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  13911. }
  13912. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  13913. this._effect.setTexture("specularSampler", this.specularTexture);
  13914. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  13915. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  13916. }
  13917. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  13918. this._effect.setTexture("bumpSampler", this.bumpTexture);
  13919. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level);
  13920. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  13921. }
  13922. // Clip plane
  13923. if (scene.clipPlane) {
  13924. var clipPlane = scene.clipPlane;
  13925. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  13926. }
  13927. // Point size
  13928. if (this.pointsCloud) {
  13929. this._effect.setFloat("pointSize", this.pointSize);
  13930. }
  13931. // Colors
  13932. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  13933. // Scaling down color according to emissive
  13934. this._scaledSpecular.r = this.specularColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  13935. this._scaledSpecular.g = this.specularColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  13936. this._scaledSpecular.b = this.specularColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  13937. this._effect.setVector3("vEyePosition", scene.activeCamera.position);
  13938. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  13939. this._effect.setColor4("vSpecularColor", this._scaledSpecular, this.specularPower);
  13940. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  13941. }
  13942. // Scaling down color according to emissive
  13943. this._scaledDiffuse.r = this.diffuseColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  13944. this._scaledDiffuse.g = this.diffuseColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  13945. this._scaledDiffuse.b = this.diffuseColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  13946. this._effect.setColor4("vDiffuseColor", this._scaledDiffuse, this.alpha * mesh.visibility);
  13947. if (scene.lightsEnabled) {
  13948. var lightIndex = 0;
  13949. for (var index = 0; index < scene.lights.length; index++) {
  13950. var light = scene.lights[index];
  13951. if (!light.isEnabled()) {
  13952. continue;
  13953. }
  13954. if (!light.canAffectMesh(mesh)) {
  13955. continue;
  13956. }
  13957. if (light instanceof BABYLON.PointLight) {
  13958. // Point Light
  13959. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  13960. }
  13961. else if (light instanceof BABYLON.DirectionalLight) {
  13962. // Directional Light
  13963. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  13964. }
  13965. else if (light instanceof BABYLON.SpotLight) {
  13966. // Spot Light
  13967. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  13968. }
  13969. else if (light instanceof BABYLON.HemisphericLight) {
  13970. // Hemispheric Light
  13971. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  13972. }
  13973. light.diffuse.scaleToRef(light.intensity, this._scaledDiffuse);
  13974. light.specular.scaleToRef(light.intensity, this._scaledSpecular);
  13975. this._effect.setColor4("vLightDiffuse" + lightIndex, this._scaledDiffuse, light.range);
  13976. this._effect.setColor3("vLightSpecular" + lightIndex, this._scaledSpecular);
  13977. // Shadows
  13978. if (scene.shadowsEnabled) {
  13979. var shadowGenerator = light.getShadowGenerator();
  13980. if (mesh.receiveShadows && shadowGenerator) {
  13981. this._effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  13982. this._effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMap());
  13983. this._effect.setFloat("darkness" + lightIndex, shadowGenerator.getDarkness());
  13984. }
  13985. }
  13986. lightIndex++;
  13987. if (lightIndex === maxSimultaneousLights)
  13988. break;
  13989. }
  13990. }
  13991. // View
  13992. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  13993. this._effect.setMatrix("view", scene.getViewMatrix());
  13994. }
  13995. // Fog
  13996. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  13997. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  13998. this._effect.setColor3("vFogColor", scene.fogColor);
  13999. }
  14000. _super.prototype.bind.call(this, world, mesh);
  14001. };
  14002. StandardMaterial.prototype.getAnimatables = function () {
  14003. var results = [];
  14004. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  14005. results.push(this.diffuseTexture);
  14006. }
  14007. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  14008. results.push(this.ambientTexture);
  14009. }
  14010. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  14011. results.push(this.opacityTexture);
  14012. }
  14013. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  14014. results.push(this.reflectionTexture);
  14015. }
  14016. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  14017. results.push(this.emissiveTexture);
  14018. }
  14019. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  14020. results.push(this.specularTexture);
  14021. }
  14022. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  14023. results.push(this.bumpTexture);
  14024. }
  14025. return results;
  14026. };
  14027. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  14028. if (this.diffuseTexture) {
  14029. this.diffuseTexture.dispose();
  14030. }
  14031. if (this.ambientTexture) {
  14032. this.ambientTexture.dispose();
  14033. }
  14034. if (this.opacityTexture) {
  14035. this.opacityTexture.dispose();
  14036. }
  14037. if (this.reflectionTexture) {
  14038. this.reflectionTexture.dispose();
  14039. }
  14040. if (this.emissiveTexture) {
  14041. this.emissiveTexture.dispose();
  14042. }
  14043. if (this.specularTexture) {
  14044. this.specularTexture.dispose();
  14045. }
  14046. if (this.bumpTexture) {
  14047. this.bumpTexture.dispose();
  14048. }
  14049. _super.prototype.dispose.call(this, forceDisposeEffect);
  14050. };
  14051. StandardMaterial.prototype.clone = function (name) {
  14052. var newStandardMaterial = new StandardMaterial(name, this.getScene());
  14053. // Base material
  14054. newStandardMaterial.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  14055. newStandardMaterial.alpha = this.alpha;
  14056. newStandardMaterial.fillMode = this.fillMode;
  14057. newStandardMaterial.backFaceCulling = this.backFaceCulling;
  14058. // Standard material
  14059. if (this.diffuseTexture && this.diffuseTexture.clone) {
  14060. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  14061. }
  14062. if (this.ambientTexture && this.ambientTexture.clone) {
  14063. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  14064. }
  14065. if (this.opacityTexture && this.opacityTexture.clone) {
  14066. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  14067. }
  14068. if (this.reflectionTexture && this.reflectionTexture.clone) {
  14069. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  14070. }
  14071. if (this.emissiveTexture && this.emissiveTexture.clone) {
  14072. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  14073. }
  14074. if (this.specularTexture && this.specularTexture.clone) {
  14075. newStandardMaterial.specularTexture = this.specularTexture.clone();
  14076. }
  14077. if (this.bumpTexture && this.bumpTexture.clone) {
  14078. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  14079. }
  14080. newStandardMaterial.ambientColor = this.ambientColor.clone();
  14081. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  14082. newStandardMaterial.specularColor = this.specularColor.clone();
  14083. newStandardMaterial.specularPower = this.specularPower;
  14084. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  14085. return newStandardMaterial;
  14086. };
  14087. // Statics
  14088. // Flags used to enable or disable a type of texture for all Standard Materials
  14089. StandardMaterial.DiffuseTextureEnabled = true;
  14090. StandardMaterial.AmbientTextureEnabled = true;
  14091. StandardMaterial.OpacityTextureEnabled = true;
  14092. StandardMaterial.ReflectionTextureEnabled = true;
  14093. StandardMaterial.EmissiveTextureEnabled = true;
  14094. StandardMaterial.SpecularTextureEnabled = true;
  14095. StandardMaterial.BumpTextureEnabled = true;
  14096. StandardMaterial.FresnelEnabled = true;
  14097. return StandardMaterial;
  14098. })(BABYLON.Material);
  14099. BABYLON.StandardMaterial = StandardMaterial;
  14100. })(BABYLON || (BABYLON = {}));
  14101. //# sourceMappingURL=babylon.standardMaterial.js.map
  14102. var BABYLON;
  14103. (function (BABYLON) {
  14104. var MultiMaterial = (function (_super) {
  14105. __extends(MultiMaterial, _super);
  14106. function MultiMaterial(name, scene) {
  14107. _super.call(this, name, scene, true);
  14108. this.subMaterials = new Array();
  14109. scene.multiMaterials.push(this);
  14110. }
  14111. // Properties
  14112. MultiMaterial.prototype.getSubMaterial = function (index) {
  14113. if (index < 0 || index >= this.subMaterials.length) {
  14114. return this.getScene().defaultMaterial;
  14115. }
  14116. return this.subMaterials[index];
  14117. };
  14118. // Methods
  14119. MultiMaterial.prototype.isReady = function (mesh) {
  14120. for (var index = 0; index < this.subMaterials.length; index++) {
  14121. var subMaterial = this.subMaterials[index];
  14122. if (subMaterial) {
  14123. if (!this.subMaterials[index].isReady(mesh)) {
  14124. return false;
  14125. }
  14126. }
  14127. }
  14128. return true;
  14129. };
  14130. return MultiMaterial;
  14131. })(BABYLON.Material);
  14132. BABYLON.MultiMaterial = MultiMaterial;
  14133. })(BABYLON || (BABYLON = {}));
  14134. //# sourceMappingURL=babylon.multiMaterial.js.mapvar BABYLON;
  14135. (function (BABYLON) {
  14136. var Database = (function () {
  14137. function Database(urlToScene, callbackManifestChecked) {
  14138. // Handling various flavors of prefixed version of IndexedDB
  14139. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  14140. this.callbackManifestChecked = callbackManifestChecked;
  14141. this.currentSceneUrl = BABYLON.Database.ReturnFullUrlLocation(urlToScene);
  14142. this.db = null;
  14143. this.enableSceneOffline = false;
  14144. this.enableTexturesOffline = false;
  14145. this.manifestVersionFound = 0;
  14146. this.mustUpdateRessources = false;
  14147. this.hasReachedQuota = false;
  14148. this.checkManifestFile();
  14149. }
  14150. Database.prototype.checkManifestFile = function () {
  14151. var _this = this;
  14152. function noManifestFile() {
  14153. BABYLON.Tools.Log("Valid manifest file not found. Scene & textures will be loaded directly from the web server.");
  14154. that.enableSceneOffline = false;
  14155. that.enableTexturesOffline = false;
  14156. that.callbackManifestChecked(false);
  14157. }
  14158. var that = this;
  14159. var manifestURL = this.currentSceneUrl + ".manifest";
  14160. var xhr = new XMLHttpRequest();
  14161. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  14162. xhr.open("GET", manifestURLTimeStamped, true);
  14163. xhr.addEventListener("load", function () {
  14164. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  14165. try {
  14166. var manifestFile = JSON.parse(xhr.response);
  14167. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  14168. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  14169. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  14170. _this.manifestVersionFound = manifestFile.version;
  14171. }
  14172. if (_this.callbackManifestChecked) {
  14173. _this.callbackManifestChecked(true);
  14174. }
  14175. }
  14176. catch (ex) {
  14177. noManifestFile();
  14178. }
  14179. }
  14180. else {
  14181. noManifestFile();
  14182. }
  14183. }, false);
  14184. xhr.addEventListener("error", function (event) {
  14185. noManifestFile();
  14186. }, false);
  14187. try {
  14188. xhr.send();
  14189. }
  14190. catch (ex) {
  14191. BABYLON.Tools.Error("Error on XHR send request.");
  14192. that.callbackManifestChecked(false);
  14193. }
  14194. };
  14195. Database.prototype.openAsync = function (successCallback, errorCallback) {
  14196. var _this = this;
  14197. function handleError() {
  14198. that.isSupported = false;
  14199. if (errorCallback)
  14200. errorCallback();
  14201. }
  14202. var that = this;
  14203. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  14204. // Your browser doesn't support IndexedDB
  14205. this.isSupported = false;
  14206. if (errorCallback)
  14207. errorCallback();
  14208. }
  14209. else {
  14210. // If the DB hasn't been opened or created yet
  14211. if (!this.db) {
  14212. this.hasReachedQuota = false;
  14213. this.isSupported = true;
  14214. var request = this.idbFactory.open("babylonjs", 1);
  14215. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  14216. request.onerror = function (event) {
  14217. handleError();
  14218. };
  14219. // executes when a version change transaction cannot complete due to other active transactions
  14220. request.onblocked = function (event) {
  14221. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  14222. handleError();
  14223. };
  14224. // DB has been opened successfully
  14225. request.onsuccess = function (event) {
  14226. _this.db = request.result;
  14227. successCallback();
  14228. };
  14229. // Initialization of the DB. Creating Scenes & Textures stores
  14230. request.onupgradeneeded = function (event) {
  14231. _this.db = (event.target).result;
  14232. try {
  14233. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  14234. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  14235. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  14236. }
  14237. catch (ex) {
  14238. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  14239. handleError();
  14240. }
  14241. };
  14242. }
  14243. else {
  14244. if (successCallback)
  14245. successCallback();
  14246. }
  14247. }
  14248. };
  14249. Database.prototype.loadImageFromDB = function (url, image) {
  14250. var _this = this;
  14251. var completeURL = BABYLON.Database.ReturnFullUrlLocation(url);
  14252. var saveAndLoadImage = function () {
  14253. if (!_this.hasReachedQuota && _this.db !== null) {
  14254. // the texture is not yet in the DB, let's try to save it
  14255. _this._saveImageIntoDBAsync(completeURL, image);
  14256. }
  14257. else {
  14258. image.src = url;
  14259. }
  14260. };
  14261. if (!this.mustUpdateRessources) {
  14262. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  14263. }
  14264. else {
  14265. saveAndLoadImage();
  14266. }
  14267. };
  14268. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  14269. if (this.isSupported && this.db !== null) {
  14270. var texture;
  14271. var transaction = this.db.transaction(["textures"]);
  14272. transaction.onabort = function (event) {
  14273. image.src = url;
  14274. };
  14275. transaction.oncomplete = function (event) {
  14276. var blobTextureURL;
  14277. if (texture) {
  14278. var URL = window.URL || window.webkitURL;
  14279. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  14280. image.onerror = function () {
  14281. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  14282. image.src = url;
  14283. };
  14284. image.src = blobTextureURL;
  14285. }
  14286. else {
  14287. notInDBCallback();
  14288. }
  14289. };
  14290. var getRequest = transaction.objectStore("textures").get(url);
  14291. getRequest.onsuccess = function (event) {
  14292. texture = (event.target).result;
  14293. };
  14294. getRequest.onerror = function (event) {
  14295. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  14296. image.src = url;
  14297. };
  14298. }
  14299. else {
  14300. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  14301. image.src = url;
  14302. }
  14303. };
  14304. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  14305. var _this = this;
  14306. if (this.isSupported) {
  14307. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  14308. var generateBlobUrl = function () {
  14309. var blobTextureURL;
  14310. if (blob) {
  14311. var URL = window.URL || window.webkitURL;
  14312. try {
  14313. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  14314. }
  14315. catch (ex) {
  14316. blobTextureURL = URL.createObjectURL(blob);
  14317. }
  14318. }
  14319. image.src = blobTextureURL;
  14320. };
  14321. if (BABYLON.Database.isUASupportingBlobStorage) {
  14322. var xhr = new XMLHttpRequest(), blob;
  14323. xhr.open("GET", url, true);
  14324. xhr.responseType = "blob";
  14325. xhr.addEventListener("load", function () {
  14326. if (xhr.status === 200) {
  14327. // Blob as response (XHR2)
  14328. blob = xhr.response;
  14329. var transaction = _this.db.transaction(["textures"], "readwrite");
  14330. // the transaction could abort because of a QuotaExceededError error
  14331. transaction.onabort = function (event) {
  14332. try {
  14333. if (event.srcElement.error.name === "QuotaExceededError") {
  14334. this.hasReachedQuota = true;
  14335. }
  14336. }
  14337. catch (ex) {
  14338. }
  14339. generateBlobUrl();
  14340. };
  14341. transaction.oncomplete = function (event) {
  14342. generateBlobUrl();
  14343. };
  14344. var newTexture = { textureUrl: url, data: blob };
  14345. try {
  14346. // Put the blob into the dabase
  14347. var addRequest = transaction.objectStore("textures").put(newTexture);
  14348. addRequest.onsuccess = function (event) {
  14349. };
  14350. addRequest.onerror = function (event) {
  14351. generateBlobUrl();
  14352. };
  14353. }
  14354. catch (ex) {
  14355. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  14356. if (ex.code === 25) {
  14357. BABYLON.Database.isUASupportingBlobStorage = false;
  14358. }
  14359. image.src = url;
  14360. }
  14361. }
  14362. else {
  14363. image.src = url;
  14364. }
  14365. }, false);
  14366. xhr.addEventListener("error", function (event) {
  14367. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  14368. image.src = url;
  14369. }, false);
  14370. xhr.send();
  14371. }
  14372. else {
  14373. image.src = url;
  14374. }
  14375. }
  14376. else {
  14377. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  14378. image.src = url;
  14379. }
  14380. };
  14381. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  14382. var _this = this;
  14383. var updateVersion = function (event) {
  14384. // the version is not yet in the DB or we need to update it
  14385. _this._saveVersionIntoDBAsync(url, versionLoaded);
  14386. };
  14387. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  14388. };
  14389. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  14390. var _this = this;
  14391. if (this.isSupported) {
  14392. var version;
  14393. try {
  14394. var transaction = this.db.transaction(["versions"]);
  14395. transaction.oncomplete = function (event) {
  14396. if (version) {
  14397. // If the version in the JSON file is > than the version in DB
  14398. if (_this.manifestVersionFound > version.data) {
  14399. _this.mustUpdateRessources = true;
  14400. updateInDBCallback();
  14401. }
  14402. else {
  14403. callback(version.data);
  14404. }
  14405. }
  14406. else {
  14407. _this.mustUpdateRessources = true;
  14408. updateInDBCallback();
  14409. }
  14410. };
  14411. transaction.onabort = function (event) {
  14412. callback(-1);
  14413. };
  14414. var getRequest = transaction.objectStore("versions").get(url);
  14415. getRequest.onsuccess = function (event) {
  14416. version = (event.target).result;
  14417. };
  14418. getRequest.onerror = function (event) {
  14419. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  14420. callback(-1);
  14421. };
  14422. }
  14423. catch (ex) {
  14424. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  14425. callback(-1);
  14426. }
  14427. }
  14428. else {
  14429. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  14430. callback(-1);
  14431. }
  14432. };
  14433. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  14434. var _this = this;
  14435. if (this.isSupported && !this.hasReachedQuota) {
  14436. try {
  14437. // Open a transaction to the database
  14438. var transaction = this.db.transaction(["versions"], "readwrite");
  14439. // the transaction could abort because of a QuotaExceededError error
  14440. transaction.onabort = function (event) {
  14441. try {
  14442. if (event.srcElement.error.name === "QuotaExceededError") {
  14443. _this.hasReachedQuota = true;
  14444. }
  14445. }
  14446. catch (ex) {
  14447. }
  14448. callback(-1);
  14449. };
  14450. transaction.oncomplete = function (event) {
  14451. callback(_this.manifestVersionFound);
  14452. };
  14453. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  14454. // Put the scene into the database
  14455. var addRequest = transaction.objectStore("versions").put(newVersion);
  14456. addRequest.onsuccess = function (event) {
  14457. };
  14458. addRequest.onerror = function (event) {
  14459. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  14460. };
  14461. }
  14462. catch (ex) {
  14463. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  14464. callback(-1);
  14465. }
  14466. }
  14467. else {
  14468. callback(-1);
  14469. }
  14470. };
  14471. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  14472. var _this = this;
  14473. var completeUrl = BABYLON.Database.ReturnFullUrlLocation(url);
  14474. var saveAndLoadFile = function (event) {
  14475. // the scene is not yet in the DB, let's try to save it
  14476. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  14477. };
  14478. this._checkVersionFromDB(completeUrl, function (version) {
  14479. if (version !== -1) {
  14480. if (!_this.mustUpdateRessources) {
  14481. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  14482. }
  14483. else {
  14484. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  14485. }
  14486. }
  14487. else {
  14488. errorCallback();
  14489. }
  14490. });
  14491. };
  14492. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  14493. if (this.isSupported) {
  14494. var targetStore;
  14495. if (url.indexOf(".babylon") !== -1) {
  14496. targetStore = "scenes";
  14497. }
  14498. else {
  14499. targetStore = "textures";
  14500. }
  14501. var file;
  14502. var transaction = this.db.transaction([targetStore]);
  14503. transaction.oncomplete = function (event) {
  14504. if (file) {
  14505. callback(file.data);
  14506. }
  14507. else {
  14508. notInDBCallback();
  14509. }
  14510. };
  14511. transaction.onabort = function (event) {
  14512. notInDBCallback();
  14513. };
  14514. var getRequest = transaction.objectStore(targetStore).get(url);
  14515. getRequest.onsuccess = function (event) {
  14516. file = (event.target).result;
  14517. };
  14518. getRequest.onerror = function (event) {
  14519. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  14520. notInDBCallback();
  14521. };
  14522. }
  14523. else {
  14524. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  14525. callback();
  14526. }
  14527. };
  14528. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  14529. var _this = this;
  14530. if (this.isSupported) {
  14531. var targetStore;
  14532. if (url.indexOf(".babylon") !== -1) {
  14533. targetStore = "scenes";
  14534. }
  14535. else {
  14536. targetStore = "textures";
  14537. }
  14538. // Create XHR
  14539. var xhr = new XMLHttpRequest(), fileData;
  14540. xhr.open("GET", url, true);
  14541. if (useArrayBuffer) {
  14542. xhr.responseType = "arraybuffer";
  14543. }
  14544. xhr.onprogress = progressCallback;
  14545. xhr.addEventListener("load", function () {
  14546. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  14547. // Blob as response (XHR2)
  14548. //fileData = xhr.responseText;
  14549. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  14550. if (!_this.hasReachedQuota) {
  14551. // Open a transaction to the database
  14552. var transaction = _this.db.transaction([targetStore], "readwrite");
  14553. // the transaction could abort because of a QuotaExceededError error
  14554. transaction.onabort = function (event) {
  14555. try {
  14556. if (event.srcElement.error.name === "QuotaExceededError") {
  14557. this.hasReachedQuota = true;
  14558. }
  14559. }
  14560. catch (ex) {
  14561. }
  14562. callback(fileData);
  14563. };
  14564. transaction.oncomplete = function (event) {
  14565. callback(fileData);
  14566. };
  14567. var newFile;
  14568. if (targetStore === "scenes") {
  14569. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  14570. }
  14571. else {
  14572. newFile = { textureUrl: url, data: fileData };
  14573. }
  14574. try {
  14575. // Put the scene into the database
  14576. var addRequest = transaction.objectStore(targetStore).put(newFile);
  14577. addRequest.onsuccess = function (event) {
  14578. };
  14579. addRequest.onerror = function (event) {
  14580. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  14581. };
  14582. }
  14583. catch (ex) {
  14584. callback(fileData);
  14585. }
  14586. }
  14587. else {
  14588. callback(fileData);
  14589. }
  14590. }
  14591. else {
  14592. callback();
  14593. }
  14594. }, false);
  14595. xhr.addEventListener("error", function (event) {
  14596. BABYLON.Tools.Error("error on XHR request.");
  14597. callback();
  14598. }, false);
  14599. xhr.send();
  14600. }
  14601. else {
  14602. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  14603. callback();
  14604. }
  14605. };
  14606. Database.isUASupportingBlobStorage = true;
  14607. Database.parseURL = function (url) {
  14608. var a = document.createElement('a');
  14609. a.href = url;
  14610. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  14611. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  14612. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  14613. return absLocation;
  14614. };
  14615. Database.ReturnFullUrlLocation = function (url) {
  14616. if (url.indexOf("http:/") === -1) {
  14617. return (BABYLON.Database.parseURL(window.location.href) + url);
  14618. }
  14619. else {
  14620. return url;
  14621. }
  14622. };
  14623. return Database;
  14624. })();
  14625. BABYLON.Database = Database;
  14626. })(BABYLON || (BABYLON = {}));
  14627. //# sourceMappingURL=babylon.database.js.mapvar BABYLON;
  14628. (function (BABYLON) {
  14629. var SpriteManager = (function () {
  14630. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon) {
  14631. this.name = name;
  14632. this.cellSize = cellSize;
  14633. this.sprites = new Array();
  14634. this.renderingGroupId = 0;
  14635. this.fogEnabled = true;
  14636. this._vertexDeclaration = [3, 4, 4, 4];
  14637. this._vertexStrideSize = 15 * 4; // 15 floats per sprite (x, y, z, angle, size, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  14638. this._capacity = capacity;
  14639. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false);
  14640. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  14641. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  14642. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  14643. this._scene = scene;
  14644. this._scene.spriteManagers.push(this);
  14645. // VBO
  14646. this._vertexDeclaration = [3, 4, 4, 4];
  14647. this._vertexStrideSize = 15 * 4;
  14648. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  14649. var indices = [];
  14650. var index = 0;
  14651. for (var count = 0; count < capacity; count++) {
  14652. indices.push(index);
  14653. indices.push(index + 1);
  14654. indices.push(index + 2);
  14655. indices.push(index);
  14656. indices.push(index + 2);
  14657. indices.push(index + 3);
  14658. index += 4;
  14659. }
  14660. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  14661. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  14662. // Effects
  14663. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  14664. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  14665. }
  14666. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  14667. var arrayOffset = index * 15;
  14668. if (offsetX == 0)
  14669. offsetX = this._epsilon;
  14670. else if (offsetX == 1)
  14671. offsetX = 1 - this._epsilon;
  14672. if (offsetY == 0)
  14673. offsetY = this._epsilon;
  14674. else if (offsetY == 1)
  14675. offsetY = 1 - this._epsilon;
  14676. this._vertices[arrayOffset] = sprite.position.x;
  14677. this._vertices[arrayOffset + 1] = sprite.position.y;
  14678. this._vertices[arrayOffset + 2] = sprite.position.z;
  14679. this._vertices[arrayOffset + 3] = sprite.angle;
  14680. this._vertices[arrayOffset + 4] = sprite.size;
  14681. this._vertices[arrayOffset + 5] = offsetX;
  14682. this._vertices[arrayOffset + 6] = offsetY;
  14683. this._vertices[arrayOffset + 7] = sprite.invertU ? 1 : 0;
  14684. this._vertices[arrayOffset + 8] = sprite.invertV ? 1 : 0;
  14685. var offset = (sprite.cellIndex / rowSize) >> 0;
  14686. this._vertices[arrayOffset + 9] = sprite.cellIndex - offset * rowSize;
  14687. this._vertices[arrayOffset + 10] = offset;
  14688. // Color
  14689. this._vertices[arrayOffset + 11] = sprite.color.r;
  14690. this._vertices[arrayOffset + 12] = sprite.color.g;
  14691. this._vertices[arrayOffset + 13] = sprite.color.b;
  14692. this._vertices[arrayOffset + 14] = sprite.color.a;
  14693. };
  14694. SpriteManager.prototype.render = function () {
  14695. // Check
  14696. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  14697. return;
  14698. var engine = this._scene.getEngine();
  14699. var baseSize = this._spriteTexture.getBaseSize();
  14700. // Sprites
  14701. var deltaTime = engine.getDeltaTime();
  14702. var max = Math.min(this._capacity, this.sprites.length);
  14703. var rowSize = baseSize.width / this.cellSize;
  14704. var offset = 0;
  14705. for (var index = 0; index < max; index++) {
  14706. var sprite = this.sprites[index];
  14707. if (!sprite) {
  14708. continue;
  14709. }
  14710. sprite._animate(deltaTime);
  14711. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  14712. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  14713. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  14714. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  14715. }
  14716. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  14717. // Render
  14718. var effect = this._effectBase;
  14719. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  14720. effect = this._effectFog;
  14721. }
  14722. engine.enableEffect(effect);
  14723. var viewMatrix = this._scene.getViewMatrix();
  14724. effect.setTexture("diffuseSampler", this._spriteTexture);
  14725. effect.setMatrix("view", viewMatrix);
  14726. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  14727. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  14728. // Fog
  14729. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  14730. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  14731. effect.setColor3("vFogColor", this._scene.fogColor);
  14732. }
  14733. // VBOs
  14734. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  14735. // Draw order
  14736. effect.setBool("alphaTest", true);
  14737. engine.setColorWrite(false);
  14738. engine.draw(true, 0, max * 6);
  14739. engine.setColorWrite(true);
  14740. effect.setBool("alphaTest", false);
  14741. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  14742. engine.draw(true, 0, max * 6);
  14743. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  14744. };
  14745. SpriteManager.prototype.dispose = function () {
  14746. if (this._vertexBuffer) {
  14747. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  14748. this._vertexBuffer = null;
  14749. }
  14750. if (this._indexBuffer) {
  14751. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  14752. this._indexBuffer = null;
  14753. }
  14754. if (this._spriteTexture) {
  14755. this._spriteTexture.dispose();
  14756. this._spriteTexture = null;
  14757. }
  14758. // Remove from scene
  14759. var index = this._scene.spriteManagers.indexOf(this);
  14760. this._scene.spriteManagers.splice(index, 1);
  14761. // Callback
  14762. if (this.onDispose) {
  14763. this.onDispose();
  14764. }
  14765. };
  14766. return SpriteManager;
  14767. })();
  14768. BABYLON.SpriteManager = SpriteManager;
  14769. })(BABYLON || (BABYLON = {}));
  14770. //# sourceMappingURL=babylon.spriteManager.js.mapvar BABYLON;
  14771. (function (BABYLON) {
  14772. var Sprite = (function () {
  14773. function Sprite(name, manager) {
  14774. this.name = name;
  14775. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  14776. this.size = 1.0;
  14777. this.angle = 0;
  14778. this.cellIndex = 0;
  14779. this.invertU = 0;
  14780. this.invertV = 0;
  14781. this.animations = new Array();
  14782. this._animationStarted = false;
  14783. this._loopAnimation = false;
  14784. this._fromIndex = 0;
  14785. this._toIndex = 0;
  14786. this._delay = 0;
  14787. this._direction = 1;
  14788. this._frameCount = 0;
  14789. this._time = 0;
  14790. this._manager = manager;
  14791. this._manager.sprites.push(this);
  14792. this.position = BABYLON.Vector3.Zero();
  14793. }
  14794. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  14795. this._fromIndex = from;
  14796. this._toIndex = to;
  14797. this._loopAnimation = loop;
  14798. this._delay = delay;
  14799. this._animationStarted = true;
  14800. this._direction = from < to ? 1 : -1;
  14801. this.cellIndex = from;
  14802. this._time = 0;
  14803. };
  14804. Sprite.prototype.stopAnimation = function () {
  14805. this._animationStarted = false;
  14806. };
  14807. Sprite.prototype._animate = function (deltaTime) {
  14808. if (!this._animationStarted)
  14809. return;
  14810. this._time += deltaTime;
  14811. if (this._time > this._delay) {
  14812. this._time = this._time % this._delay;
  14813. this.cellIndex += this._direction;
  14814. if (this.cellIndex == this._toIndex) {
  14815. if (this._loopAnimation) {
  14816. this.cellIndex = this._fromIndex;
  14817. }
  14818. else {
  14819. this._animationStarted = false;
  14820. if (this.disposeWhenFinishedAnimating) {
  14821. this.dispose();
  14822. }
  14823. }
  14824. }
  14825. }
  14826. };
  14827. Sprite.prototype.dispose = function () {
  14828. for (var i = 0; i < this._manager.sprites.length; i++) {
  14829. if (this._manager.sprites[i] == this) {
  14830. this._manager.sprites.splice(i, 1);
  14831. }
  14832. }
  14833. };
  14834. return Sprite;
  14835. })();
  14836. BABYLON.Sprite = Sprite;
  14837. })(BABYLON || (BABYLON = {}));
  14838. //# sourceMappingURL=babylon.sprite.js.mapvar BABYLON;
  14839. (function (BABYLON) {
  14840. var Layer = (function () {
  14841. function Layer(name, imgUrl, scene, isBackground, color) {
  14842. this.name = name;
  14843. this._vertexDeclaration = [2];
  14844. this._vertexStrideSize = 2 * 4;
  14845. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  14846. this.isBackground = isBackground === undefined ? true : isBackground;
  14847. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  14848. this._scene = scene;
  14849. this._scene.layers.push(this);
  14850. // VBO
  14851. var vertices = [];
  14852. vertices.push(1, 1);
  14853. vertices.push(-1, 1);
  14854. vertices.push(-1, -1);
  14855. vertices.push(1, -1);
  14856. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  14857. // Indices
  14858. var indices = [];
  14859. indices.push(0);
  14860. indices.push(1);
  14861. indices.push(2);
  14862. indices.push(0);
  14863. indices.push(2);
  14864. indices.push(3);
  14865. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  14866. // Effects
  14867. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  14868. }
  14869. Layer.prototype.render = function () {
  14870. // Check
  14871. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  14872. return;
  14873. var engine = this._scene.getEngine();
  14874. // Render
  14875. engine.enableEffect(this._effect);
  14876. engine.setState(false);
  14877. // Texture
  14878. this._effect.setTexture("textureSampler", this.texture);
  14879. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  14880. // Color
  14881. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  14882. // VBOs
  14883. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  14884. // Draw order
  14885. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  14886. engine.draw(true, 0, 6);
  14887. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  14888. };
  14889. Layer.prototype.dispose = function () {
  14890. if (this._vertexBuffer) {
  14891. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  14892. this._vertexBuffer = null;
  14893. }
  14894. if (this._indexBuffer) {
  14895. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  14896. this._indexBuffer = null;
  14897. }
  14898. if (this.texture) {
  14899. this.texture.dispose();
  14900. this.texture = null;
  14901. }
  14902. // Remove from scene
  14903. var index = this._scene.layers.indexOf(this);
  14904. this._scene.layers.splice(index, 1);
  14905. // Callback
  14906. if (this.onDispose) {
  14907. this.onDispose();
  14908. }
  14909. };
  14910. return Layer;
  14911. })();
  14912. BABYLON.Layer = Layer;
  14913. })(BABYLON || (BABYLON = {}));
  14914. //# sourceMappingURL=babylon.layer.js.mapvar BABYLON;
  14915. (function (BABYLON) {
  14916. var Particle = (function () {
  14917. function Particle() {
  14918. this.position = BABYLON.Vector3.Zero();
  14919. this.direction = BABYLON.Vector3.Zero();
  14920. this.color = new BABYLON.Color4(0, 0, 0, 0);
  14921. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  14922. this.lifeTime = 1.0;
  14923. this.age = 0;
  14924. this.size = 0;
  14925. this.angle = 0;
  14926. this.angularSpeed = 0;
  14927. }
  14928. Particle.prototype.copyTo = function (other) {
  14929. other.position.copyFrom(this.position);
  14930. other.direction.copyFrom(this.direction);
  14931. other.color.copyFrom(this.color);
  14932. other.colorStep.copyFrom(this.colorStep);
  14933. other.lifeTime = this.lifeTime;
  14934. other.age = this.age;
  14935. other.size = this.size;
  14936. other.angle = this.angle;
  14937. other.angularSpeed = this.angularSpeed;
  14938. };
  14939. return Particle;
  14940. })();
  14941. BABYLON.Particle = Particle;
  14942. })(BABYLON || (BABYLON = {}));
  14943. //# sourceMappingURL=babylon.particle.js.mapvar BABYLON;
  14944. (function (BABYLON) {
  14945. var randomNumber = function (min, max) {
  14946. if (min === max) {
  14947. return (min);
  14948. }
  14949. var random = Math.random();
  14950. return ((random * (max - min)) + min);
  14951. };
  14952. var ParticleSystem = (function () {
  14953. function ParticleSystem(name, capacity, scene, customEffect) {
  14954. var _this = this;
  14955. this.name = name;
  14956. this.renderingGroupId = 0;
  14957. this.emitter = null;
  14958. this.emitRate = 10;
  14959. this.manualEmitCount = -1;
  14960. this.updateSpeed = 0.01;
  14961. this.targetStopDuration = 0;
  14962. this.disposeOnStop = false;
  14963. this.minEmitPower = 1;
  14964. this.maxEmitPower = 1;
  14965. this.minLifeTime = 1;
  14966. this.maxLifeTime = 1;
  14967. this.minSize = 1;
  14968. this.maxSize = 1;
  14969. this.minAngularSpeed = 0;
  14970. this.maxAngularSpeed = 0;
  14971. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  14972. this.forceDepthWrite = false;
  14973. this.gravity = BABYLON.Vector3.Zero();
  14974. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  14975. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  14976. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  14977. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  14978. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  14979. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  14980. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  14981. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  14982. this.particles = new Array();
  14983. this._vertexDeclaration = [3, 4, 4];
  14984. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  14985. this._stockParticles = new Array();
  14986. this._newPartsExcess = 0;
  14987. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  14988. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  14989. this._scaledDirection = BABYLON.Vector3.Zero();
  14990. this._scaledGravity = BABYLON.Vector3.Zero();
  14991. this._currentRenderId = -1;
  14992. this._started = false;
  14993. this._stopped = false;
  14994. this._actualFrame = 0;
  14995. this.id = name;
  14996. this._capacity = capacity;
  14997. this._scene = scene;
  14998. this._customEffect = customEffect;
  14999. scene.particleSystems.push(this);
  15000. // VBO
  15001. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  15002. var indices = [];
  15003. var index = 0;
  15004. for (var count = 0; count < capacity; count++) {
  15005. indices.push(index);
  15006. indices.push(index + 1);
  15007. indices.push(index + 2);
  15008. indices.push(index);
  15009. indices.push(index + 2);
  15010. indices.push(index + 3);
  15011. index += 4;
  15012. }
  15013. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  15014. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  15015. // Default behaviors
  15016. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate) {
  15017. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  15018. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  15019. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  15020. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  15021. };
  15022. this.startPositionFunction = function (worldMatrix, positionToUpdate) {
  15023. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  15024. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  15025. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  15026. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  15027. };
  15028. this.updateFunction = function (particles) {
  15029. for (var index = 0; index < particles.length; index++) {
  15030. var particle = particles[index];
  15031. particle.age += _this._scaledUpdateSpeed;
  15032. if (particle.age >= particle.lifeTime) {
  15033. _this.recycleParticle(particle);
  15034. index--;
  15035. continue;
  15036. }
  15037. else {
  15038. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  15039. particle.color.addInPlace(_this._scaledColorStep);
  15040. if (particle.color.a < 0)
  15041. particle.color.a = 0;
  15042. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  15043. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  15044. particle.position.addInPlace(_this._scaledDirection);
  15045. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  15046. particle.direction.addInPlace(_this._scaledGravity);
  15047. }
  15048. }
  15049. };
  15050. }
  15051. ParticleSystem.prototype.recycleParticle = function (particle) {
  15052. var lastParticle = this.particles.pop();
  15053. if (lastParticle !== particle) {
  15054. lastParticle.copyTo(particle);
  15055. this._stockParticles.push(lastParticle);
  15056. }
  15057. };
  15058. ParticleSystem.prototype.getCapacity = function () {
  15059. return this._capacity;
  15060. };
  15061. ParticleSystem.prototype.isAlive = function () {
  15062. return this._alive;
  15063. };
  15064. ParticleSystem.prototype.isStarted = function () {
  15065. return this._started;
  15066. };
  15067. ParticleSystem.prototype.start = function () {
  15068. this._started = true;
  15069. this._stopped = false;
  15070. this._actualFrame = 0;
  15071. };
  15072. ParticleSystem.prototype.stop = function () {
  15073. this._stopped = true;
  15074. };
  15075. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  15076. var offset = index * 11;
  15077. this._vertices[offset] = particle.position.x;
  15078. this._vertices[offset + 1] = particle.position.y;
  15079. this._vertices[offset + 2] = particle.position.z;
  15080. this._vertices[offset + 3] = particle.color.r;
  15081. this._vertices[offset + 4] = particle.color.g;
  15082. this._vertices[offset + 5] = particle.color.b;
  15083. this._vertices[offset + 6] = particle.color.a;
  15084. this._vertices[offset + 7] = particle.angle;
  15085. this._vertices[offset + 8] = particle.size;
  15086. this._vertices[offset + 9] = offsetX;
  15087. this._vertices[offset + 10] = offsetY;
  15088. };
  15089. ParticleSystem.prototype._update = function (newParticles) {
  15090. // Update current
  15091. this._alive = this.particles.length > 0;
  15092. this.updateFunction(this.particles);
  15093. // Add new ones
  15094. var worldMatrix;
  15095. if (this.emitter.position) {
  15096. worldMatrix = this.emitter.getWorldMatrix();
  15097. }
  15098. else {
  15099. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  15100. }
  15101. for (var index = 0; index < newParticles; index++) {
  15102. if (this.particles.length === this._capacity) {
  15103. break;
  15104. }
  15105. if (this._stockParticles.length !== 0) {
  15106. var particle = this._stockParticles.pop();
  15107. particle.age = 0;
  15108. }
  15109. else {
  15110. particle = new BABYLON.Particle();
  15111. }
  15112. this.particles.push(particle);
  15113. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  15114. this.startDirectionFunction(emitPower, worldMatrix, particle.direction);
  15115. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  15116. particle.size = randomNumber(this.minSize, this.maxSize);
  15117. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  15118. this.startPositionFunction(worldMatrix, particle.position);
  15119. var step = randomNumber(0, 1.0);
  15120. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  15121. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  15122. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  15123. }
  15124. };
  15125. ParticleSystem.prototype._getEffect = function () {
  15126. if (this._customEffect) {
  15127. return this._customEffect;
  15128. }
  15129. ;
  15130. var defines = [];
  15131. if (this._scene.clipPlane) {
  15132. defines.push("#define CLIPPLANE");
  15133. }
  15134. // Effect
  15135. var join = defines.join("\n");
  15136. if (this._cachedDefines !== join) {
  15137. this._cachedDefines = join;
  15138. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  15139. }
  15140. return this._effect;
  15141. };
  15142. ParticleSystem.prototype.animate = function () {
  15143. if (!this._started)
  15144. return;
  15145. var effect = this._getEffect();
  15146. // Check
  15147. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  15148. return;
  15149. if (this._currentRenderId === this._scene.getRenderId()) {
  15150. return;
  15151. }
  15152. this._currentRenderId = this._scene.getRenderId();
  15153. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  15154. // determine the number of particles we need to create
  15155. var emitCout;
  15156. if (this.manualEmitCount > -1) {
  15157. emitCout = this.manualEmitCount;
  15158. this.manualEmitCount = 0;
  15159. }
  15160. else {
  15161. emitCout = this.emitRate;
  15162. }
  15163. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  15164. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  15165. if (this._newPartsExcess > 1.0) {
  15166. newParticles += this._newPartsExcess >> 0;
  15167. this._newPartsExcess -= this._newPartsExcess >> 0;
  15168. }
  15169. this._alive = false;
  15170. if (!this._stopped) {
  15171. this._actualFrame += this._scaledUpdateSpeed;
  15172. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  15173. this.stop();
  15174. }
  15175. else {
  15176. newParticles = 0;
  15177. }
  15178. this._update(newParticles);
  15179. // Stopped?
  15180. if (this._stopped) {
  15181. if (!this._alive) {
  15182. this._started = false;
  15183. if (this.disposeOnStop) {
  15184. this._scene._toBeDisposed.push(this);
  15185. }
  15186. }
  15187. }
  15188. // Update VBO
  15189. var offset = 0;
  15190. for (var index = 0; index < this.particles.length; index++) {
  15191. var particle = this.particles[index];
  15192. this._appendParticleVertex(offset++, particle, 0, 0);
  15193. this._appendParticleVertex(offset++, particle, 1, 0);
  15194. this._appendParticleVertex(offset++, particle, 1, 1);
  15195. this._appendParticleVertex(offset++, particle, 0, 1);
  15196. }
  15197. var engine = this._scene.getEngine();
  15198. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  15199. };
  15200. ParticleSystem.prototype.render = function () {
  15201. var effect = this._getEffect();
  15202. // Check
  15203. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  15204. return 0;
  15205. var engine = this._scene.getEngine();
  15206. // Render
  15207. engine.enableEffect(effect);
  15208. engine.setState(false);
  15209. var viewMatrix = this._scene.getViewMatrix();
  15210. effect.setTexture("diffuseSampler", this.particleTexture);
  15211. effect.setMatrix("view", viewMatrix);
  15212. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  15213. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  15214. if (this._scene.clipPlane) {
  15215. var clipPlane = this._scene.clipPlane;
  15216. var invView = viewMatrix.clone();
  15217. invView.invert();
  15218. effect.setMatrix("invView", invView);
  15219. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  15220. }
  15221. // VBOs
  15222. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  15223. // Draw order
  15224. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  15225. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  15226. }
  15227. else {
  15228. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  15229. }
  15230. if (this.forceDepthWrite) {
  15231. engine.setDepthWrite(true);
  15232. }
  15233. engine.draw(true, 0, this.particles.length * 6);
  15234. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  15235. return this.particles.length;
  15236. };
  15237. ParticleSystem.prototype.dispose = function () {
  15238. if (this._vertexBuffer) {
  15239. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  15240. this._vertexBuffer = null;
  15241. }
  15242. if (this._indexBuffer) {
  15243. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  15244. this._indexBuffer = null;
  15245. }
  15246. if (this.particleTexture) {
  15247. this.particleTexture.dispose();
  15248. this.particleTexture = null;
  15249. }
  15250. // Remove from scene
  15251. var index = this._scene.particleSystems.indexOf(this);
  15252. this._scene.particleSystems.splice(index, 1);
  15253. // Callback
  15254. if (this.onDispose) {
  15255. this.onDispose();
  15256. }
  15257. };
  15258. // Clone
  15259. ParticleSystem.prototype.clone = function (name, newEmitter) {
  15260. var result = new ParticleSystem(name, this._capacity, this._scene);
  15261. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  15262. if (newEmitter === undefined) {
  15263. newEmitter = this.emitter;
  15264. }
  15265. result.emitter = newEmitter;
  15266. if (this.particleTexture) {
  15267. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  15268. }
  15269. result.start();
  15270. return result;
  15271. };
  15272. // Statics
  15273. ParticleSystem.BLENDMODE_ONEONE = 0;
  15274. ParticleSystem.BLENDMODE_STANDARD = 1;
  15275. return ParticleSystem;
  15276. })();
  15277. BABYLON.ParticleSystem = ParticleSystem;
  15278. })(BABYLON || (BABYLON = {}));
  15279. //# sourceMappingURL=babylon.particleSystem.js.mapvar BABYLON;
  15280. (function (BABYLON) {
  15281. var Animation = (function () {
  15282. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  15283. this.name = name;
  15284. this.targetProperty = targetProperty;
  15285. this.framePerSecond = framePerSecond;
  15286. this.dataType = dataType;
  15287. this.loopMode = loopMode;
  15288. this._offsetsCache = {};
  15289. this._highLimitsCache = {};
  15290. this._stopped = false;
  15291. this.targetPropertyPath = targetProperty.split(".");
  15292. this.dataType = dataType;
  15293. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  15294. }
  15295. Animation.CreateAndStartAnimation = function (name, mesh, tartgetProperty, framePerSecond, totalFrame, from, to, loopMode) {
  15296. var dataType = undefined;
  15297. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  15298. dataType = Animation.ANIMATIONTYPE_FLOAT;
  15299. }
  15300. else if (from instanceof BABYLON.Quaternion) {
  15301. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  15302. }
  15303. else if (from instanceof BABYLON.Vector3) {
  15304. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  15305. }
  15306. else if (from instanceof BABYLON.Vector2) {
  15307. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  15308. }
  15309. else if (from instanceof BABYLON.Color3) {
  15310. dataType = Animation.ANIMATIONTYPE_COLOR3;
  15311. }
  15312. if (dataType == undefined) {
  15313. return;
  15314. }
  15315. var animation = new Animation(name, tartgetProperty, framePerSecond, dataType, loopMode);
  15316. var keys = [];
  15317. keys.push({ frame: 0, value: from });
  15318. keys.push({ frame: totalFrame, value: to });
  15319. animation.setKeys(keys);
  15320. mesh.animations.push(animation);
  15321. return mesh.getScene().beginAnimation(mesh, 0, totalFrame, (animation.loopMode === 1));
  15322. };
  15323. // Methods
  15324. Animation.prototype.isStopped = function () {
  15325. return this._stopped;
  15326. };
  15327. Animation.prototype.getKeys = function () {
  15328. return this._keys;
  15329. };
  15330. Animation.prototype.getEasingFunction = function () {
  15331. return this._easingFunction;
  15332. };
  15333. Animation.prototype.setEasingFunction = function (easingFunction) {
  15334. this._easingFunction = easingFunction;
  15335. };
  15336. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  15337. return startValue + (endValue - startValue) * gradient;
  15338. };
  15339. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  15340. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  15341. };
  15342. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  15343. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  15344. };
  15345. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  15346. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  15347. };
  15348. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  15349. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  15350. };
  15351. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  15352. var startScale = new BABYLON.Vector3(0, 0, 0);
  15353. var startRotation = new BABYLON.Quaternion();
  15354. var startTranslation = new BABYLON.Vector3(0, 0, 0);
  15355. startValue.decompose(startScale, startRotation, startTranslation);
  15356. var endScale = new BABYLON.Vector3(0, 0, 0);
  15357. var endRotation = new BABYLON.Quaternion();
  15358. var endTranslation = new BABYLON.Vector3(0, 0, 0);
  15359. endValue.decompose(endScale, endRotation, endTranslation);
  15360. var resultScale = this.vector3InterpolateFunction(startScale, endScale, gradient);
  15361. var resultRotation = this.quaternionInterpolateFunction(startRotation, endRotation, gradient);
  15362. var resultTranslation = this.vector3InterpolateFunction(startTranslation, endTranslation, gradient);
  15363. var result = BABYLON.Matrix.Compose(resultScale, resultRotation, resultTranslation);
  15364. return result;
  15365. };
  15366. Animation.prototype.clone = function () {
  15367. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  15368. clone.setKeys(this._keys);
  15369. return clone;
  15370. };
  15371. Animation.prototype.setKeys = function (values) {
  15372. this._keys = values.slice(0);
  15373. this._offsetsCache = {};
  15374. this._highLimitsCache = {};
  15375. };
  15376. Animation.prototype._getKeyValue = function (value) {
  15377. if (typeof value === "function") {
  15378. return value();
  15379. }
  15380. return value;
  15381. };
  15382. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  15383. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  15384. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  15385. }
  15386. this.currentFrame = currentFrame;
  15387. for (var key = 0; key < this._keys.length; key++) {
  15388. // for each frame, we need the key just before the frame superior
  15389. if (this._keys[key + 1].frame >= currentFrame) {
  15390. var startValue = this._getKeyValue(this._keys[key].value);
  15391. var endValue = this._getKeyValue(this._keys[key + 1].value);
  15392. // gradient : percent of currentFrame between the frame inf and the frame sup
  15393. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  15394. // check for easingFunction and correction of gradient
  15395. if (this._easingFunction != null) {
  15396. gradient = this._easingFunction.ease(gradient);
  15397. }
  15398. switch (this.dataType) {
  15399. case Animation.ANIMATIONTYPE_FLOAT:
  15400. switch (loopMode) {
  15401. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15402. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15403. return this.floatInterpolateFunction(startValue, endValue, gradient);
  15404. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15405. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  15406. }
  15407. break;
  15408. case Animation.ANIMATIONTYPE_QUATERNION:
  15409. var quaternion = null;
  15410. switch (loopMode) {
  15411. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15412. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15413. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  15414. break;
  15415. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15416. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  15417. break;
  15418. }
  15419. return quaternion;
  15420. case Animation.ANIMATIONTYPE_VECTOR3:
  15421. switch (loopMode) {
  15422. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15423. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15424. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  15425. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15426. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  15427. }
  15428. case Animation.ANIMATIONTYPE_VECTOR2:
  15429. switch (loopMode) {
  15430. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15431. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15432. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  15433. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15434. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  15435. }
  15436. case Animation.ANIMATIONTYPE_COLOR3:
  15437. switch (loopMode) {
  15438. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15439. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15440. return this.color3InterpolateFunction(startValue, endValue, gradient);
  15441. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15442. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  15443. }
  15444. case Animation.ANIMATIONTYPE_MATRIX:
  15445. switch (loopMode) {
  15446. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15447. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15448. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15449. return startValue;
  15450. }
  15451. default:
  15452. break;
  15453. }
  15454. break;
  15455. }
  15456. }
  15457. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  15458. };
  15459. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  15460. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  15461. this._stopped = true;
  15462. return false;
  15463. }
  15464. var returnValue = true;
  15465. // Adding a start key at frame 0 if missing
  15466. if (this._keys[0].frame !== 0) {
  15467. var newKey = { frame: 0, value: this._keys[0].value };
  15468. this._keys.splice(0, 0, newKey);
  15469. }
  15470. // Check limits
  15471. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  15472. from = this._keys[0].frame;
  15473. }
  15474. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  15475. to = this._keys[this._keys.length - 1].frame;
  15476. }
  15477. // Compute ratio
  15478. var range = to - from;
  15479. var offsetValue;
  15480. // ratio represents the frame delta between from and to
  15481. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  15482. var highLimitValue = 0;
  15483. if (ratio > range && !loop) {
  15484. returnValue = false;
  15485. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  15486. }
  15487. else {
  15488. // Get max value if required
  15489. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  15490. var keyOffset = to.toString() + from.toString();
  15491. if (!this._offsetsCache[keyOffset]) {
  15492. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  15493. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  15494. switch (this.dataType) {
  15495. case Animation.ANIMATIONTYPE_FLOAT:
  15496. this._offsetsCache[keyOffset] = toValue - fromValue;
  15497. break;
  15498. case Animation.ANIMATIONTYPE_QUATERNION:
  15499. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  15500. break;
  15501. case Animation.ANIMATIONTYPE_VECTOR3:
  15502. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  15503. case Animation.ANIMATIONTYPE_VECTOR2:
  15504. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  15505. case Animation.ANIMATIONTYPE_COLOR3:
  15506. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  15507. default:
  15508. break;
  15509. }
  15510. this._highLimitsCache[keyOffset] = toValue;
  15511. }
  15512. highLimitValue = this._highLimitsCache[keyOffset];
  15513. offsetValue = this._offsetsCache[keyOffset];
  15514. }
  15515. }
  15516. if (offsetValue === undefined) {
  15517. switch (this.dataType) {
  15518. case Animation.ANIMATIONTYPE_FLOAT:
  15519. offsetValue = 0;
  15520. break;
  15521. case Animation.ANIMATIONTYPE_QUATERNION:
  15522. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  15523. break;
  15524. case Animation.ANIMATIONTYPE_VECTOR3:
  15525. offsetValue = BABYLON.Vector3.Zero();
  15526. break;
  15527. case Animation.ANIMATIONTYPE_VECTOR2:
  15528. offsetValue = BABYLON.Vector2.Zero();
  15529. break;
  15530. case Animation.ANIMATIONTYPE_COLOR3:
  15531. offsetValue = BABYLON.Color3.Black();
  15532. }
  15533. }
  15534. // Compute value
  15535. var repeatCount = (ratio / range) >> 0;
  15536. var currentFrame = returnValue ? from + ratio % range : to;
  15537. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  15538. // Set value
  15539. if (this.targetPropertyPath.length > 1) {
  15540. var property = this._target[this.targetPropertyPath[0]];
  15541. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  15542. property = property[this.targetPropertyPath[index]];
  15543. }
  15544. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  15545. }
  15546. else {
  15547. this._target[this.targetPropertyPath[0]] = currentValue;
  15548. }
  15549. if (this._target.markAsDirty) {
  15550. this._target.markAsDirty(this.targetProperty);
  15551. }
  15552. if (!returnValue) {
  15553. this._stopped = true;
  15554. }
  15555. return returnValue;
  15556. };
  15557. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  15558. get: function () {
  15559. return Animation._ANIMATIONTYPE_FLOAT;
  15560. },
  15561. enumerable: true,
  15562. configurable: true
  15563. });
  15564. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  15565. get: function () {
  15566. return Animation._ANIMATIONTYPE_VECTOR3;
  15567. },
  15568. enumerable: true,
  15569. configurable: true
  15570. });
  15571. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  15572. get: function () {
  15573. return Animation._ANIMATIONTYPE_VECTOR2;
  15574. },
  15575. enumerable: true,
  15576. configurable: true
  15577. });
  15578. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  15579. get: function () {
  15580. return Animation._ANIMATIONTYPE_QUATERNION;
  15581. },
  15582. enumerable: true,
  15583. configurable: true
  15584. });
  15585. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  15586. get: function () {
  15587. return Animation._ANIMATIONTYPE_MATRIX;
  15588. },
  15589. enumerable: true,
  15590. configurable: true
  15591. });
  15592. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  15593. get: function () {
  15594. return Animation._ANIMATIONTYPE_COLOR3;
  15595. },
  15596. enumerable: true,
  15597. configurable: true
  15598. });
  15599. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  15600. get: function () {
  15601. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  15602. },
  15603. enumerable: true,
  15604. configurable: true
  15605. });
  15606. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  15607. get: function () {
  15608. return Animation._ANIMATIONLOOPMODE_CYCLE;
  15609. },
  15610. enumerable: true,
  15611. configurable: true
  15612. });
  15613. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  15614. get: function () {
  15615. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  15616. },
  15617. enumerable: true,
  15618. configurable: true
  15619. });
  15620. // Statics
  15621. Animation._ANIMATIONTYPE_FLOAT = 0;
  15622. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  15623. Animation._ANIMATIONTYPE_QUATERNION = 2;
  15624. Animation._ANIMATIONTYPE_MATRIX = 3;
  15625. Animation._ANIMATIONTYPE_COLOR3 = 4;
  15626. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  15627. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  15628. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  15629. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  15630. return Animation;
  15631. })();
  15632. BABYLON.Animation = Animation;
  15633. })(BABYLON || (BABYLON = {}));
  15634. //# sourceMappingURL=babylon.animation.js.mapvar BABYLON;
  15635. (function (BABYLON) {
  15636. var Animatable = (function () {
  15637. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  15638. if (fromFrame === void 0) { fromFrame = 0; }
  15639. if (toFrame === void 0) { toFrame = 100; }
  15640. if (loopAnimation === void 0) { loopAnimation = false; }
  15641. if (speedRatio === void 0) { speedRatio = 1.0; }
  15642. this.target = target;
  15643. this.fromFrame = fromFrame;
  15644. this.toFrame = toFrame;
  15645. this.loopAnimation = loopAnimation;
  15646. this.speedRatio = speedRatio;
  15647. this.onAnimationEnd = onAnimationEnd;
  15648. this._animations = new Array();
  15649. this._paused = false;
  15650. this.animationStarted = false;
  15651. if (animations) {
  15652. this.appendAnimations(target, animations);
  15653. }
  15654. this._scene = scene;
  15655. scene._activeAnimatables.push(this);
  15656. }
  15657. // Methods
  15658. Animatable.prototype.appendAnimations = function (target, animations) {
  15659. for (var index = 0; index < animations.length; index++) {
  15660. var animation = animations[index];
  15661. animation._target = target;
  15662. this._animations.push(animation);
  15663. }
  15664. };
  15665. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  15666. var animations = this._animations;
  15667. for (var index = 0; index < animations.length; index++) {
  15668. if (animations[index].targetProperty === property) {
  15669. return animations[index];
  15670. }
  15671. }
  15672. return null;
  15673. };
  15674. Animatable.prototype.pause = function () {
  15675. if (this._paused) {
  15676. return;
  15677. }
  15678. this._paused = true;
  15679. };
  15680. Animatable.prototype.restart = function () {
  15681. this._paused = false;
  15682. };
  15683. Animatable.prototype.stop = function () {
  15684. var index = this._scene._activeAnimatables.indexOf(this);
  15685. if (index > -1) {
  15686. this._scene._activeAnimatables.splice(index, 1);
  15687. }
  15688. if (this.onAnimationEnd) {
  15689. this.onAnimationEnd();
  15690. }
  15691. };
  15692. Animatable.prototype._animate = function (delay) {
  15693. if (this._paused) {
  15694. if (!this._pausedDelay) {
  15695. this._pausedDelay = delay;
  15696. }
  15697. return true;
  15698. }
  15699. if (!this._localDelayOffset) {
  15700. this._localDelayOffset = delay;
  15701. }
  15702. else if (this._pausedDelay) {
  15703. this._localDelayOffset += delay - this._pausedDelay;
  15704. this._pausedDelay = null;
  15705. }
  15706. // Animating
  15707. var running = false;
  15708. var animations = this._animations;
  15709. for (var index = 0; index < animations.length; index++) {
  15710. var animation = animations[index];
  15711. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  15712. running = running || isRunning;
  15713. }
  15714. if (!running && this.onAnimationEnd) {
  15715. this.onAnimationEnd();
  15716. }
  15717. return running;
  15718. };
  15719. return Animatable;
  15720. })();
  15721. BABYLON.Animatable = Animatable;
  15722. })(BABYLON || (BABYLON = {}));
  15723. //# sourceMappingURL=babylon.animatable.js.map
  15724. var BABYLON;
  15725. (function (BABYLON) {
  15726. var EasingFunction = (function () {
  15727. function EasingFunction() {
  15728. // Properties
  15729. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  15730. }
  15731. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  15732. get: function () {
  15733. return EasingFunction._EASINGMODE_EASEIN;
  15734. },
  15735. enumerable: true,
  15736. configurable: true
  15737. });
  15738. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  15739. get: function () {
  15740. return EasingFunction._EASINGMODE_EASEOUT;
  15741. },
  15742. enumerable: true,
  15743. configurable: true
  15744. });
  15745. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  15746. get: function () {
  15747. return EasingFunction._EASINGMODE_EASEINOUT;
  15748. },
  15749. enumerable: true,
  15750. configurable: true
  15751. });
  15752. EasingFunction.prototype.setEasingMode = function (easingMode) {
  15753. var n = Math.min(Math.max(easingMode, 0), 2);
  15754. this._easingMode = n;
  15755. };
  15756. EasingFunction.prototype.getEasingMode = function () {
  15757. return this._easingMode;
  15758. };
  15759. EasingFunction.prototype.easeInCore = function (gradient) {
  15760. throw new Error('You must implement this method');
  15761. };
  15762. EasingFunction.prototype.ease = function (gradient) {
  15763. switch (this._easingMode) {
  15764. case EasingFunction.EASINGMODE_EASEIN:
  15765. return this.easeInCore(gradient);
  15766. case EasingFunction.EASINGMODE_EASEOUT:
  15767. return (1 - this.easeInCore(1 - gradient));
  15768. }
  15769. if (gradient >= 0.5) {
  15770. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  15771. }
  15772. return (this.easeInCore(gradient * 2) * 0.5);
  15773. };
  15774. //Statics
  15775. EasingFunction._EASINGMODE_EASEIN = 0;
  15776. EasingFunction._EASINGMODE_EASEOUT = 1;
  15777. EasingFunction._EASINGMODE_EASEINOUT = 2;
  15778. return EasingFunction;
  15779. })();
  15780. BABYLON.EasingFunction = EasingFunction;
  15781. var CircleEase = (function (_super) {
  15782. __extends(CircleEase, _super);
  15783. function CircleEase() {
  15784. _super.apply(this, arguments);
  15785. }
  15786. CircleEase.prototype.easeInCore = function (gradient) {
  15787. gradient = Math.max(0, Math.min(1, gradient));
  15788. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  15789. };
  15790. return CircleEase;
  15791. })(EasingFunction);
  15792. BABYLON.CircleEase = CircleEase;
  15793. var BackEase = (function (_super) {
  15794. __extends(BackEase, _super);
  15795. function BackEase(amplitude) {
  15796. if (amplitude === void 0) { amplitude = 1; }
  15797. _super.call(this);
  15798. this.amplitude = amplitude;
  15799. }
  15800. BackEase.prototype.easeInCore = function (gradient) {
  15801. var num = Math.max(0, this.amplitude);
  15802. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  15803. };
  15804. return BackEase;
  15805. })(EasingFunction);
  15806. BABYLON.BackEase = BackEase;
  15807. var BounceEase = (function (_super) {
  15808. __extends(BounceEase, _super);
  15809. function BounceEase(bounces, bounciness) {
  15810. if (bounces === void 0) { bounces = 3; }
  15811. if (bounciness === void 0) { bounciness = 2; }
  15812. _super.call(this);
  15813. this.bounces = bounces;
  15814. this.bounciness = bounciness;
  15815. }
  15816. BounceEase.prototype.easeInCore = function (gradient) {
  15817. var y = Math.max(0.0, this.bounces);
  15818. var bounciness = this.bounciness;
  15819. if (bounciness <= 1.0) {
  15820. bounciness = 1.001;
  15821. }
  15822. var num9 = Math.pow(bounciness, y);
  15823. var num5 = 1.0 - bounciness;
  15824. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  15825. var num15 = gradient * num4;
  15826. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  15827. var num3 = Math.floor(num65);
  15828. var num13 = num3 + 1.0;
  15829. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  15830. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  15831. var num7 = (num8 + num12) * 0.5;
  15832. var num6 = gradient - num7;
  15833. var num2 = num7 - num8;
  15834. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  15835. };
  15836. return BounceEase;
  15837. })(EasingFunction);
  15838. BABYLON.BounceEase = BounceEase;
  15839. var CubicEase = (function (_super) {
  15840. __extends(CubicEase, _super);
  15841. function CubicEase() {
  15842. _super.apply(this, arguments);
  15843. }
  15844. CubicEase.prototype.easeInCore = function (gradient) {
  15845. return (gradient * gradient * gradient);
  15846. };
  15847. return CubicEase;
  15848. })(EasingFunction);
  15849. BABYLON.CubicEase = CubicEase;
  15850. var ElasticEase = (function (_super) {
  15851. __extends(ElasticEase, _super);
  15852. function ElasticEase(oscillations, springiness) {
  15853. if (oscillations === void 0) { oscillations = 3; }
  15854. if (springiness === void 0) { springiness = 3; }
  15855. _super.call(this);
  15856. this.oscillations = oscillations;
  15857. this.springiness = springiness;
  15858. }
  15859. ElasticEase.prototype.easeInCore = function (gradient) {
  15860. var num2;
  15861. var num3 = Math.max(0.0, this.oscillations);
  15862. var num = Math.max(0.0, this.springiness);
  15863. if (num == 0) {
  15864. num2 = gradient;
  15865. }
  15866. else {
  15867. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  15868. }
  15869. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  15870. };
  15871. return ElasticEase;
  15872. })(EasingFunction);
  15873. BABYLON.ElasticEase = ElasticEase;
  15874. var ExponentialEase = (function (_super) {
  15875. __extends(ExponentialEase, _super);
  15876. function ExponentialEase(exponent) {
  15877. if (exponent === void 0) { exponent = 2; }
  15878. _super.call(this);
  15879. this.exponent = exponent;
  15880. }
  15881. ExponentialEase.prototype.easeInCore = function (gradient) {
  15882. if (this.exponent <= 0) {
  15883. return gradient;
  15884. }
  15885. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  15886. };
  15887. return ExponentialEase;
  15888. })(EasingFunction);
  15889. BABYLON.ExponentialEase = ExponentialEase;
  15890. var PowerEase = (function (_super) {
  15891. __extends(PowerEase, _super);
  15892. function PowerEase(power) {
  15893. if (power === void 0) { power = 2; }
  15894. _super.call(this);
  15895. this.power = power;
  15896. }
  15897. PowerEase.prototype.easeInCore = function (gradient) {
  15898. var y = Math.max(0.0, this.power);
  15899. return Math.pow(gradient, y);
  15900. };
  15901. return PowerEase;
  15902. })(EasingFunction);
  15903. BABYLON.PowerEase = PowerEase;
  15904. var QuadraticEase = (function (_super) {
  15905. __extends(QuadraticEase, _super);
  15906. function QuadraticEase() {
  15907. _super.apply(this, arguments);
  15908. }
  15909. QuadraticEase.prototype.easeInCore = function (gradient) {
  15910. return (gradient * gradient);
  15911. };
  15912. return QuadraticEase;
  15913. })(EasingFunction);
  15914. BABYLON.QuadraticEase = QuadraticEase;
  15915. var QuarticEase = (function (_super) {
  15916. __extends(QuarticEase, _super);
  15917. function QuarticEase() {
  15918. _super.apply(this, arguments);
  15919. }
  15920. QuarticEase.prototype.easeInCore = function (gradient) {
  15921. return (gradient * gradient * gradient * gradient);
  15922. };
  15923. return QuarticEase;
  15924. })(EasingFunction);
  15925. BABYLON.QuarticEase = QuarticEase;
  15926. var QuinticEase = (function (_super) {
  15927. __extends(QuinticEase, _super);
  15928. function QuinticEase() {
  15929. _super.apply(this, arguments);
  15930. }
  15931. QuinticEase.prototype.easeInCore = function (gradient) {
  15932. return (gradient * gradient * gradient * gradient * gradient);
  15933. };
  15934. return QuinticEase;
  15935. })(EasingFunction);
  15936. BABYLON.QuinticEase = QuinticEase;
  15937. var SineEase = (function (_super) {
  15938. __extends(SineEase, _super);
  15939. function SineEase() {
  15940. _super.apply(this, arguments);
  15941. }
  15942. SineEase.prototype.easeInCore = function (gradient) {
  15943. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  15944. };
  15945. return SineEase;
  15946. })(EasingFunction);
  15947. BABYLON.SineEase = SineEase;
  15948. var BezierCurveEase = (function (_super) {
  15949. __extends(BezierCurveEase, _super);
  15950. function BezierCurveEase(x1, y1, x2, y2) {
  15951. if (x1 === void 0) { x1 = 0; }
  15952. if (y1 === void 0) { y1 = 0; }
  15953. if (x2 === void 0) { x2 = 1; }
  15954. if (y2 === void 0) { y2 = 1; }
  15955. _super.call(this);
  15956. this.x1 = x1;
  15957. this.y1 = y1;
  15958. this.x2 = x2;
  15959. this.y2 = y2;
  15960. }
  15961. BezierCurveEase.prototype.easeInCore = function (gradient) {
  15962. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  15963. };
  15964. return BezierCurveEase;
  15965. })(EasingFunction);
  15966. BABYLON.BezierCurveEase = BezierCurveEase;
  15967. })(BABYLON || (BABYLON = {}));
  15968. //# sourceMappingURL=babylon.easing.js.mapvar BABYLON;
  15969. (function (BABYLON) {
  15970. var Octree = (function () {
  15971. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  15972. if (maxDepth === void 0) { maxDepth = 2; }
  15973. this.maxDepth = maxDepth;
  15974. this.dynamicContent = new Array();
  15975. this._maxBlockCapacity = maxBlockCapacity || 64;
  15976. this._selectionContent = new BABYLON.SmartArray(1024);
  15977. this._creationFunc = creationFunc;
  15978. }
  15979. // Methods
  15980. Octree.prototype.update = function (worldMin, worldMax, entries) {
  15981. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  15982. };
  15983. Octree.prototype.addMesh = function (entry) {
  15984. for (var index = 0; index < this.blocks.length; index++) {
  15985. var block = this.blocks[index];
  15986. block.addEntry(entry);
  15987. }
  15988. };
  15989. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  15990. this._selectionContent.reset();
  15991. for (var index = 0; index < this.blocks.length; index++) {
  15992. var block = this.blocks[index];
  15993. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  15994. }
  15995. if (allowDuplicate) {
  15996. this._selectionContent.concat(this.dynamicContent);
  15997. }
  15998. else {
  15999. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  16000. }
  16001. return this._selectionContent;
  16002. };
  16003. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  16004. this._selectionContent.reset();
  16005. for (var index = 0; index < this.blocks.length; index++) {
  16006. var block = this.blocks[index];
  16007. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  16008. }
  16009. if (allowDuplicate) {
  16010. this._selectionContent.concat(this.dynamicContent);
  16011. }
  16012. else {
  16013. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  16014. }
  16015. return this._selectionContent;
  16016. };
  16017. Octree.prototype.intersectsRay = function (ray) {
  16018. this._selectionContent.reset();
  16019. for (var index = 0; index < this.blocks.length; index++) {
  16020. var block = this.blocks[index];
  16021. block.intersectsRay(ray, this._selectionContent);
  16022. }
  16023. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  16024. return this._selectionContent;
  16025. };
  16026. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  16027. target.blocks = new Array();
  16028. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  16029. for (var x = 0; x < 2; x++) {
  16030. for (var y = 0; y < 2; y++) {
  16031. for (var z = 0; z < 2; z++) {
  16032. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  16033. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  16034. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  16035. block.addEntries(entries);
  16036. target.blocks.push(block);
  16037. }
  16038. }
  16039. }
  16040. };
  16041. Octree.CreationFuncForMeshes = function (entry, block) {
  16042. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  16043. block.entries.push(entry);
  16044. }
  16045. };
  16046. Octree.CreationFuncForSubMeshes = function (entry, block) {
  16047. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  16048. block.entries.push(entry);
  16049. }
  16050. };
  16051. return Octree;
  16052. })();
  16053. BABYLON.Octree = Octree;
  16054. })(BABYLON || (BABYLON = {}));
  16055. //# sourceMappingURL=babylon.octree.js.mapvar BABYLON;
  16056. (function (BABYLON) {
  16057. var OctreeBlock = (function () {
  16058. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  16059. this.entries = new Array();
  16060. this._boundingVectors = new Array();
  16061. this._capacity = capacity;
  16062. this._depth = depth;
  16063. this._maxDepth = maxDepth;
  16064. this._creationFunc = creationFunc;
  16065. this._minPoint = minPoint;
  16066. this._maxPoint = maxPoint;
  16067. this._boundingVectors.push(minPoint.clone());
  16068. this._boundingVectors.push(maxPoint.clone());
  16069. this._boundingVectors.push(minPoint.clone());
  16070. this._boundingVectors[2].x = maxPoint.x;
  16071. this._boundingVectors.push(minPoint.clone());
  16072. this._boundingVectors[3].y = maxPoint.y;
  16073. this._boundingVectors.push(minPoint.clone());
  16074. this._boundingVectors[4].z = maxPoint.z;
  16075. this._boundingVectors.push(maxPoint.clone());
  16076. this._boundingVectors[5].z = minPoint.z;
  16077. this._boundingVectors.push(maxPoint.clone());
  16078. this._boundingVectors[6].x = minPoint.x;
  16079. this._boundingVectors.push(maxPoint.clone());
  16080. this._boundingVectors[7].y = minPoint.y;
  16081. }
  16082. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  16083. // Property
  16084. get: function () {
  16085. return this._capacity;
  16086. },
  16087. enumerable: true,
  16088. configurable: true
  16089. });
  16090. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  16091. get: function () {
  16092. return this._minPoint;
  16093. },
  16094. enumerable: true,
  16095. configurable: true
  16096. });
  16097. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  16098. get: function () {
  16099. return this._maxPoint;
  16100. },
  16101. enumerable: true,
  16102. configurable: true
  16103. });
  16104. // Methods
  16105. OctreeBlock.prototype.addEntry = function (entry) {
  16106. if (this.blocks) {
  16107. for (var index = 0; index < this.blocks.length; index++) {
  16108. var block = this.blocks[index];
  16109. block.addEntry(entry);
  16110. }
  16111. return;
  16112. }
  16113. this._creationFunc(entry, this);
  16114. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  16115. this.createInnerBlocks();
  16116. }
  16117. };
  16118. OctreeBlock.prototype.addEntries = function (entries) {
  16119. for (var index = 0; index < entries.length; index++) {
  16120. var mesh = entries[index];
  16121. this.addEntry(mesh);
  16122. }
  16123. };
  16124. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  16125. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  16126. if (this.blocks) {
  16127. for (var index = 0; index < this.blocks.length; index++) {
  16128. var block = this.blocks[index];
  16129. block.select(frustumPlanes, selection, allowDuplicate);
  16130. }
  16131. return;
  16132. }
  16133. if (allowDuplicate) {
  16134. selection.concat(this.entries);
  16135. }
  16136. else {
  16137. selection.concatWithNoDuplicate(this.entries);
  16138. }
  16139. }
  16140. };
  16141. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  16142. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  16143. if (this.blocks) {
  16144. for (var index = 0; index < this.blocks.length; index++) {
  16145. var block = this.blocks[index];
  16146. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  16147. }
  16148. return;
  16149. }
  16150. if (allowDuplicate) {
  16151. selection.concat(this.entries);
  16152. }
  16153. else {
  16154. selection.concatWithNoDuplicate(this.entries);
  16155. }
  16156. }
  16157. };
  16158. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  16159. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  16160. if (this.blocks) {
  16161. for (var index = 0; index < this.blocks.length; index++) {
  16162. var block = this.blocks[index];
  16163. block.intersectsRay(ray, selection);
  16164. }
  16165. return;
  16166. }
  16167. selection.concatWithNoDuplicate(this.entries);
  16168. }
  16169. };
  16170. OctreeBlock.prototype.createInnerBlocks = function () {
  16171. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  16172. };
  16173. return OctreeBlock;
  16174. })();
  16175. BABYLON.OctreeBlock = OctreeBlock;
  16176. })(BABYLON || (BABYLON = {}));
  16177. //# sourceMappingURL=babylon.octreeBlock.js.mapvar BABYLON;
  16178. (function (BABYLON) {
  16179. var Bone = (function () {
  16180. function Bone(name, skeleton, parentBone, matrix) {
  16181. this.name = name;
  16182. this.children = new Array();
  16183. this.animations = new Array();
  16184. this._worldTransform = new BABYLON.Matrix();
  16185. this._absoluteTransform = new BABYLON.Matrix();
  16186. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  16187. this._skeleton = skeleton;
  16188. this._matrix = matrix;
  16189. this._baseMatrix = matrix;
  16190. skeleton.bones.push(this);
  16191. if (parentBone) {
  16192. this._parent = parentBone;
  16193. parentBone.children.push(this);
  16194. }
  16195. else {
  16196. this._parent = null;
  16197. }
  16198. this._updateDifferenceMatrix();
  16199. }
  16200. // Members
  16201. Bone.prototype.getParent = function () {
  16202. return this._parent;
  16203. };
  16204. Bone.prototype.getLocalMatrix = function () {
  16205. return this._matrix;
  16206. };
  16207. Bone.prototype.getBaseMatrix = function () {
  16208. return this._baseMatrix;
  16209. };
  16210. Bone.prototype.getWorldMatrix = function () {
  16211. return this._worldTransform;
  16212. };
  16213. Bone.prototype.getInvertedAbsoluteTransform = function () {
  16214. return this._invertedAbsoluteTransform;
  16215. };
  16216. Bone.prototype.getAbsoluteMatrix = function () {
  16217. var matrix = this._matrix.clone();
  16218. var parent = this._parent;
  16219. while (parent) {
  16220. matrix = matrix.multiply(parent.getLocalMatrix());
  16221. parent = parent.getParent();
  16222. }
  16223. return matrix;
  16224. };
  16225. // Methods
  16226. Bone.prototype.updateMatrix = function (matrix) {
  16227. this._matrix = matrix;
  16228. this._skeleton._markAsDirty();
  16229. this._updateDifferenceMatrix();
  16230. };
  16231. Bone.prototype._updateDifferenceMatrix = function () {
  16232. if (this._parent) {
  16233. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  16234. }
  16235. else {
  16236. this._absoluteTransform.copyFrom(this._matrix);
  16237. }
  16238. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  16239. for (var index = 0; index < this.children.length; index++) {
  16240. this.children[index]._updateDifferenceMatrix();
  16241. }
  16242. };
  16243. Bone.prototype.markAsDirty = function () {
  16244. this._skeleton._markAsDirty();
  16245. };
  16246. return Bone;
  16247. })();
  16248. BABYLON.Bone = Bone;
  16249. })(BABYLON || (BABYLON = {}));
  16250. //# sourceMappingURL=babylon.bone.js.mapvar BABYLON;
  16251. (function (BABYLON) {
  16252. var Skeleton = (function () {
  16253. function Skeleton(name, id, scene) {
  16254. this.name = name;
  16255. this.id = id;
  16256. this.bones = new Array();
  16257. this._isDirty = true;
  16258. this._identity = BABYLON.Matrix.Identity();
  16259. this.bones = [];
  16260. this._scene = scene;
  16261. scene.skeletons.push(this);
  16262. }
  16263. // Members
  16264. Skeleton.prototype.getTransformMatrices = function () {
  16265. return this._transformMatrices;
  16266. };
  16267. // Methods
  16268. Skeleton.prototype._markAsDirty = function () {
  16269. this._isDirty = true;
  16270. };
  16271. Skeleton.prototype.prepare = function () {
  16272. if (!this._isDirty) {
  16273. return;
  16274. }
  16275. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  16276. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  16277. }
  16278. for (var index = 0; index < this.bones.length; index++) {
  16279. var bone = this.bones[index];
  16280. var parentBone = bone.getParent();
  16281. if (parentBone) {
  16282. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  16283. }
  16284. else {
  16285. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  16286. }
  16287. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  16288. }
  16289. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  16290. this._isDirty = false;
  16291. };
  16292. Skeleton.prototype.getAnimatables = function () {
  16293. if (!this._animatables || this._animatables.length != this.bones.length) {
  16294. this._animatables = [];
  16295. for (var index = 0; index < this.bones.length; index++) {
  16296. this._animatables.push(this.bones[index]);
  16297. }
  16298. }
  16299. return this._animatables;
  16300. };
  16301. Skeleton.prototype.clone = function (name, id) {
  16302. var result = new BABYLON.Skeleton(name, id || name, this._scene);
  16303. for (var index = 0; index < this.bones.length; index++) {
  16304. var source = this.bones[index];
  16305. var parentBone = null;
  16306. if (source.getParent()) {
  16307. var parentIndex = this.bones.indexOf(source.getParent());
  16308. parentBone = result.bones[parentIndex];
  16309. }
  16310. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  16311. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  16312. }
  16313. return result;
  16314. };
  16315. return Skeleton;
  16316. })();
  16317. BABYLON.Skeleton = Skeleton;
  16318. })(BABYLON || (BABYLON = {}));
  16319. //# sourceMappingURL=babylon.skeleton.js.mapvar BABYLON;
  16320. (function (BABYLON) {
  16321. var PostProcess = (function () {
  16322. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable, defines) {
  16323. this.name = name;
  16324. this.width = -1;
  16325. this.height = -1;
  16326. this._reusable = false;
  16327. this._textures = new BABYLON.SmartArray(2);
  16328. this._currentRenderTextureInd = 0;
  16329. if (camera != null) {
  16330. this._camera = camera;
  16331. this._scene = camera.getScene();
  16332. camera.attachPostProcess(this);
  16333. this._engine = this._scene.getEngine();
  16334. }
  16335. else {
  16336. this._engine = engine;
  16337. }
  16338. this._renderRatio = ratio;
  16339. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  16340. this._reusable = reusable || false;
  16341. samplers = samplers || [];
  16342. samplers.push("textureSampler");
  16343. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: fragmentUrl }, ["position"], parameters || [], samplers, defines !== undefined ? defines : "");
  16344. }
  16345. PostProcess.prototype.isReusable = function () {
  16346. return this._reusable;
  16347. };
  16348. PostProcess.prototype.activate = function (camera, sourceTexture) {
  16349. camera = camera || this._camera;
  16350. var scene = camera.getScene();
  16351. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  16352. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  16353. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  16354. desiredWidth = BABYLON.Tools.GetExponantOfTwo(desiredWidth, maxSize);
  16355. desiredHeight = BABYLON.Tools.GetExponantOfTwo(desiredHeight, maxSize);
  16356. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  16357. if (this._textures.length > 0) {
  16358. for (var i = 0; i < this._textures.length; i++) {
  16359. this._engine._releaseTexture(this._textures.data[i]);
  16360. }
  16361. this._textures.reset();
  16362. }
  16363. this.width = desiredWidth;
  16364. this.height = desiredHeight;
  16365. this._textures.push(this._engine.createRenderTargetTexture({ width: this.width, height: this.height }, { generateMipMaps: false, generateDepthBuffer: camera._postProcesses.indexOf(this) === camera._postProcessesTakenIndices[0], samplingMode: this.renderTargetSamplingMode }));
  16366. if (this._reusable) {
  16367. this._textures.push(this._engine.createRenderTargetTexture({ width: this.width, height: this.height }, { generateMipMaps: false, generateDepthBuffer: camera._postProcesses.indexOf(this) === camera._postProcessesTakenIndices[0], samplingMode: this.renderTargetSamplingMode }));
  16368. }
  16369. if (this.onSizeChanged) {
  16370. this.onSizeChanged();
  16371. }
  16372. }
  16373. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  16374. if (this.onActivate) {
  16375. this.onActivate(camera);
  16376. }
  16377. // Clear
  16378. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  16379. if (this._reusable) {
  16380. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  16381. }
  16382. };
  16383. PostProcess.prototype.apply = function () {
  16384. // Check
  16385. if (!this._effect.isReady())
  16386. return null;
  16387. // States
  16388. this._engine.enableEffect(this._effect);
  16389. this._engine.setState(false);
  16390. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16391. this._engine.setDepthBuffer(false);
  16392. this._engine.setDepthWrite(false);
  16393. // Texture
  16394. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  16395. // Parameters
  16396. if (this.onApply) {
  16397. this.onApply(this._effect);
  16398. }
  16399. return this._effect;
  16400. };
  16401. PostProcess.prototype.dispose = function (camera) {
  16402. camera = camera || this._camera;
  16403. if (this._textures.length > 0) {
  16404. for (var i = 0; i < this._textures.length; i++) {
  16405. this._engine._releaseTexture(this._textures.data[i]);
  16406. }
  16407. this._textures.reset();
  16408. }
  16409. camera.detachPostProcess(this);
  16410. var index = camera._postProcesses.indexOf(this);
  16411. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  16412. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  16413. }
  16414. };
  16415. return PostProcess;
  16416. })();
  16417. BABYLON.PostProcess = PostProcess;
  16418. })(BABYLON || (BABYLON = {}));
  16419. //# sourceMappingURL=babylon.postProcess.js.mapvar BABYLON;
  16420. (function (BABYLON) {
  16421. var PostProcessManager = (function () {
  16422. function PostProcessManager(scene) {
  16423. this._vertexDeclaration = [2];
  16424. this._vertexStrideSize = 2 * 4;
  16425. this._scene = scene;
  16426. // VBO
  16427. var vertices = [];
  16428. vertices.push(1, 1);
  16429. vertices.push(-1, 1);
  16430. vertices.push(-1, -1);
  16431. vertices.push(1, -1);
  16432. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  16433. // Indices
  16434. var indices = [];
  16435. indices.push(0);
  16436. indices.push(1);
  16437. indices.push(2);
  16438. indices.push(0);
  16439. indices.push(2);
  16440. indices.push(3);
  16441. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  16442. }
  16443. // Methods
  16444. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  16445. var postProcesses = this._scene.activeCamera._postProcesses;
  16446. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  16447. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  16448. return false;
  16449. }
  16450. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  16451. return true;
  16452. };
  16453. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture) {
  16454. var postProcesses = this._scene.activeCamera._postProcesses;
  16455. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  16456. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  16457. return;
  16458. }
  16459. var engine = this._scene.getEngine();
  16460. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  16461. if (index < postProcessesTakenIndices.length - 1) {
  16462. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  16463. }
  16464. else {
  16465. if (targetTexture) {
  16466. engine.bindFramebuffer(targetTexture);
  16467. }
  16468. else {
  16469. engine.restoreDefaultFramebuffer();
  16470. }
  16471. }
  16472. if (doNotPresent) {
  16473. break;
  16474. }
  16475. var pp = postProcesses[postProcessesTakenIndices[index]];
  16476. var effect = pp.apply();
  16477. if (effect) {
  16478. if (pp.onBeforeRender) {
  16479. pp.onBeforeRender(effect);
  16480. }
  16481. // VBOs
  16482. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  16483. // Draw order
  16484. engine.draw(true, 0, 6);
  16485. }
  16486. }
  16487. // Restore depth buffer
  16488. engine.setDepthBuffer(true);
  16489. engine.setDepthWrite(true);
  16490. };
  16491. PostProcessManager.prototype.dispose = function () {
  16492. if (this._vertexBuffer) {
  16493. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  16494. this._vertexBuffer = null;
  16495. }
  16496. if (this._indexBuffer) {
  16497. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  16498. this._indexBuffer = null;
  16499. }
  16500. };
  16501. return PostProcessManager;
  16502. })();
  16503. BABYLON.PostProcessManager = PostProcessManager;
  16504. })(BABYLON || (BABYLON = {}));
  16505. //# sourceMappingURL=babylon.postProcessManager.js.map
  16506. var BABYLON;
  16507. (function (BABYLON) {
  16508. var PassPostProcess = (function (_super) {
  16509. __extends(PassPostProcess, _super);
  16510. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  16511. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  16512. }
  16513. return PassPostProcess;
  16514. })(BABYLON.PostProcess);
  16515. BABYLON.PassPostProcess = PassPostProcess;
  16516. })(BABYLON || (BABYLON = {}));
  16517. //# sourceMappingURL=babylon.passPostProcess.js.map
  16518. var BABYLON;
  16519. (function (BABYLON) {
  16520. var BlurPostProcess = (function (_super) {
  16521. __extends(BlurPostProcess, _super);
  16522. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  16523. var _this = this;
  16524. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  16525. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  16526. this.direction = direction;
  16527. this.blurWidth = blurWidth;
  16528. this.onApply = function (effect) {
  16529. effect.setFloat2("screenSize", _this.width, _this.height);
  16530. effect.setVector2("direction", _this.direction);
  16531. effect.setFloat("blurWidth", _this.blurWidth);
  16532. };
  16533. }
  16534. return BlurPostProcess;
  16535. })(BABYLON.PostProcess);
  16536. BABYLON.BlurPostProcess = BlurPostProcess;
  16537. })(BABYLON || (BABYLON = {}));
  16538. //# sourceMappingURL=babylon.blurPostProcess.js.map
  16539. var BABYLON;
  16540. (function (BABYLON) {
  16541. var FilterPostProcess = (function (_super) {
  16542. __extends(FilterPostProcess, _super);
  16543. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  16544. var _this = this;
  16545. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  16546. this.kernelMatrix = kernelMatrix;
  16547. this.onApply = function (effect) {
  16548. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  16549. };
  16550. }
  16551. return FilterPostProcess;
  16552. })(BABYLON.PostProcess);
  16553. BABYLON.FilterPostProcess = FilterPostProcess;
  16554. })(BABYLON || (BABYLON = {}));
  16555. //# sourceMappingURL=babylon.filterPostProcess.js.map
  16556. var BABYLON;
  16557. (function (BABYLON) {
  16558. var RefractionPostProcess = (function (_super) {
  16559. __extends(RefractionPostProcess, _super);
  16560. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  16561. var _this = this;
  16562. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  16563. this.color = color;
  16564. this.depth = depth;
  16565. this.colorLevel = colorLevel;
  16566. this.onActivate = function (cam) {
  16567. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  16568. };
  16569. this.onApply = function (effect) {
  16570. effect.setColor3("baseColor", _this.color);
  16571. effect.setFloat("depth", _this.depth);
  16572. effect.setFloat("colorLevel", _this.colorLevel);
  16573. effect.setTexture("refractionSampler", _this._refRexture);
  16574. };
  16575. }
  16576. // Methods
  16577. RefractionPostProcess.prototype.dispose = function (camera) {
  16578. if (this._refRexture) {
  16579. this._refRexture.dispose();
  16580. }
  16581. _super.prototype.dispose.call(this, camera);
  16582. };
  16583. return RefractionPostProcess;
  16584. })(BABYLON.PostProcess);
  16585. BABYLON.RefractionPostProcess = RefractionPostProcess;
  16586. })(BABYLON || (BABYLON = {}));
  16587. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  16588. var BABYLON;
  16589. (function (BABYLON) {
  16590. var BlackAndWhitePostProcess = (function (_super) {
  16591. __extends(BlackAndWhitePostProcess, _super);
  16592. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  16593. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  16594. }
  16595. return BlackAndWhitePostProcess;
  16596. })(BABYLON.PostProcess);
  16597. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  16598. })(BABYLON || (BABYLON = {}));
  16599. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  16600. var BABYLON;
  16601. (function (BABYLON) {
  16602. var ConvolutionPostProcess = (function (_super) {
  16603. __extends(ConvolutionPostProcess, _super);
  16604. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  16605. var _this = this;
  16606. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  16607. this.kernel = kernel;
  16608. this.onApply = function (effect) {
  16609. effect.setFloat2("screenSize", _this.width, _this.height);
  16610. effect.setArray("kernel", _this.kernel);
  16611. };
  16612. }
  16613. // Statics
  16614. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  16615. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  16616. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  16617. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  16618. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  16619. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  16620. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  16621. return ConvolutionPostProcess;
  16622. })(BABYLON.PostProcess);
  16623. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  16624. })(BABYLON || (BABYLON = {}));
  16625. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  16626. var BABYLON;
  16627. (function (BABYLON) {
  16628. var FxaaPostProcess = (function (_super) {
  16629. __extends(FxaaPostProcess, _super);
  16630. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  16631. var _this = this;
  16632. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  16633. this.onSizeChanged = function () {
  16634. _this.texelWidth = 1.0 / _this.width;
  16635. _this.texelHeight = 1.0 / _this.height;
  16636. };
  16637. this.onApply = function (effect) {
  16638. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  16639. };
  16640. }
  16641. return FxaaPostProcess;
  16642. })(BABYLON.PostProcess);
  16643. BABYLON.FxaaPostProcess = FxaaPostProcess;
  16644. })(BABYLON || (BABYLON = {}));
  16645. //# sourceMappingURL=babylon.fxaaPostProcess.js.mapvar BABYLON;
  16646. (function (BABYLON) {
  16647. var LensFlare = (function () {
  16648. function LensFlare(size, position, color, imgUrl, system) {
  16649. this.size = size;
  16650. this.position = position;
  16651. this.dispose = function () {
  16652. if (this.texture) {
  16653. this.texture.dispose();
  16654. }
  16655. // Remove from scene
  16656. var index = this._system.lensFlares.indexOf(this);
  16657. this._system.lensFlares.splice(index, 1);
  16658. };
  16659. this.color = color || new BABYLON.Color3(1, 1, 1);
  16660. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  16661. this._system = system;
  16662. system.lensFlares.push(this);
  16663. }
  16664. return LensFlare;
  16665. })();
  16666. BABYLON.LensFlare = LensFlare;
  16667. })(BABYLON || (BABYLON = {}));
  16668. //# sourceMappingURL=babylon.lensFlare.js.mapvar BABYLON;
  16669. (function (BABYLON) {
  16670. var LensFlareSystem = (function () {
  16671. function LensFlareSystem(name, emitter, scene) {
  16672. this.name = name;
  16673. this.lensFlares = new Array();
  16674. this.borderLimit = 300;
  16675. this._vertexDeclaration = [2];
  16676. this._vertexStrideSize = 2 * 4;
  16677. this._isEnabled = true;
  16678. this._scene = scene;
  16679. this._emitter = emitter;
  16680. scene.lensFlareSystems.push(this);
  16681. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  16682. // VBO
  16683. var vertices = [];
  16684. vertices.push(1, 1);
  16685. vertices.push(-1, 1);
  16686. vertices.push(-1, -1);
  16687. vertices.push(1, -1);
  16688. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  16689. // Indices
  16690. var indices = [];
  16691. indices.push(0);
  16692. indices.push(1);
  16693. indices.push(2);
  16694. indices.push(0);
  16695. indices.push(2);
  16696. indices.push(3);
  16697. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  16698. // Effects
  16699. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  16700. }
  16701. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  16702. get: function () {
  16703. return this._isEnabled;
  16704. },
  16705. set: function (value) {
  16706. this._isEnabled = value;
  16707. },
  16708. enumerable: true,
  16709. configurable: true
  16710. });
  16711. LensFlareSystem.prototype.getScene = function () {
  16712. return this._scene;
  16713. };
  16714. LensFlareSystem.prototype.getEmitter = function () {
  16715. return this._emitter;
  16716. };
  16717. LensFlareSystem.prototype.getEmitterPosition = function () {
  16718. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  16719. };
  16720. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  16721. var position = this.getEmitterPosition();
  16722. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  16723. this._positionX = position.x;
  16724. this._positionY = position.y;
  16725. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  16726. if (position.z > 0) {
  16727. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  16728. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  16729. return true;
  16730. }
  16731. }
  16732. return false;
  16733. };
  16734. LensFlareSystem.prototype._isVisible = function () {
  16735. if (!this._isEnabled) {
  16736. return false;
  16737. }
  16738. var emitterPosition = this.getEmitterPosition();
  16739. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  16740. var distance = direction.length();
  16741. direction.normalize();
  16742. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  16743. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  16744. return !pickInfo.hit || pickInfo.distance > distance;
  16745. };
  16746. LensFlareSystem.prototype.render = function () {
  16747. if (!this._effect.isReady())
  16748. return false;
  16749. var engine = this._scene.getEngine();
  16750. var viewport = this._scene.activeCamera.viewport;
  16751. var globalViewport = viewport.toGlobal(engine);
  16752. // Position
  16753. if (!this.computeEffectivePosition(globalViewport)) {
  16754. return false;
  16755. }
  16756. // Visibility
  16757. if (!this._isVisible()) {
  16758. return false;
  16759. }
  16760. // Intensity
  16761. var awayX;
  16762. var awayY;
  16763. if (this._positionX < this.borderLimit + globalViewport.x) {
  16764. awayX = this.borderLimit + globalViewport.x - this._positionX;
  16765. }
  16766. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  16767. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  16768. }
  16769. else {
  16770. awayX = 0;
  16771. }
  16772. if (this._positionY < this.borderLimit + globalViewport.y) {
  16773. awayY = this.borderLimit + globalViewport.y - this._positionY;
  16774. }
  16775. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  16776. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  16777. }
  16778. else {
  16779. awayY = 0;
  16780. }
  16781. var away = (awayX > awayY) ? awayX : awayY;
  16782. if (away > this.borderLimit) {
  16783. away = this.borderLimit;
  16784. }
  16785. var intensity = 1.0 - (away / this.borderLimit);
  16786. if (intensity < 0) {
  16787. return false;
  16788. }
  16789. if (intensity > 1.0) {
  16790. intensity = 1.0;
  16791. }
  16792. // Position
  16793. var centerX = globalViewport.x + globalViewport.width / 2;
  16794. var centerY = globalViewport.y + globalViewport.height / 2;
  16795. var distX = centerX - this._positionX;
  16796. var distY = centerY - this._positionY;
  16797. // Effects
  16798. engine.enableEffect(this._effect);
  16799. engine.setState(false);
  16800. engine.setDepthBuffer(false);
  16801. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  16802. // VBOs
  16803. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  16804. for (var index = 0; index < this.lensFlares.length; index++) {
  16805. var flare = this.lensFlares[index];
  16806. var x = centerX - (distX * flare.position);
  16807. var y = centerY - (distY * flare.position);
  16808. var cw = flare.size;
  16809. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  16810. var cx = 2 * (x / globalViewport.width) - 1.0;
  16811. var cy = 1.0 - 2 * (y / globalViewport.height);
  16812. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  16813. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  16814. // Texture
  16815. this._effect.setTexture("textureSampler", flare.texture);
  16816. // Color
  16817. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  16818. // Draw order
  16819. engine.draw(true, 0, 6);
  16820. }
  16821. engine.setDepthBuffer(true);
  16822. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16823. return true;
  16824. };
  16825. LensFlareSystem.prototype.dispose = function () {
  16826. if (this._vertexBuffer) {
  16827. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  16828. this._vertexBuffer = null;
  16829. }
  16830. if (this._indexBuffer) {
  16831. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  16832. this._indexBuffer = null;
  16833. }
  16834. while (this.lensFlares.length) {
  16835. this.lensFlares[0].dispose();
  16836. }
  16837. // Remove from scene
  16838. var index = this._scene.lensFlareSystems.indexOf(this);
  16839. this._scene.lensFlareSystems.splice(index, 1);
  16840. };
  16841. return LensFlareSystem;
  16842. })();
  16843. BABYLON.LensFlareSystem = LensFlareSystem;
  16844. })(BABYLON || (BABYLON = {}));
  16845. //# sourceMappingURL=babylon.lensFlareSystem.js.mapvar BABYLON;
  16846. (function (BABYLON) {
  16847. var IntersectionInfo = (function () {
  16848. function IntersectionInfo(bu, bv, distance) {
  16849. this.bu = bu;
  16850. this.bv = bv;
  16851. this.distance = distance;
  16852. this.faceId = 0;
  16853. }
  16854. return IntersectionInfo;
  16855. })();
  16856. BABYLON.IntersectionInfo = IntersectionInfo;
  16857. var PickingInfo = (function () {
  16858. function PickingInfo() {
  16859. this.hit = false;
  16860. this.distance = 0;
  16861. this.pickedPoint = null;
  16862. this.pickedMesh = null;
  16863. this.bu = 0;
  16864. this.bv = 0;
  16865. this.faceId = -1;
  16866. }
  16867. // Methods
  16868. PickingInfo.prototype.getNormal = function () {
  16869. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  16870. return null;
  16871. }
  16872. var indices = this.pickedMesh.getIndices();
  16873. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16874. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  16875. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  16876. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  16877. normal0 = normal0.scale(this.bu);
  16878. normal1 = normal1.scale(this.bv);
  16879. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  16880. return new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  16881. };
  16882. PickingInfo.prototype.getTextureCoordinates = function () {
  16883. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  16884. return null;
  16885. }
  16886. var indices = this.pickedMesh.getIndices();
  16887. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  16888. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  16889. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  16890. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  16891. uv0 = uv0.scale(this.bu);
  16892. uv1 = uv1.scale(this.bv);
  16893. uv2 = uv2.scale(1.0 - this.bu - this.bv);
  16894. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  16895. };
  16896. return PickingInfo;
  16897. })();
  16898. BABYLON.PickingInfo = PickingInfo;
  16899. })(BABYLON || (BABYLON = {}));
  16900. //# sourceMappingURL=babylon.pickingInfo.js.mapvar BABYLON;
  16901. (function (BABYLON) {
  16902. var FilesInput = (function () {
  16903. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  16904. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  16905. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  16906. this.engine = p_engine;
  16907. this.canvas = p_canvas;
  16908. this.currentScene = p_scene;
  16909. this.sceneLoadedCallback = p_sceneLoadedCallback;
  16910. this.progressCallback = p_progressCallback;
  16911. this.additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  16912. this.textureLoadingCallback = p_textureLoadingCallback;
  16913. this.startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  16914. }
  16915. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  16916. var _this = this;
  16917. if (p_elementToMonitor) {
  16918. this.elementToMonitor = p_elementToMonitor;
  16919. this.elementToMonitor.addEventListener("dragenter", function (e) {
  16920. _this.drag(e);
  16921. }, false);
  16922. this.elementToMonitor.addEventListener("dragover", function (e) {
  16923. _this.drag(e);
  16924. }, false);
  16925. this.elementToMonitor.addEventListener("drop", function (e) {
  16926. _this.drop(e);
  16927. }, false);
  16928. }
  16929. };
  16930. FilesInput.prototype.renderFunction = function () {
  16931. if (this.additionnalRenderLoopLogicCallback) {
  16932. this.additionnalRenderLoopLogicCallback();
  16933. }
  16934. if (this.currentScene) {
  16935. if (this.textureLoadingCallback) {
  16936. var remaining = this.currentScene.getWaitingItemsCount();
  16937. if (remaining > 0) {
  16938. this.textureLoadingCallback(remaining);
  16939. }
  16940. }
  16941. this.currentScene.render();
  16942. }
  16943. };
  16944. FilesInput.prototype.drag = function (e) {
  16945. e.stopPropagation();
  16946. e.preventDefault();
  16947. };
  16948. FilesInput.prototype.drop = function (eventDrop) {
  16949. eventDrop.stopPropagation();
  16950. eventDrop.preventDefault();
  16951. this.loadFiles(eventDrop);
  16952. };
  16953. FilesInput.prototype.loadFiles = function (event) {
  16954. var _this = this;
  16955. var that = this;
  16956. if (this.startingProcessingFilesCallback)
  16957. this.startingProcessingFilesCallback();
  16958. var sceneFileToLoad;
  16959. var filesToLoad;
  16960. // Handling data transfer via drag'n'drop
  16961. if (event && event.dataTransfer && event.dataTransfer.files) {
  16962. filesToLoad = event.dataTransfer.files;
  16963. }
  16964. // Handling files from input files
  16965. if (event && event.target && event.target.files) {
  16966. filesToLoad = event.target.files;
  16967. }
  16968. if (filesToLoad && filesToLoad.length > 0) {
  16969. for (var i = 0; i < filesToLoad.length; i++) {
  16970. switch (filesToLoad[i].type) {
  16971. case "image/jpeg":
  16972. case "image/png":
  16973. BABYLON.FilesInput.FilesTextures[filesToLoad[i].name] = filesToLoad[i];
  16974. break;
  16975. case "image/targa":
  16976. case "image/vnd.ms-dds":
  16977. case "audio/wav":
  16978. case "audio/x-wav":
  16979. case "audio/mp3":
  16980. case "audio/mpeg":
  16981. case "audio/mpeg3":
  16982. case "audio/x-mpeg-3":
  16983. case "audio/ogg":
  16984. BABYLON.FilesInput.FilesToLoad[filesToLoad[i].name] = filesToLoad[i];
  16985. break;
  16986. default:
  16987. if (filesToLoad[i].name.indexOf(".babylon") !== -1 && filesToLoad[i].name.indexOf(".manifest") === -1 && filesToLoad[i].name.indexOf(".incremental") === -1 && filesToLoad[i].name.indexOf(".babylonmeshdata") === -1 && filesToLoad[i].name.indexOf(".babylongeometrydata") === -1) {
  16988. sceneFileToLoad = filesToLoad[i];
  16989. }
  16990. break;
  16991. }
  16992. }
  16993. // If a ".babylon" file has been provided
  16994. if (sceneFileToLoad) {
  16995. if (this.currentScene) {
  16996. this.engine.stopRenderLoop();
  16997. this.currentScene.dispose();
  16998. }
  16999. BABYLON.SceneLoader.Load("file:", sceneFileToLoad, this.engine, function (newScene) {
  17000. that.currentScene = newScene;
  17001. // Wait for textures and shaders to be ready
  17002. that.currentScene.executeWhenReady(function () {
  17003. // Attach camera to canvas inputs
  17004. if (that.currentScene.activeCamera) {
  17005. that.currentScene.activeCamera.attachControl(that.canvas);
  17006. }
  17007. if (that.sceneLoadedCallback) {
  17008. that.sceneLoadedCallback(sceneFileToLoad, that.currentScene);
  17009. }
  17010. that.engine.runRenderLoop(function () {
  17011. that.renderFunction();
  17012. });
  17013. });
  17014. }, function (progress) {
  17015. if (_this.progressCallback) {
  17016. _this.progressCallback(progress);
  17017. }
  17018. });
  17019. }
  17020. else {
  17021. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  17022. }
  17023. }
  17024. };
  17025. FilesInput.FilesTextures = new Array();
  17026. FilesInput.FilesToLoad = new Array();
  17027. return FilesInput;
  17028. })();
  17029. BABYLON.FilesInput = FilesInput;
  17030. })(BABYLON || (BABYLON = {}));
  17031. //# sourceMappingURL=babylon.filesInput.js.mapvar BABYLON;
  17032. (function (BABYLON) {
  17033. var OimoJSPlugin = (function () {
  17034. function OimoJSPlugin() {
  17035. this._registeredMeshes = [];
  17036. /**
  17037. * Update the body position according to the mesh position
  17038. * @param mesh
  17039. */
  17040. this.updateBodyPosition = function (mesh) {
  17041. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17042. var registeredMesh = this._registeredMeshes[index];
  17043. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  17044. var body = registeredMesh.body.body;
  17045. mesh.computeWorldMatrix(true);
  17046. var center = mesh.getBoundingInfo().boundingBox.center;
  17047. body.setPosition(center.x, center.y, center.z);
  17048. body.setRotation(mesh.rotation.x, mesh.rotation.y, mesh.rotation.z);
  17049. return;
  17050. }
  17051. // Case where the parent has been updated
  17052. if (registeredMesh.mesh.parent === mesh) {
  17053. mesh.computeWorldMatrix(true);
  17054. registeredMesh.mesh.computeWorldMatrix(true);
  17055. var absolutePosition = registeredMesh.mesh.getAbsolutePosition();
  17056. var absoluteRotation = mesh.rotation;
  17057. body = registeredMesh.body.body;
  17058. body.setPosition(absolutePosition.x, absolutePosition.y, absolutePosition.z);
  17059. body.setRotation(absoluteRotation.x, absoluteRotation.y, absoluteRotation.z);
  17060. return;
  17061. }
  17062. }
  17063. };
  17064. }
  17065. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  17066. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  17067. };
  17068. OimoJSPlugin.prototype.initialize = function (iterations) {
  17069. this._world = new OIMO.World();
  17070. this._world.clear();
  17071. };
  17072. OimoJSPlugin.prototype.setGravity = function (gravity) {
  17073. this._world.gravity = gravity;
  17074. };
  17075. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  17076. var body = null;
  17077. this.unregisterMesh(mesh);
  17078. mesh.computeWorldMatrix(true);
  17079. switch (impostor) {
  17080. case BABYLON.PhysicsEngine.SphereImpostor:
  17081. var initialRotation = null;
  17082. if (mesh.rotationQuaternion) {
  17083. initialRotation = mesh.rotationQuaternion.clone();
  17084. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  17085. mesh.computeWorldMatrix(true);
  17086. }
  17087. var bbox = mesh.getBoundingInfo().boundingBox;
  17088. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  17089. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  17090. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  17091. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  17092. // The delta between the mesh position and the mesh bounding box center
  17093. var deltaPosition = mesh.position.subtract(bbox.center);
  17094. // Transform delta position with the rotation
  17095. if (initialRotation) {
  17096. var m = new BABYLON.Matrix();
  17097. initialRotation.toRotationMatrix(m);
  17098. deltaPosition = BABYLON.Vector3.TransformCoordinates(deltaPosition, m);
  17099. }
  17100. body = new OIMO.Body({
  17101. type: 'sphere',
  17102. size: [size],
  17103. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  17104. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  17105. move: options.mass != 0,
  17106. config: [options.mass, options.friction, options.restitution],
  17107. world: this._world
  17108. });
  17109. // Restore rotation
  17110. if (initialRotation) {
  17111. body.setQuaternion(initialRotation);
  17112. }
  17113. this._registeredMeshes.push({
  17114. mesh: mesh,
  17115. body: body,
  17116. delta: deltaPosition
  17117. });
  17118. break;
  17119. case BABYLON.PhysicsEngine.PlaneImpostor:
  17120. case BABYLON.PhysicsEngine.BoxImpostor:
  17121. initialRotation = null;
  17122. if (mesh.rotationQuaternion) {
  17123. initialRotation = mesh.rotationQuaternion.clone();
  17124. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  17125. mesh.computeWorldMatrix(true);
  17126. }
  17127. bbox = mesh.getBoundingInfo().boundingBox;
  17128. var min = bbox.minimumWorld;
  17129. var max = bbox.maximumWorld;
  17130. var box = max.subtract(min);
  17131. var sizeX = this._checkWithEpsilon(box.x);
  17132. var sizeY = this._checkWithEpsilon(box.y);
  17133. var sizeZ = this._checkWithEpsilon(box.z);
  17134. // The delta between the mesh position and the mesh boudning box center
  17135. deltaPosition = mesh.position.subtract(bbox.center);
  17136. // Transform delta position with the rotation
  17137. if (initialRotation) {
  17138. m = new BABYLON.Matrix();
  17139. initialRotation.toRotationMatrix(m);
  17140. deltaPosition = BABYLON.Vector3.TransformCoordinates(deltaPosition, m);
  17141. }
  17142. body = new OIMO.Body({
  17143. type: 'box',
  17144. size: [sizeX, sizeY, sizeZ],
  17145. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  17146. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  17147. move: options.mass != 0,
  17148. config: [options.mass, options.friction, options.restitution],
  17149. world: this._world
  17150. });
  17151. if (initialRotation) {
  17152. body.setQuaternion(initialRotation);
  17153. }
  17154. this._registeredMeshes.push({
  17155. mesh: mesh,
  17156. body: body,
  17157. delta: deltaPosition
  17158. });
  17159. break;
  17160. }
  17161. return body;
  17162. };
  17163. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  17164. var types = [], sizes = [], positions = [], rotations = [];
  17165. var initialMesh = parts[0].mesh;
  17166. for (var index = 0; index < parts.length; index++) {
  17167. var part = parts[index];
  17168. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  17169. types.push(bodyParameters.type);
  17170. sizes.push.apply(sizes, bodyParameters.size);
  17171. positions.push.apply(positions, bodyParameters.pos);
  17172. rotations.push.apply(rotations, bodyParameters.rot);
  17173. }
  17174. var body = new OIMO.Body({
  17175. type: types,
  17176. size: sizes,
  17177. pos: positions,
  17178. rot: rotations,
  17179. move: options.mass != 0,
  17180. config: [options.mass, options.friction, options.restitution],
  17181. world: this._world
  17182. });
  17183. this._registeredMeshes.push({
  17184. mesh: initialMesh,
  17185. body: body
  17186. });
  17187. return body;
  17188. };
  17189. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  17190. var bodyParameters = null;
  17191. var mesh = part.mesh;
  17192. // We need the bounding box/sphere info to compute the physics body
  17193. mesh.computeWorldMatrix();
  17194. switch (part.impostor) {
  17195. case BABYLON.PhysicsEngine.SphereImpostor:
  17196. var bbox = mesh.getBoundingInfo().boundingBox;
  17197. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  17198. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  17199. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  17200. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  17201. bodyParameters = {
  17202. type: 'sphere',
  17203. /* bug with oimo : sphere needs 3 sizes in this case */
  17204. size: [size, -1, -1],
  17205. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  17206. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  17207. };
  17208. break;
  17209. case BABYLON.PhysicsEngine.PlaneImpostor:
  17210. case BABYLON.PhysicsEngine.BoxImpostor:
  17211. bbox = mesh.getBoundingInfo().boundingBox;
  17212. var min = bbox.minimumWorld;
  17213. var max = bbox.maximumWorld;
  17214. var box = max.subtract(min);
  17215. var sizeX = this._checkWithEpsilon(box.x);
  17216. var sizeY = this._checkWithEpsilon(box.y);
  17217. var sizeZ = this._checkWithEpsilon(box.z);
  17218. var relativePosition = mesh.position;
  17219. bodyParameters = {
  17220. type: 'box',
  17221. size: [sizeX, sizeY, sizeZ],
  17222. pos: [relativePosition.x, relativePosition.y, relativePosition.z],
  17223. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  17224. };
  17225. break;
  17226. }
  17227. return bodyParameters;
  17228. };
  17229. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  17230. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17231. var registeredMesh = this._registeredMeshes[index];
  17232. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  17233. if (registeredMesh.body) {
  17234. this._world.removeRigidBody(registeredMesh.body.body);
  17235. this._unbindBody(registeredMesh.body);
  17236. }
  17237. this._registeredMeshes.splice(index, 1);
  17238. return;
  17239. }
  17240. }
  17241. };
  17242. OimoJSPlugin.prototype._unbindBody = function (body) {
  17243. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17244. var registeredMesh = this._registeredMeshes[index];
  17245. if (registeredMesh.body === body) {
  17246. registeredMesh.body = null;
  17247. }
  17248. }
  17249. };
  17250. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  17251. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17252. var registeredMesh = this._registeredMeshes[index];
  17253. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  17254. // Get object mass to have a behaviour similar to cannon.js
  17255. var mass = registeredMesh.body.body.massInfo.mass;
  17256. // The force is scaled with the mass of object
  17257. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  17258. return;
  17259. }
  17260. }
  17261. };
  17262. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  17263. var body1 = null, body2 = null;
  17264. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17265. var registeredMesh = this._registeredMeshes[index];
  17266. if (registeredMesh.mesh === mesh1) {
  17267. body1 = registeredMesh.body.body;
  17268. }
  17269. else if (registeredMesh.mesh === mesh2) {
  17270. body2 = registeredMesh.body.body;
  17271. }
  17272. }
  17273. if (!body1 || !body2) {
  17274. return false;
  17275. }
  17276. if (!options) {
  17277. options = {};
  17278. }
  17279. new OIMO.Link({
  17280. type: options.type,
  17281. body1: body1,
  17282. body2: body2,
  17283. min: options.min,
  17284. max: options.max,
  17285. axe1: options.axe1,
  17286. axe2: options.axe2,
  17287. pos1: [pivot1.x, pivot1.y, pivot1.z],
  17288. pos2: [pivot2.x, pivot2.y, pivot2.z],
  17289. collision: options.collision,
  17290. spring: options.spring,
  17291. world: this._world
  17292. });
  17293. return true;
  17294. };
  17295. OimoJSPlugin.prototype.dispose = function () {
  17296. this._world.clear();
  17297. while (this._registeredMeshes.length) {
  17298. this.unregisterMesh(this._registeredMeshes[0].mesh);
  17299. }
  17300. };
  17301. OimoJSPlugin.prototype.isSupported = function () {
  17302. return OIMO !== undefined;
  17303. };
  17304. OimoJSPlugin.prototype._getLastShape = function (body) {
  17305. var lastShape = body.shapes;
  17306. while (lastShape.next) {
  17307. lastShape = lastShape.next;
  17308. }
  17309. return lastShape;
  17310. };
  17311. OimoJSPlugin.prototype.runOneStep = function (time) {
  17312. this._world.step();
  17313. // Update the position of all registered meshes
  17314. var i = this._registeredMeshes.length;
  17315. var m;
  17316. while (i--) {
  17317. var body = this._registeredMeshes[i].body.body;
  17318. var mesh = this._registeredMeshes[i].mesh;
  17319. var delta = this._registeredMeshes[i].delta;
  17320. if (!body.sleeping) {
  17321. if (body.shapes.next) {
  17322. var parentShape = this._getLastShape(body);
  17323. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  17324. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  17325. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  17326. var mtx = BABYLON.Matrix.FromArray(body.getMatrix());
  17327. if (!mesh.rotationQuaternion) {
  17328. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  17329. }
  17330. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  17331. mesh.computeWorldMatrix();
  17332. }
  17333. else {
  17334. m = body.getMatrix();
  17335. mtx = BABYLON.Matrix.FromArray(m);
  17336. // Body position
  17337. var bodyX = mtx.m[12], bodyY = mtx.m[13], bodyZ = mtx.m[14];
  17338. if (!delta) {
  17339. mesh.position.x = bodyX;
  17340. mesh.position.y = bodyY;
  17341. mesh.position.z = bodyZ;
  17342. }
  17343. else {
  17344. mesh.position.x = bodyX + delta.x;
  17345. mesh.position.y = bodyY + delta.y;
  17346. mesh.position.z = bodyZ + delta.z;
  17347. }
  17348. if (!mesh.rotationQuaternion) {
  17349. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  17350. }
  17351. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  17352. mesh.computeWorldMatrix();
  17353. }
  17354. }
  17355. }
  17356. };
  17357. return OimoJSPlugin;
  17358. })();
  17359. BABYLON.OimoJSPlugin = OimoJSPlugin;
  17360. })(BABYLON || (BABYLON = {}));
  17361. //# sourceMappingURL=babylon.oimoJSPlugin.js.mapvar BABYLON;
  17362. (function (BABYLON) {
  17363. var PhysicsEngine = (function () {
  17364. function PhysicsEngine(plugin) {
  17365. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  17366. }
  17367. PhysicsEngine.prototype._initialize = function (gravity) {
  17368. this._currentPlugin.initialize();
  17369. this._setGravity(gravity);
  17370. };
  17371. PhysicsEngine.prototype._runOneStep = function (delta) {
  17372. if (delta > 0.1) {
  17373. delta = 0.1;
  17374. }
  17375. else if (delta <= 0) {
  17376. delta = 1.0 / 60.0;
  17377. }
  17378. this._currentPlugin.runOneStep(delta);
  17379. };
  17380. PhysicsEngine.prototype._setGravity = function (gravity) {
  17381. this.gravity = gravity || new BABYLON.Vector3(0, -9.82, 0);
  17382. this._currentPlugin.setGravity(this.gravity);
  17383. };
  17384. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  17385. return this._currentPlugin.registerMesh(mesh, impostor, options);
  17386. };
  17387. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  17388. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  17389. };
  17390. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  17391. this._currentPlugin.unregisterMesh(mesh);
  17392. };
  17393. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  17394. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  17395. };
  17396. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  17397. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  17398. };
  17399. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  17400. this._currentPlugin.updateBodyPosition(mesh);
  17401. };
  17402. PhysicsEngine.prototype.dispose = function () {
  17403. this._currentPlugin.dispose();
  17404. };
  17405. PhysicsEngine.prototype.isSupported = function () {
  17406. return this._currentPlugin.isSupported();
  17407. };
  17408. // Statics
  17409. PhysicsEngine.NoImpostor = 0;
  17410. PhysicsEngine.SphereImpostor = 1;
  17411. PhysicsEngine.BoxImpostor = 2;
  17412. PhysicsEngine.PlaneImpostor = 3;
  17413. PhysicsEngine.MeshImpostor = 4;
  17414. PhysicsEngine.CapsuleImpostor = 5;
  17415. PhysicsEngine.ConeImpostor = 6;
  17416. PhysicsEngine.CylinderImpostor = 7;
  17417. PhysicsEngine.ConvexHullImpostor = 8;
  17418. PhysicsEngine.Epsilon = 0.001;
  17419. return PhysicsEngine;
  17420. })();
  17421. BABYLON.PhysicsEngine = PhysicsEngine;
  17422. })(BABYLON || (BABYLON = {}));
  17423. //# sourceMappingURL=babylon.physicsEngine.js.mapvar BABYLON;
  17424. (function (BABYLON) {
  17425. var serializeLight = function (light) {
  17426. var serializationObject = {};
  17427. serializationObject.name = light.name;
  17428. serializationObject.id = light.id;
  17429. serializationObject.tags = BABYLON.Tags.GetTags(light);
  17430. if (light instanceof BABYLON.PointLight) {
  17431. serializationObject.type = 0;
  17432. serializationObject.position = light.position.asArray();
  17433. }
  17434. else if (light instanceof BABYLON.DirectionalLight) {
  17435. serializationObject.type = 1;
  17436. var directionalLight = light;
  17437. serializationObject.position = directionalLight.position.asArray();
  17438. serializationObject.direction = directionalLight.direction.asArray();
  17439. }
  17440. else if (light instanceof BABYLON.SpotLight) {
  17441. serializationObject.type = 2;
  17442. var spotLight = light;
  17443. serializationObject.position = spotLight.position.asArray();
  17444. serializationObject.direction = spotLight.position.asArray();
  17445. serializationObject.angle = spotLight.angle;
  17446. serializationObject.exponent = spotLight.exponent;
  17447. }
  17448. else if (light instanceof BABYLON.HemisphericLight) {
  17449. serializationObject.type = 3;
  17450. var hemisphericLight = light;
  17451. serializationObject.direction = hemisphericLight.direction.asArray();
  17452. serializationObject.groundColor = hemisphericLight.groundColor.asArray();
  17453. }
  17454. if (light.intensity) {
  17455. serializationObject.intensity = light.intensity;
  17456. }
  17457. serializationObject.range = light.range;
  17458. serializationObject.diffuse = light.diffuse.asArray();
  17459. serializationObject.specular = light.specular.asArray();
  17460. return serializationObject;
  17461. };
  17462. var serializeFresnelParameter = function (fresnelParameter) {
  17463. var serializationObject = {};
  17464. serializationObject.isEnabled = fresnelParameter.isEnabled;
  17465. serializationObject.leftColor = fresnelParameter.leftColor;
  17466. serializationObject.rightColor = fresnelParameter.rightColor;
  17467. serializationObject.bias = fresnelParameter.bias;
  17468. serializationObject.power = fresnelParameter.power;
  17469. return serializationObject;
  17470. };
  17471. var serializeCamera = function (camera) {
  17472. var serializationObject = {};
  17473. serializationObject.name = camera.name;
  17474. serializationObject.tags = BABYLON.Tags.GetTags(camera);
  17475. serializationObject.id = camera.id;
  17476. serializationObject.position = camera.position.asArray();
  17477. // Parent
  17478. if (camera.parent) {
  17479. serializationObject.parentId = camera.parent.id;
  17480. }
  17481. // Target
  17482. serializationObject.rotation = camera.rotation.asArray();
  17483. // Locked target
  17484. if (camera.lockedTarget && camera.lockedTarget.id) {
  17485. serializationObject.lockedTargetId = camera.lockedTarget.id;
  17486. }
  17487. serializationObject.fov = camera.fov;
  17488. serializationObject.minZ = camera.minZ;
  17489. serializationObject.maxZ = camera.maxZ;
  17490. serializationObject.speed = camera.speed;
  17491. serializationObject.inertia = camera.inertia;
  17492. serializationObject.checkCollisions = camera.checkCollisions;
  17493. serializationObject.applyGravity = camera.applyGravity;
  17494. if (camera.ellipsoid) {
  17495. serializationObject.ellipsoid = camera.ellipsoid.asArray();
  17496. }
  17497. // Animations
  17498. appendAnimations(camera, serializationObject);
  17499. // Layer mask
  17500. serializationObject.layerMask = camera.layerMask;
  17501. return serializationObject;
  17502. };
  17503. var appendAnimations = function (source, destination) {
  17504. if (source.animations) {
  17505. destination.animations = [];
  17506. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  17507. var animation = source.animations[animationIndex];
  17508. destination.animations.push(serializeAnimation(animation));
  17509. }
  17510. }
  17511. };
  17512. var serializeAnimation = function (animation) {
  17513. var serializationObject = {};
  17514. serializationObject.name = animation.name;
  17515. serializationObject.property = animation.targetProperty;
  17516. serializationObject.framePerSecond = animation.framePerSecond;
  17517. serializationObject.dataType = animation.dataType;
  17518. serializationObject.loopBehavior = animation.loopMode;
  17519. var dataType = animation.dataType;
  17520. serializationObject.keys = [];
  17521. var keys = animation.getKeys();
  17522. for (var index = 0; index < keys.length; index++) {
  17523. var animationKey = keys[index];
  17524. var key = {};
  17525. key.frame = animationKey.frame;
  17526. switch (dataType) {
  17527. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  17528. key.values = [animationKey.value];
  17529. break;
  17530. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  17531. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  17532. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  17533. key.values = animationKey.value.asArray();
  17534. break;
  17535. }
  17536. serializationObject.keys.push(key);
  17537. }
  17538. return serializationObject;
  17539. };
  17540. var serializeMultiMaterial = function (material) {
  17541. var serializationObject = {};
  17542. serializationObject.name = material.name;
  17543. serializationObject.id = material.id;
  17544. serializationObject.tags = BABYLON.Tags.GetTags(material);
  17545. serializationObject.materials = [];
  17546. for (var matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
  17547. var subMat = material.subMaterials[matIndex];
  17548. if (subMat) {
  17549. serializationObject.materials.push(subMat.id);
  17550. }
  17551. else {
  17552. serializationObject.materials.push(null);
  17553. }
  17554. }
  17555. return serializationObject;
  17556. };
  17557. var serializeMaterial = function (material) {
  17558. var serializationObject = {};
  17559. serializationObject.name = material.name;
  17560. serializationObject.ambient = material.ambientColor.asArray();
  17561. serializationObject.diffuse = material.diffuseColor.asArray();
  17562. serializationObject.specular = material.specularColor.asArray();
  17563. serializationObject.specularPower = material.specularPower;
  17564. serializationObject.emissive = material.emissiveColor.asArray();
  17565. serializationObject.alpha = material.alpha;
  17566. serializationObject.id = material.id;
  17567. serializationObject.tags = BABYLON.Tags.GetTags(material);
  17568. serializationObject.backFaceCulling = material.backFaceCulling;
  17569. if (material.diffuseTexture) {
  17570. serializationObject.diffuseTexture = serializeTexture(material.diffuseTexture);
  17571. }
  17572. if (material.diffuseFresnelParameters) {
  17573. serializationObject.diffuseFresnelParameters = serializeFresnelParameter(material.diffuseFresnelParameters);
  17574. }
  17575. if (material.ambientTexture) {
  17576. serializationObject.ambientTexture = serializeTexture(material.ambientTexture);
  17577. }
  17578. if (material.opacityTexture) {
  17579. serializationObject.opacityTexture = serializeTexture(material.opacityTexture);
  17580. }
  17581. if (material.opacityFresnelParameters) {
  17582. serializationObject.opacityFresnelParameters = serializeFresnelParameter(material.opacityFresnelParameters);
  17583. }
  17584. if (material.reflectionTexture) {
  17585. serializationObject.reflectionTexture = serializeTexture(material.reflectionTexture);
  17586. }
  17587. if (material.reflectionFresnelParameters) {
  17588. serializationObject.reflectionFresnelParameters = serializeFresnelParameter(material.reflectionFresnelParameters);
  17589. }
  17590. if (material.emissiveTexture) {
  17591. serializationObject.emissiveTexture = serializeTexture(material.emissiveTexture);
  17592. }
  17593. if (material.emissiveFresnelParameters) {
  17594. serializationObject.emissiveFresnelParameters = serializeFresnelParameter(material.emissiveFresnelParameters);
  17595. }
  17596. if (material.specularTexture) {
  17597. serializationObject.specularTexture = serializeTexture(material.specularTexture);
  17598. }
  17599. if (material.bumpTexture) {
  17600. serializationObject.bumpTexture = serializeTexture(material.bumpTexture);
  17601. }
  17602. return serializationObject;
  17603. };
  17604. var serializeTexture = function (texture) {
  17605. var serializationObject = {};
  17606. if (!texture.name) {
  17607. return null;
  17608. }
  17609. if (texture instanceof BABYLON.CubeTexture) {
  17610. serializationObject.name = texture.name;
  17611. serializationObject.hasAlpha = texture.hasAlpha;
  17612. serializationObject.level = texture.level;
  17613. serializationObject.coordinatesMode = texture.coordinatesMode;
  17614. return serializationObject;
  17615. }
  17616. if (texture instanceof BABYLON.MirrorTexture) {
  17617. var mirrorTexture = texture;
  17618. serializationObject.renderTargetSize = mirrorTexture.getRenderSize();
  17619. serializationObject.renderList = [];
  17620. for (var index = 0; index < mirrorTexture.renderList.length; index++) {
  17621. serializationObject.renderList.push(mirrorTexture.renderList[index].id);
  17622. }
  17623. serializationObject.mirrorPlane = mirrorTexture.mirrorPlane.asArray();
  17624. }
  17625. else if (texture instanceof BABYLON.RenderTargetTexture) {
  17626. var renderTargetTexture = texture;
  17627. serializationObject.renderTargetSize = renderTargetTexture.getRenderSize();
  17628. serializationObject.renderList = [];
  17629. for (index = 0; index < renderTargetTexture.renderList.length; index++) {
  17630. serializationObject.renderList.push(renderTargetTexture.renderList[index].id);
  17631. }
  17632. }
  17633. var regularTexture = texture;
  17634. serializationObject.name = texture.name;
  17635. serializationObject.hasAlpha = texture.hasAlpha;
  17636. serializationObject.level = texture.level;
  17637. serializationObject.coordinatesIndex = texture.coordinatesIndex;
  17638. serializationObject.coordinatesMode = texture.coordinatesMode;
  17639. serializationObject.uOffset = regularTexture.uOffset;
  17640. serializationObject.vOffset = regularTexture.vOffset;
  17641. serializationObject.uScale = regularTexture.uScale;
  17642. serializationObject.vScale = regularTexture.vScale;
  17643. serializationObject.uAng = regularTexture.uAng;
  17644. serializationObject.vAng = regularTexture.vAng;
  17645. serializationObject.wAng = regularTexture.wAng;
  17646. serializationObject.wrapU = texture.wrapU;
  17647. serializationObject.wrapV = texture.wrapV;
  17648. // Animations
  17649. appendAnimations(texture, serializationObject);
  17650. return serializationObject;
  17651. };
  17652. var serializeSkeleton = function (skeleton) {
  17653. var serializationObject = {};
  17654. serializationObject.name = skeleton.name;
  17655. serializationObject.id = skeleton.id;
  17656. serializationObject.bones = [];
  17657. for (var index = 0; index < skeleton.bones.length; index++) {
  17658. var bone = skeleton.bones[index];
  17659. var serializedBone = {
  17660. parentBoneIndex: bone.getParent() ? skeleton.bones.indexOf(bone.getParent()) : -1,
  17661. name: bone.name,
  17662. matrix: bone.getLocalMatrix().toArray()
  17663. };
  17664. serializationObject.bones.push(serializedBone);
  17665. if (bone.animations && bone.animations.length > 0) {
  17666. serializedBone.animation = serializeAnimation(bone.animations[0]);
  17667. }
  17668. }
  17669. return serializationObject;
  17670. };
  17671. var serializeParticleSystem = function (particleSystem) {
  17672. var serializationObject = {};
  17673. serializationObject.emitterId = particleSystem.emitter.id;
  17674. serializationObject.capacity = particleSystem.getCapacity();
  17675. if (particleSystem.particleTexture) {
  17676. serializationObject.textureName = particleSystem.particleTexture.name;
  17677. }
  17678. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  17679. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  17680. serializationObject.minSize = particleSystem.minSize;
  17681. serializationObject.maxSize = particleSystem.maxSize;
  17682. serializationObject.minLifeTime = particleSystem.minLifeTime;
  17683. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  17684. serializationObject.emitRate = particleSystem.emitRate;
  17685. serializationObject.minEmitBox = particleSystem.minEmitBox.asArray();
  17686. serializationObject.maxEmitBox = particleSystem.maxEmitBox.asArray();
  17687. serializationObject.gravity = particleSystem.gravity.asArray();
  17688. serializationObject.direction1 = particleSystem.direction1.asArray();
  17689. serializationObject.direction2 = particleSystem.direction2.asArray();
  17690. serializationObject.color1 = particleSystem.color1.asArray();
  17691. serializationObject.color2 = particleSystem.color2.asArray();
  17692. serializationObject.colorDead = particleSystem.colorDead.asArray();
  17693. serializationObject.updateSpeed = particleSystem.updateSpeed;
  17694. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  17695. serializationObject.textureMask = particleSystem.textureMask.asArray();
  17696. serializationObject.blendMode = particleSystem.blendMode;
  17697. return serializationObject;
  17698. };
  17699. var serializeLensFlareSystem = function (lensFlareSystem) {
  17700. var serializationObject = {};
  17701. serializationObject.emitterId = lensFlareSystem.getEmitter().id;
  17702. serializationObject.borderLimit = lensFlareSystem.borderLimit;
  17703. serializationObject.flares = [];
  17704. for (var index = 0; index < lensFlareSystem.lensFlares.length; index++) {
  17705. var flare = lensFlareSystem.lensFlares[index];
  17706. serializationObject.flares.push({
  17707. size: flare.size,
  17708. position: flare.position,
  17709. color: flare.color.asArray(),
  17710. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  17711. });
  17712. }
  17713. return serializationObject;
  17714. };
  17715. var serializeShadowGenerator = function (light) {
  17716. var serializationObject = {};
  17717. var shadowGenerator = light.getShadowGenerator();
  17718. serializationObject.lightId = light.id;
  17719. serializationObject.mapSize = shadowGenerator.getShadowMap().getRenderSize();
  17720. serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
  17721. serializationObject.usePoissonSampling = shadowGenerator.usePoissonSampling;
  17722. serializationObject.renderList = [];
  17723. for (var meshIndex = 0; meshIndex < shadowGenerator.getShadowMap().renderList.length; meshIndex++) {
  17724. var mesh = shadowGenerator.getShadowMap().renderList[meshIndex];
  17725. serializationObject.renderList.push(mesh.id);
  17726. }
  17727. return serializationObject;
  17728. };
  17729. var serializedGeometries = [];
  17730. var serializeGeometry = function (geometry, serializationGeometries) {
  17731. if (serializedGeometries[geometry.id]) {
  17732. return;
  17733. }
  17734. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  17735. serializationGeometries.boxes.push(serializeBox(geometry));
  17736. }
  17737. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  17738. serializationGeometries.spheres.push(serializeSphere(geometry));
  17739. }
  17740. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  17741. serializationGeometries.cylinders.push(serializeCylinder(geometry));
  17742. }
  17743. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  17744. serializationGeometries.toruses.push(serializeTorus(geometry));
  17745. }
  17746. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  17747. serializationGeometries.grounds.push(serializeGround(geometry));
  17748. }
  17749. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  17750. serializationGeometries.planes.push(serializePlane(geometry));
  17751. }
  17752. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  17753. serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
  17754. }
  17755. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  17756. throw new Error("Unknow primitive type");
  17757. }
  17758. else {
  17759. serializationGeometries.vertexData.push(serializeVertexData(geometry));
  17760. }
  17761. serializedGeometries[geometry.id] = true;
  17762. };
  17763. var serializeGeometryBase = function (geometry) {
  17764. var serializationObject = {};
  17765. serializationObject.id = geometry.id;
  17766. if (BABYLON.Tags.HasTags(geometry)) {
  17767. serializationObject.tags = BABYLON.Tags.GetTags(geometry);
  17768. }
  17769. return serializationObject;
  17770. };
  17771. var serializeVertexData = function (vertexData) {
  17772. var serializationObject = serializeGeometryBase(vertexData);
  17773. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  17774. serializationObject.positions = vertexData.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17775. }
  17776. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  17777. serializationObject.normals = vertexData.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17778. }
  17779. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  17780. serializationObject.uvs = vertexData.getVerticesData(BABYLON.VertexBuffer.UVKind);
  17781. }
  17782. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  17783. serializationObject.uvs2 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  17784. }
  17785. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  17786. serializationObject.colors = vertexData.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  17787. }
  17788. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  17789. serializationObject.matricesIndices = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  17790. serializationObject.matricesIndices._isExpanded = true;
  17791. }
  17792. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  17793. serializationObject.matricesWeights = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  17794. }
  17795. serializationObject.indices = vertexData.getIndices();
  17796. return serializationObject;
  17797. };
  17798. var serializePrimitive = function (primitive) {
  17799. var serializationObject = serializeGeometryBase(primitive);
  17800. serializationObject.canBeRegenerated = primitive.canBeRegenerated();
  17801. return serializationObject;
  17802. };
  17803. var serializeBox = function (box) {
  17804. var serializationObject = serializePrimitive(box);
  17805. serializationObject.size = box.size;
  17806. return serializationObject;
  17807. };
  17808. var serializeSphere = function (sphere) {
  17809. var serializationObject = serializePrimitive(sphere);
  17810. serializationObject.segments = sphere.segments;
  17811. serializationObject.diameter = sphere.diameter;
  17812. return serializationObject;
  17813. };
  17814. var serializeCylinder = function (cylinder) {
  17815. var serializationObject = serializePrimitive(cylinder);
  17816. serializationObject.height = cylinder.height;
  17817. serializationObject.diameterTop = cylinder.diameterTop;
  17818. serializationObject.diameterBottom = cylinder.diameterBottom;
  17819. serializationObject.tessellation = cylinder.tessellation;
  17820. return serializationObject;
  17821. };
  17822. var serializeTorus = function (torus) {
  17823. var serializationObject = serializePrimitive(torus);
  17824. serializationObject.diameter = torus.diameter;
  17825. serializationObject.thickness = torus.thickness;
  17826. serializationObject.tessellation = torus.tessellation;
  17827. return serializationObject;
  17828. };
  17829. var serializeGround = function (ground) {
  17830. var serializationObject = serializePrimitive(ground);
  17831. serializationObject.width = ground.width;
  17832. serializationObject.height = ground.height;
  17833. serializationObject.subdivisions = ground.subdivisions;
  17834. return serializationObject;
  17835. };
  17836. var serializePlane = function (plane) {
  17837. var serializationObject = serializePrimitive(plane);
  17838. serializationObject.size = plane.size;
  17839. return serializationObject;
  17840. };
  17841. var serializeTorusKnot = function (torusKnot) {
  17842. var serializationObject = serializePrimitive(torusKnot);
  17843. serializationObject.radius = torusKnot.radius;
  17844. serializationObject.tube = torusKnot.tube;
  17845. serializationObject.radialSegments = torusKnot.radialSegments;
  17846. serializationObject.tubularSegments = torusKnot.tubularSegments;
  17847. serializationObject.p = torusKnot.p;
  17848. serializationObject.q = torusKnot.q;
  17849. return serializationObject;
  17850. };
  17851. var serializeMesh = function (mesh, serializationScene) {
  17852. var serializationObject = {};
  17853. serializationObject.name = mesh.name;
  17854. serializationObject.id = mesh.id;
  17855. if (BABYLON.Tags.HasTags(mesh)) {
  17856. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  17857. }
  17858. serializationObject.position = mesh.position.asArray();
  17859. if (mesh.rotationQuaternion) {
  17860. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  17861. }
  17862. else if (mesh.rotation) {
  17863. serializationObject.rotation = mesh.rotation.asArray();
  17864. }
  17865. serializationObject.scaling = mesh.scaling.asArray();
  17866. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  17867. serializationObject.isEnabled = mesh.isEnabled();
  17868. serializationObject.isVisible = mesh.isVisible;
  17869. serializationObject.infiniteDistance = mesh.infiniteDistance;
  17870. serializationObject.pickable = mesh.isPickable;
  17871. serializationObject.receiveShadows = mesh.receiveShadows;
  17872. serializationObject.billboardMode = mesh.billboardMode;
  17873. serializationObject.visibility = mesh.visibility;
  17874. serializationObject.checkCollisions = mesh.checkCollisions;
  17875. // Parent
  17876. if (mesh.parent) {
  17877. serializationObject.parentId = mesh.parent.id;
  17878. }
  17879. // Geometry
  17880. var geometry = mesh._geometry;
  17881. if (geometry) {
  17882. var geometryId = geometry.id;
  17883. serializationObject.geometryId = geometryId;
  17884. if (!mesh.getScene().getGeometryByID(geometryId)) {
  17885. // geometry was in the memory but not added to the scene, nevertheless it's better to serialize too be able to reload the mesh with its geometry
  17886. serializeGeometry(geometry, serializationScene.geometries);
  17887. }
  17888. // SubMeshes
  17889. serializationObject.subMeshes = [];
  17890. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  17891. var subMesh = mesh.subMeshes[subIndex];
  17892. serializationObject.subMeshes.push({
  17893. materialIndex: subMesh.materialIndex,
  17894. verticesStart: subMesh.verticesStart,
  17895. verticesCount: subMesh.verticesCount,
  17896. indexStart: subMesh.indexStart,
  17897. indexCount: subMesh.indexCount
  17898. });
  17899. }
  17900. }
  17901. // Material
  17902. if (mesh.material) {
  17903. serializationObject.materialId = mesh.material.id;
  17904. }
  17905. else {
  17906. mesh.material = null;
  17907. }
  17908. // Skeleton
  17909. if (mesh.skeleton) {
  17910. serializationObject.skeletonId = mesh.skeleton.id;
  17911. }
  17912. // Physics
  17913. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  17914. serializationObject.physicsMass = mesh.getPhysicsMass();
  17915. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  17916. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  17917. switch (mesh.getPhysicsImpostor()) {
  17918. case BABYLON.PhysicsEngine.BoxImpostor:
  17919. serializationObject.physicsImpostor = 1;
  17920. break;
  17921. case BABYLON.PhysicsEngine.SphereImpostor:
  17922. serializationObject.physicsImpostor = 2;
  17923. break;
  17924. }
  17925. }
  17926. // Instances
  17927. serializationObject.instances = [];
  17928. for (var index = 0; index < mesh.instances.length; index++) {
  17929. var instance = mesh.instances[index];
  17930. var serializationInstance = {
  17931. name: instance.name,
  17932. position: instance.position,
  17933. rotation: instance.rotation,
  17934. rotationQuaternion: instance.rotationQuaternion,
  17935. scaling: instance.scaling
  17936. };
  17937. serializationObject.instances.push(serializationInstance);
  17938. // Animations
  17939. appendAnimations(instance, serializationInstance);
  17940. }
  17941. // Animations
  17942. appendAnimations(mesh, serializationObject);
  17943. // Layer mask
  17944. serializationObject.layerMask = mesh.layerMask;
  17945. return serializationObject;
  17946. };
  17947. var SceneSerializer = (function () {
  17948. function SceneSerializer() {
  17949. }
  17950. SceneSerializer.Serialize = function (scene) {
  17951. var serializationObject = {};
  17952. // Scene
  17953. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  17954. serializationObject.autoClear = scene.autoClear;
  17955. serializationObject.clearColor = scene.clearColor.asArray();
  17956. serializationObject.ambientColor = scene.ambientColor.asArray();
  17957. serializationObject.gravity = scene.gravity.asArray();
  17958. // Fog
  17959. if (scene.fogMode && scene.fogMode !== 0) {
  17960. serializationObject.fogMode = scene.fogMode;
  17961. serializationObject.fogColor = scene.fogColor.asArray();
  17962. serializationObject.fogStart = scene.fogStart;
  17963. serializationObject.fogEnd = scene.fogEnd;
  17964. serializationObject.fogDensity = scene.fogDensity;
  17965. }
  17966. // Lights
  17967. serializationObject.lights = [];
  17968. for (var index = 0; index < scene.lights.length; index++) {
  17969. var light = scene.lights[index];
  17970. serializationObject.lights.push(serializeLight(light));
  17971. }
  17972. // Cameras
  17973. serializationObject.cameras = [];
  17974. for (index = 0; index < scene.cameras.length; index++) {
  17975. var camera = scene.cameras[index];
  17976. if (camera instanceof BABYLON.FreeCamera) {
  17977. serializationObject.cameras.push(serializeCamera(camera));
  17978. }
  17979. }
  17980. if (scene.activeCamera) {
  17981. serializationObject.activeCameraID = scene.activeCamera.id;
  17982. }
  17983. // Materials
  17984. serializationObject.materials = [];
  17985. serializationObject.multiMaterials = [];
  17986. for (index = 0; index < scene.materials.length; index++) {
  17987. var material = scene.materials[index];
  17988. if (material instanceof BABYLON.StandardMaterial) {
  17989. serializationObject.materials.push(serializeMaterial(material));
  17990. }
  17991. else if (material instanceof BABYLON.MultiMaterial) {
  17992. serializationObject.multiMaterials.push(serializeMultiMaterial(material));
  17993. }
  17994. }
  17995. // Skeletons
  17996. serializationObject.skeletons = [];
  17997. for (index = 0; index < scene.skeletons.length; index++) {
  17998. serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
  17999. }
  18000. // Geometries
  18001. serializationObject.geometries = {};
  18002. serializationObject.geometries.boxes = [];
  18003. serializationObject.geometries.spheres = [];
  18004. serializationObject.geometries.cylinders = [];
  18005. serializationObject.geometries.toruses = [];
  18006. serializationObject.geometries.grounds = [];
  18007. serializationObject.geometries.planes = [];
  18008. serializationObject.geometries.torusKnots = [];
  18009. serializationObject.geometries.vertexData = [];
  18010. serializedGeometries = [];
  18011. var geometries = scene.getGeometries();
  18012. for (var index = 0; index < geometries.length; index++) {
  18013. var geometry = geometries[index];
  18014. if (geometry.isReady()) {
  18015. serializeGeometry(geometry, serializationObject.geometries);
  18016. }
  18017. }
  18018. // Meshes
  18019. serializationObject.meshes = [];
  18020. for (index = 0; index < scene.meshes.length; index++) {
  18021. var abstractMesh = scene.meshes[index];
  18022. if (abstractMesh instanceof BABYLON.Mesh) {
  18023. var mesh = abstractMesh;
  18024. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  18025. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  18026. }
  18027. }
  18028. }
  18029. // Particles Systems
  18030. serializationObject.particleSystems = [];
  18031. for (index = 0; index < scene.particleSystems.length; index++) {
  18032. serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
  18033. }
  18034. // Lens flares
  18035. serializationObject.lensFlareSystems = [];
  18036. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  18037. serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
  18038. }
  18039. // Shadows
  18040. serializationObject.shadowGenerators = [];
  18041. for (index = 0; index < scene.lights.length; index++) {
  18042. light = scene.lights[index];
  18043. if (light.getShadowGenerator()) {
  18044. serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
  18045. }
  18046. }
  18047. return serializationObject;
  18048. };
  18049. return SceneSerializer;
  18050. })();
  18051. BABYLON.SceneSerializer = SceneSerializer;
  18052. })(BABYLON || (BABYLON = {}));
  18053. //# sourceMappingURL=babylon.sceneSerializer.js.mapvar BABYLON;
  18054. (function (BABYLON) {
  18055. var SceneLoader = (function () {
  18056. function SceneLoader() {
  18057. }
  18058. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  18059. get: function () {
  18060. return SceneLoader._ForceFullSceneLoadingForIncremental;
  18061. },
  18062. set: function (value) {
  18063. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  18064. },
  18065. enumerable: true,
  18066. configurable: true
  18067. });
  18068. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  18069. get: function () {
  18070. return SceneLoader._ShowLoadingScreen;
  18071. },
  18072. set: function (value) {
  18073. SceneLoader._ShowLoadingScreen = value;
  18074. },
  18075. enumerable: true,
  18076. configurable: true
  18077. });
  18078. SceneLoader._getPluginForFilename = function (sceneFilename) {
  18079. var dotPosition = sceneFilename.lastIndexOf(".");
  18080. var queryStringPosition = sceneFilename.indexOf("?");
  18081. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  18082. for (var index = 0; index < this._registeredPlugins.length; index++) {
  18083. var plugin = this._registeredPlugins[index];
  18084. if (plugin.extensions.indexOf(extension) !== -1) {
  18085. return plugin;
  18086. }
  18087. }
  18088. return this._registeredPlugins[this._registeredPlugins.length - 1];
  18089. };
  18090. // Public functions
  18091. SceneLoader.RegisterPlugin = function (plugin) {
  18092. plugin.extensions = plugin.extensions.toLowerCase();
  18093. SceneLoader._registeredPlugins.push(plugin);
  18094. };
  18095. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  18096. var manifestChecked = function (success) {
  18097. scene.database = database;
  18098. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  18099. var importMeshFromData = function (data) {
  18100. var meshes = [];
  18101. var particleSystems = [];
  18102. var skeletons = [];
  18103. try {
  18104. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  18105. if (onerror) {
  18106. onerror(scene, 'unable to load the scene');
  18107. }
  18108. return;
  18109. }
  18110. }
  18111. catch (e) {
  18112. if (onerror) {
  18113. onerror(scene, e);
  18114. }
  18115. return;
  18116. }
  18117. if (onsuccess) {
  18118. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  18119. onsuccess(meshes, particleSystems, skeletons);
  18120. }
  18121. };
  18122. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  18123. // Direct load
  18124. importMeshFromData(sceneFilename.substr(5));
  18125. return;
  18126. }
  18127. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  18128. importMeshFromData(data);
  18129. }, progressCallBack, database);
  18130. };
  18131. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  18132. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  18133. };
  18134. /**
  18135. * Load a scene
  18136. * @param rootUrl a string that defines the root url for scene and resources
  18137. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  18138. * @param engine is the instance of BABYLON.Engine to use to create the scene
  18139. */
  18140. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  18141. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  18142. };
  18143. /**
  18144. * Append a scene
  18145. * @param rootUrl a string that defines the root url for scene and resources
  18146. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  18147. * @param scene is the instance of BABYLON.Scene to append to
  18148. */
  18149. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  18150. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  18151. var database;
  18152. if (SceneLoader.ShowLoadingScreen) {
  18153. scene.getEngine().displayLoadingUI();
  18154. }
  18155. var loadSceneFromData = function (data) {
  18156. scene.database = database;
  18157. if (!plugin.load(scene, data, rootUrl)) {
  18158. if (onerror) {
  18159. onerror(scene);
  18160. }
  18161. scene.getEngine().hideLoadingUI();
  18162. return;
  18163. }
  18164. if (onsuccess) {
  18165. onsuccess(scene);
  18166. }
  18167. if (SceneLoader.ShowLoadingScreen) {
  18168. scene.executeWhenReady(function () {
  18169. scene.getEngine().hideLoadingUI();
  18170. });
  18171. }
  18172. };
  18173. var manifestChecked = function (success) {
  18174. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  18175. };
  18176. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  18177. // Direct load
  18178. loadSceneFromData(sceneFilename.substr(5));
  18179. return;
  18180. }
  18181. if (rootUrl.indexOf("file:") === -1) {
  18182. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  18183. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  18184. }
  18185. else {
  18186. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  18187. }
  18188. };
  18189. // Flags
  18190. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  18191. SceneLoader._ShowLoadingScreen = true;
  18192. // Members
  18193. SceneLoader._registeredPlugins = new Array();
  18194. return SceneLoader;
  18195. })();
  18196. BABYLON.SceneLoader = SceneLoader;
  18197. ;
  18198. })(BABYLON || (BABYLON = {}));
  18199. //# sourceMappingURL=babylon.sceneLoader.js.mapvar BABYLON;
  18200. (function (BABYLON) {
  18201. var Internals;
  18202. (function (Internals) {
  18203. var checkColors4 = function (colors, count) {
  18204. // Check if color3 was used
  18205. if (colors.length === count * 3) {
  18206. var colors4 = [];
  18207. for (var index = 0; index < colors.length; index += 3) {
  18208. var newIndex = (index / 3) * 4;
  18209. colors4[newIndex] = colors[index];
  18210. colors4[newIndex + 1] = colors[index + 1];
  18211. colors4[newIndex + 2] = colors[index + 2];
  18212. colors4[newIndex + 3] = 1.0;
  18213. }
  18214. return colors4;
  18215. }
  18216. return colors;
  18217. };
  18218. var loadCubeTexture = function (rootUrl, parsedTexture, scene) {
  18219. var texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene);
  18220. texture.name = parsedTexture.name;
  18221. texture.hasAlpha = parsedTexture.hasAlpha;
  18222. texture.level = parsedTexture.level;
  18223. texture.coordinatesMode = parsedTexture.coordinatesMode;
  18224. return texture;
  18225. };
  18226. var loadTexture = function (rootUrl, parsedTexture, scene) {
  18227. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  18228. return null;
  18229. }
  18230. if (parsedTexture.isCube) {
  18231. return loadCubeTexture(rootUrl, parsedTexture, scene);
  18232. }
  18233. var texture;
  18234. if (parsedTexture.mirrorPlane) {
  18235. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  18236. texture._waitingRenderList = parsedTexture.renderList;
  18237. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  18238. }
  18239. else if (parsedTexture.isRenderTarget) {
  18240. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  18241. texture._waitingRenderList = parsedTexture.renderList;
  18242. }
  18243. else {
  18244. texture = new BABYLON.Texture(rootUrl + parsedTexture.name, scene);
  18245. }
  18246. texture.name = parsedTexture.name;
  18247. texture.hasAlpha = parsedTexture.hasAlpha;
  18248. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  18249. texture.level = parsedTexture.level;
  18250. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  18251. texture.coordinatesMode = parsedTexture.coordinatesMode;
  18252. texture.uOffset = parsedTexture.uOffset;
  18253. texture.vOffset = parsedTexture.vOffset;
  18254. texture.uScale = parsedTexture.uScale;
  18255. texture.vScale = parsedTexture.vScale;
  18256. texture.uAng = parsedTexture.uAng;
  18257. texture.vAng = parsedTexture.vAng;
  18258. texture.wAng = parsedTexture.wAng;
  18259. texture.wrapU = parsedTexture.wrapU;
  18260. texture.wrapV = parsedTexture.wrapV;
  18261. // Animations
  18262. if (parsedTexture.animations) {
  18263. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  18264. var parsedAnimation = parsedTexture.animations[animationIndex];
  18265. texture.animations.push(parseAnimation(parsedAnimation));
  18266. }
  18267. }
  18268. return texture;
  18269. };
  18270. var parseSkeleton = function (parsedSkeleton, scene) {
  18271. var skeleton = new BABYLON.Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  18272. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  18273. var parsedBone = parsedSkeleton.bones[index];
  18274. var parentBone = null;
  18275. if (parsedBone.parentBoneIndex > -1) {
  18276. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  18277. }
  18278. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  18279. if (parsedBone.animation) {
  18280. bone.animations.push(parseAnimation(parsedBone.animation));
  18281. }
  18282. }
  18283. return skeleton;
  18284. };
  18285. var parseFresnelParameters = function (parsedFresnelParameters) {
  18286. var fresnelParameters = new BABYLON.FresnelParameters();
  18287. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  18288. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  18289. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  18290. fresnelParameters.bias = parsedFresnelParameters.bias;
  18291. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  18292. return fresnelParameters;
  18293. };
  18294. var parseMaterial = function (parsedMaterial, scene, rootUrl) {
  18295. var material;
  18296. material = new BABYLON.StandardMaterial(parsedMaterial.name, scene);
  18297. material.ambientColor = BABYLON.Color3.FromArray(parsedMaterial.ambient);
  18298. material.diffuseColor = BABYLON.Color3.FromArray(parsedMaterial.diffuse);
  18299. material.specularColor = BABYLON.Color3.FromArray(parsedMaterial.specular);
  18300. material.specularPower = parsedMaterial.specularPower;
  18301. material.emissiveColor = BABYLON.Color3.FromArray(parsedMaterial.emissive);
  18302. material.alpha = parsedMaterial.alpha;
  18303. material.id = parsedMaterial.id;
  18304. BABYLON.Tags.AddTagsTo(material, parsedMaterial.tags);
  18305. material.backFaceCulling = parsedMaterial.backFaceCulling;
  18306. material.wireframe = parsedMaterial.wireframe;
  18307. if (parsedMaterial.diffuseTexture) {
  18308. material.diffuseTexture = loadTexture(rootUrl, parsedMaterial.diffuseTexture, scene);
  18309. }
  18310. if (parsedMaterial.diffuseFresnelParameters) {
  18311. material.diffuseFresnelParameters = parseFresnelParameters(parsedMaterial.diffuseFresnelParameters);
  18312. }
  18313. if (parsedMaterial.ambientTexture) {
  18314. material.ambientTexture = loadTexture(rootUrl, parsedMaterial.ambientTexture, scene);
  18315. }
  18316. if (parsedMaterial.opacityTexture) {
  18317. material.opacityTexture = loadTexture(rootUrl, parsedMaterial.opacityTexture, scene);
  18318. }
  18319. if (parsedMaterial.opacityFresnelParameters) {
  18320. material.opacityFresnelParameters = parseFresnelParameters(parsedMaterial.opacityFresnelParameters);
  18321. }
  18322. if (parsedMaterial.reflectionTexture) {
  18323. material.reflectionTexture = loadTexture(rootUrl, parsedMaterial.reflectionTexture, scene);
  18324. }
  18325. if (parsedMaterial.reflectionFresnelParameters) {
  18326. material.reflectionFresnelParameters = parseFresnelParameters(parsedMaterial.reflectionFresnelParameters);
  18327. }
  18328. if (parsedMaterial.emissiveTexture) {
  18329. material.emissiveTexture = loadTexture(rootUrl, parsedMaterial.emissiveTexture, scene);
  18330. }
  18331. if (parsedMaterial.emissiveFresnelParameters) {
  18332. material.emissiveFresnelParameters = parseFresnelParameters(parsedMaterial.emissiveFresnelParameters);
  18333. }
  18334. if (parsedMaterial.specularTexture) {
  18335. material.specularTexture = loadTexture(rootUrl, parsedMaterial.specularTexture, scene);
  18336. }
  18337. if (parsedMaterial.bumpTexture) {
  18338. material.bumpTexture = loadTexture(rootUrl, parsedMaterial.bumpTexture, scene);
  18339. }
  18340. return material;
  18341. };
  18342. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  18343. for (var index = 0; index < parsedData.materials.length; index++) {
  18344. var parsedMaterial = parsedData.materials[index];
  18345. if (parsedMaterial.id === id) {
  18346. return parseMaterial(parsedMaterial, scene, rootUrl);
  18347. }
  18348. }
  18349. return null;
  18350. };
  18351. var parseMultiMaterial = function (parsedMultiMaterial, scene) {
  18352. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  18353. multiMaterial.id = parsedMultiMaterial.id;
  18354. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  18355. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  18356. var subMatId = parsedMultiMaterial.materials[matIndex];
  18357. if (subMatId) {
  18358. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  18359. }
  18360. else {
  18361. multiMaterial.subMaterials.push(null);
  18362. }
  18363. }
  18364. return multiMaterial;
  18365. };
  18366. var parseLensFlareSystem = function (parsedLensFlareSystem, scene, rootUrl) {
  18367. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  18368. var lensFlareSystem = new BABYLON.LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  18369. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  18370. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  18371. var parsedFlare = parsedLensFlareSystem.flares[index];
  18372. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  18373. }
  18374. return lensFlareSystem;
  18375. };
  18376. var parseParticleSystem = function (parsedParticleSystem, scene, rootUrl) {
  18377. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  18378. var particleSystem = new BABYLON.ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  18379. if (parsedParticleSystem.textureName) {
  18380. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  18381. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  18382. }
  18383. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  18384. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  18385. particleSystem.minSize = parsedParticleSystem.minSize;
  18386. particleSystem.maxSize = parsedParticleSystem.maxSize;
  18387. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  18388. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  18389. particleSystem.emitter = emitter;
  18390. particleSystem.emitRate = parsedParticleSystem.emitRate;
  18391. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  18392. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  18393. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  18394. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  18395. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  18396. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  18397. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  18398. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  18399. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  18400. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  18401. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  18402. particleSystem.blendMode = parsedParticleSystem.blendMode;
  18403. particleSystem.start();
  18404. return particleSystem;
  18405. };
  18406. var parseShadowGenerator = function (parsedShadowGenerator, scene) {
  18407. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  18408. var shadowGenerator = new BABYLON.ShadowGenerator(parsedShadowGenerator.mapSize, light);
  18409. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  18410. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  18411. shadowGenerator.getShadowMap().renderList.push(mesh);
  18412. }
  18413. if (parsedShadowGenerator.usePoissonSampling) {
  18414. shadowGenerator.usePoissonSampling = true;
  18415. }
  18416. else {
  18417. shadowGenerator.useVarianceShadowMap = parsedShadowGenerator.useVarianceShadowMap;
  18418. }
  18419. return shadowGenerator;
  18420. };
  18421. var parseAnimation = function (parsedAnimation) {
  18422. var animation = new BABYLON.Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  18423. var dataType = parsedAnimation.dataType;
  18424. var keys = [];
  18425. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  18426. var key = parsedAnimation.keys[index];
  18427. var data;
  18428. switch (dataType) {
  18429. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  18430. data = key.values[0];
  18431. break;
  18432. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  18433. data = BABYLON.Quaternion.FromArray(key.values);
  18434. break;
  18435. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  18436. data = BABYLON.Matrix.FromArray(key.values);
  18437. break;
  18438. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  18439. default:
  18440. data = BABYLON.Vector3.FromArray(key.values);
  18441. break;
  18442. }
  18443. keys.push({
  18444. frame: key.frame,
  18445. value: data
  18446. });
  18447. }
  18448. animation.setKeys(keys);
  18449. return animation;
  18450. };
  18451. var parseLight = function (parsedLight, scene) {
  18452. var light;
  18453. switch (parsedLight.type) {
  18454. case 0:
  18455. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  18456. break;
  18457. case 1:
  18458. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  18459. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  18460. break;
  18461. case 2:
  18462. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  18463. break;
  18464. case 3:
  18465. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  18466. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  18467. break;
  18468. }
  18469. light.id = parsedLight.id;
  18470. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  18471. if (parsedLight.intensity !== undefined) {
  18472. light.intensity = parsedLight.intensity;
  18473. }
  18474. if (parsedLight.range) {
  18475. light.range = parsedLight.range;
  18476. }
  18477. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  18478. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  18479. if (parsedLight.excludedMeshesIds) {
  18480. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  18481. }
  18482. // Parent
  18483. if (parsedLight.parentId) {
  18484. light._waitingParentId = parsedLight.parentId;
  18485. }
  18486. if (parsedLight.includedOnlyMeshesIds) {
  18487. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  18488. }
  18489. // Animations
  18490. if (parsedLight.animations) {
  18491. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  18492. var parsedAnimation = parsedLight.animations[animationIndex];
  18493. light.animations.push(parseAnimation(parsedAnimation));
  18494. }
  18495. }
  18496. if (parsedLight.autoAnimate) {
  18497. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  18498. }
  18499. };
  18500. var parseCamera = function (parsedCamera, scene) {
  18501. var camera;
  18502. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  18503. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  18504. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  18505. var alpha = parsedCamera.alpha;
  18506. var beta = parsedCamera.beta;
  18507. var radius = parsedCamera.radius;
  18508. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  18509. var eye_space = parsedCamera.eye_space;
  18510. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, eye_space, scene);
  18511. }
  18512. else {
  18513. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  18514. }
  18515. }
  18516. else if (parsedCamera.type === "AnaglyphFreeCamera") {
  18517. eye_space = parsedCamera.eye_space;
  18518. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, eye_space, scene);
  18519. }
  18520. else if (parsedCamera.type === "DeviceOrientationCamera") {
  18521. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  18522. }
  18523. else if (parsedCamera.type === "FollowCamera") {
  18524. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  18525. camera.heightOffset = parsedCamera.heightOffset;
  18526. camera.radius = parsedCamera.radius;
  18527. camera.rotationOffset = parsedCamera.rotationOffset;
  18528. if (lockedTargetMesh)
  18529. camera.target = lockedTargetMesh;
  18530. }
  18531. else if (parsedCamera.type === "GamepadCamera") {
  18532. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  18533. }
  18534. else if (parsedCamera.type === "OculusCamera") {
  18535. camera = new BABYLON.OculusCamera(parsedCamera.name, position, scene);
  18536. }
  18537. else if (parsedCamera.type === "OculusGamepadCamera") {
  18538. camera = new BABYLON.OculusGamepadCamera(parsedCamera.name, position, scene);
  18539. }
  18540. else if (parsedCamera.type === "TouchCamera") {
  18541. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  18542. }
  18543. else if (parsedCamera.type === "VirtualJoysticksCamera") {
  18544. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  18545. }
  18546. else if (parsedCamera.type === "WebVRCamera") {
  18547. camera = new BABYLON.WebVRCamera(parsedCamera.name, position, scene);
  18548. }
  18549. else if (parsedCamera.type === "VRDeviceOrientationCamera") {
  18550. camera = new BABYLON.VRDeviceOrientationCamera(parsedCamera.name, position, scene);
  18551. }
  18552. else {
  18553. // Free Camera is the default value
  18554. camera = new BABYLON.FreeCamera(parsedCamera.name, position, scene);
  18555. }
  18556. // Test for lockedTargetMesh & FreeCamera outside of if-else-if nest, since things like GamepadCamera extend FreeCamera
  18557. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  18558. camera.lockedTarget = lockedTargetMesh;
  18559. }
  18560. camera.id = parsedCamera.id;
  18561. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  18562. // Parent
  18563. if (parsedCamera.parentId) {
  18564. camera._waitingParentId = parsedCamera.parentId;
  18565. }
  18566. // Target
  18567. if (parsedCamera.target) {
  18568. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  18569. }
  18570. else {
  18571. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  18572. }
  18573. camera.fov = parsedCamera.fov;
  18574. camera.minZ = parsedCamera.minZ;
  18575. camera.maxZ = parsedCamera.maxZ;
  18576. camera.speed = parsedCamera.speed;
  18577. camera.inertia = parsedCamera.inertia;
  18578. camera.checkCollisions = parsedCamera.checkCollisions;
  18579. camera.applyGravity = parsedCamera.applyGravity;
  18580. if (parsedCamera.ellipsoid) {
  18581. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  18582. }
  18583. // Animations
  18584. if (parsedCamera.animations) {
  18585. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  18586. var parsedAnimation = parsedCamera.animations[animationIndex];
  18587. camera.animations.push(parseAnimation(parsedAnimation));
  18588. }
  18589. }
  18590. if (parsedCamera.autoAnimate) {
  18591. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  18592. }
  18593. // Layer Mask
  18594. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  18595. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  18596. }
  18597. else {
  18598. camera.layerMask = 0xFFFFFFFF;
  18599. }
  18600. return camera;
  18601. };
  18602. var parseGeometry = function (parsedGeometry, scene) {
  18603. var id = parsedGeometry.id;
  18604. return scene.getGeometryByID(id);
  18605. };
  18606. var parseBox = function (parsedBox, scene) {
  18607. if (parseGeometry(parsedBox, scene)) {
  18608. return null; // null since geometry could be something else than a box...
  18609. }
  18610. var box = new BABYLON.Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  18611. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  18612. scene.pushGeometry(box, true);
  18613. return box;
  18614. };
  18615. var parseSphere = function (parsedSphere, scene) {
  18616. if (parseGeometry(parsedSphere, scene)) {
  18617. return null; // null since geometry could be something else than a sphere...
  18618. }
  18619. var sphere = new BABYLON.Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  18620. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  18621. scene.pushGeometry(sphere, true);
  18622. return sphere;
  18623. };
  18624. var parseCylinder = function (parsedCylinder, scene) {
  18625. if (parseGeometry(parsedCylinder, scene)) {
  18626. return null; // null since geometry could be something else than a cylinder...
  18627. }
  18628. var cylinder = new BABYLON.Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  18629. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  18630. scene.pushGeometry(cylinder, true);
  18631. return cylinder;
  18632. };
  18633. var parseTorus = function (parsedTorus, scene) {
  18634. if (parseGeometry(parsedTorus, scene)) {
  18635. return null; // null since geometry could be something else than a torus...
  18636. }
  18637. var torus = new BABYLON.Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  18638. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  18639. scene.pushGeometry(torus, true);
  18640. return torus;
  18641. };
  18642. var parseGround = function (parsedGround, scene) {
  18643. if (parseGeometry(parsedGround, scene)) {
  18644. return null; // null since geometry could be something else than a ground...
  18645. }
  18646. var ground = new BABYLON.Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  18647. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  18648. scene.pushGeometry(ground, true);
  18649. return ground;
  18650. };
  18651. var parsePlane = function (parsedPlane, scene) {
  18652. if (parseGeometry(parsedPlane, scene)) {
  18653. return null; // null since geometry could be something else than a plane...
  18654. }
  18655. var plane = new BABYLON.Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  18656. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  18657. scene.pushGeometry(plane, true);
  18658. return plane;
  18659. };
  18660. var parseTorusKnot = function (parsedTorusKnot, scene) {
  18661. if (parseGeometry(parsedTorusKnot, scene)) {
  18662. return null; // null since geometry could be something else than a torusKnot...
  18663. }
  18664. var torusKnot = new BABYLON.Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  18665. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  18666. scene.pushGeometry(torusKnot, true);
  18667. return torusKnot;
  18668. };
  18669. var parseVertexData = function (parsedVertexData, scene, rootUrl) {
  18670. if (parseGeometry(parsedVertexData, scene)) {
  18671. return null; // null since geometry could be a primitive
  18672. }
  18673. var geometry = new BABYLON.Geometry(parsedVertexData.id, scene);
  18674. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  18675. if (parsedVertexData.delayLoadingFile) {
  18676. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  18677. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  18678. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  18679. geometry._delayInfo = [];
  18680. if (parsedVertexData.hasUVs) {
  18681. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  18682. }
  18683. if (parsedVertexData.hasUVs2) {
  18684. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  18685. }
  18686. if (parsedVertexData.hasColors) {
  18687. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  18688. }
  18689. if (parsedVertexData.hasMatricesIndices) {
  18690. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  18691. }
  18692. if (parsedVertexData.hasMatricesWeights) {
  18693. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  18694. }
  18695. geometry._delayLoadingFunction = importVertexData;
  18696. }
  18697. else {
  18698. importVertexData(parsedVertexData, geometry);
  18699. }
  18700. scene.pushGeometry(geometry, true);
  18701. return geometry;
  18702. };
  18703. var parseMesh = function (parsedMesh, scene, rootUrl) {
  18704. var mesh = new BABYLON.Mesh(parsedMesh.name, scene);
  18705. mesh.id = parsedMesh.id;
  18706. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  18707. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  18708. if (parsedMesh.rotationQuaternion) {
  18709. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  18710. }
  18711. else if (parsedMesh.rotation) {
  18712. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  18713. }
  18714. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  18715. if (parsedMesh.localMatrix) {
  18716. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  18717. }
  18718. else if (parsedMesh.pivotMatrix) {
  18719. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  18720. }
  18721. mesh.setEnabled(parsedMesh.isEnabled);
  18722. mesh.isVisible = parsedMesh.isVisible;
  18723. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  18724. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  18725. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  18726. if (parsedMesh.applyFog !== undefined) {
  18727. mesh.applyFog = parsedMesh.applyFog;
  18728. }
  18729. if (parsedMesh.pickable !== undefined) {
  18730. mesh.isPickable = parsedMesh.pickable;
  18731. }
  18732. if (parsedMesh.alphaIndex !== undefined) {
  18733. mesh.alphaIndex = parsedMesh.alphaIndex;
  18734. }
  18735. mesh.receiveShadows = parsedMesh.receiveShadows;
  18736. mesh.billboardMode = parsedMesh.billboardMode;
  18737. if (parsedMesh.visibility !== undefined) {
  18738. mesh.visibility = parsedMesh.visibility;
  18739. }
  18740. mesh.checkCollisions = parsedMesh.checkCollisions;
  18741. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  18742. // Parent
  18743. if (parsedMesh.parentId) {
  18744. mesh._waitingParentId = parsedMesh.parentId;
  18745. }
  18746. // Actions
  18747. if (parsedMesh.actions !== undefined) {
  18748. mesh._waitingActions = parsedMesh.actions;
  18749. }
  18750. // Geometry
  18751. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  18752. if (parsedMesh.delayLoadingFile) {
  18753. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  18754. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  18755. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  18756. if (parsedMesh._binaryInfo) {
  18757. mesh._binaryInfo = parsedMesh._binaryInfo;
  18758. }
  18759. mesh._delayInfo = [];
  18760. if (parsedMesh.hasUVs) {
  18761. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  18762. }
  18763. if (parsedMesh.hasUVs2) {
  18764. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  18765. }
  18766. if (parsedMesh.hasColors) {
  18767. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  18768. }
  18769. if (parsedMesh.hasMatricesIndices) {
  18770. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  18771. }
  18772. if (parsedMesh.hasMatricesWeights) {
  18773. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  18774. }
  18775. mesh._delayLoadingFunction = importGeometry;
  18776. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  18777. mesh._checkDelayState();
  18778. }
  18779. }
  18780. else {
  18781. importGeometry(parsedMesh, mesh);
  18782. }
  18783. // Material
  18784. if (parsedMesh.materialId) {
  18785. mesh.setMaterialByID(parsedMesh.materialId);
  18786. }
  18787. else {
  18788. mesh.material = null;
  18789. }
  18790. // Skeleton
  18791. if (parsedMesh.skeletonId > -1) {
  18792. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  18793. }
  18794. // Physics
  18795. if (parsedMesh.physicsImpostor) {
  18796. if (!scene.isPhysicsEnabled()) {
  18797. scene.enablePhysics();
  18798. }
  18799. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  18800. }
  18801. // Animations
  18802. if (parsedMesh.animations) {
  18803. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  18804. var parsedAnimation = parsedMesh.animations[animationIndex];
  18805. mesh.animations.push(parseAnimation(parsedAnimation));
  18806. }
  18807. }
  18808. if (parsedMesh.autoAnimate) {
  18809. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  18810. }
  18811. // Layer Mask
  18812. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  18813. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  18814. }
  18815. else {
  18816. mesh.layerMask = 0xFFFFFFFF;
  18817. }
  18818. // Instances
  18819. if (parsedMesh.instances) {
  18820. for (var index = 0; index < parsedMesh.instances.length; index++) {
  18821. var parsedInstance = parsedMesh.instances[index];
  18822. var instance = mesh.createInstance(parsedInstance.name);
  18823. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  18824. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  18825. if (parsedInstance.rotationQuaternion) {
  18826. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  18827. }
  18828. else if (parsedInstance.rotation) {
  18829. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  18830. }
  18831. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  18832. instance.checkCollisions = mesh.checkCollisions;
  18833. if (parsedMesh.animations) {
  18834. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  18835. parsedAnimation = parsedMesh.animations[animationIndex];
  18836. instance.animations.push(parseAnimation(parsedAnimation));
  18837. }
  18838. }
  18839. }
  18840. }
  18841. return mesh;
  18842. };
  18843. var parseActions = function (parsedActions, object, scene) {
  18844. var actionManager = new BABYLON.ActionManager(scene);
  18845. if (object === null)
  18846. scene.actionManager = actionManager;
  18847. else
  18848. object.actionManager = actionManager;
  18849. // instanciate a new object
  18850. var instanciate = function (name, params) {
  18851. var newInstance = Object.create(BABYLON[name].prototype);
  18852. newInstance.constructor.apply(newInstance, params);
  18853. return newInstance;
  18854. };
  18855. var parseParameter = function (name, value, target, propertyPath) {
  18856. if (propertyPath === null) {
  18857. // String, boolean or float
  18858. var floatValue = parseFloat(value);
  18859. if (value === "true" || value === "false")
  18860. return value === "true";
  18861. else
  18862. return isNaN(floatValue) ? value : floatValue;
  18863. }
  18864. var effectiveTarget = propertyPath.split(".");
  18865. var values = value.split(",");
  18866. for (var i = 0; i < effectiveTarget.length; i++) {
  18867. target = target[effectiveTarget[i]];
  18868. }
  18869. // Return appropriate value with its type
  18870. if (target instanceof Boolean)
  18871. return values[0] === "true";
  18872. if (target instanceof String)
  18873. return values[0];
  18874. // Parameters with multiple values such as Vector3 etc.
  18875. var split = new Array();
  18876. for (var i = 0; i < values.length; i++)
  18877. split.push(parseFloat(values[i]));
  18878. if (target instanceof BABYLON.Vector3)
  18879. return BABYLON.Vector3.FromArray(split);
  18880. if (target instanceof BABYLON.Vector4)
  18881. return BABYLON.Vector4.FromArray(split);
  18882. if (target instanceof BABYLON.Color3)
  18883. return BABYLON.Color3.FromArray(split);
  18884. if (target instanceof BABYLON.Color4)
  18885. return BABYLON.Color4.FromArray(split);
  18886. return parseFloat(values[0]);
  18887. };
  18888. // traverse graph per trigger
  18889. var traverse = function (parsedAction, trigger, condition, action) {
  18890. var parameters = new Array();
  18891. var target = null;
  18892. var propertyPath = null;
  18893. // Parameters
  18894. if (parsedAction.type === 2)
  18895. parameters.push(actionManager);
  18896. else
  18897. parameters.push(trigger);
  18898. for (var i = 0; i < parsedAction.properties.length; i++) {
  18899. var value = parsedAction.properties[i].value;
  18900. var name = parsedAction.properties[i].name;
  18901. if (name === "target")
  18902. value = target = scene.getNodeByName(value);
  18903. else if (name === "parent")
  18904. value = scene.getNodeByName(value);
  18905. else if (name === "sound")
  18906. value = scene.getSoundByName(value);
  18907. else if (name !== "propertyPath") {
  18908. if (parsedAction.type === 2 && name === "operator")
  18909. value = BABYLON.ValueCondition[value];
  18910. else
  18911. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  18912. }
  18913. else {
  18914. propertyPath = value;
  18915. }
  18916. parameters.push(value);
  18917. }
  18918. parameters.push(condition);
  18919. // If interpolate value action
  18920. if (parsedAction.name === "InterpolateValueAction") {
  18921. var param = parameters[parameters.length - 2];
  18922. parameters[parameters.length - 1] = param;
  18923. parameters[parameters.length - 2] = condition;
  18924. }
  18925. // Action or condition(s)
  18926. var newAction = instanciate(parsedAction.name, parameters);
  18927. if (newAction instanceof BABYLON.Condition) {
  18928. condition = newAction;
  18929. newAction = action;
  18930. }
  18931. else {
  18932. condition = null;
  18933. if (action)
  18934. action.then(newAction);
  18935. else
  18936. actionManager.registerAction(newAction);
  18937. }
  18938. for (var i = 0; i < parsedAction.children.length; i++)
  18939. traverse(parsedAction.children[i], trigger, condition, newAction);
  18940. };
  18941. for (var i = 0; i < parsedActions.children.length; i++) {
  18942. var triggerParams;
  18943. var trigger = parsedActions.children[i];
  18944. if (trigger.properties.length > 0) {
  18945. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: scene.getMeshByName(trigger.properties[0].value) };
  18946. }
  18947. else
  18948. triggerParams = BABYLON.ActionManager[trigger.name];
  18949. for (var j = 0; j < trigger.children.length; j++)
  18950. traverse(trigger.children[j], triggerParams, null, null);
  18951. }
  18952. };
  18953. var parseSound = function (parsedSound, scene, rootUrl) {
  18954. var soundName = parsedSound.name;
  18955. var soundUrl = rootUrl + soundName;
  18956. var options = {
  18957. autoplay: parsedSound.autoplay,
  18958. loop: parsedSound.loop,
  18959. volume: parsedSound.volume,
  18960. spatialSound: parsedSound.spatialSound,
  18961. maxDistance: parsedSound.maxDistance,
  18962. rolloffFactor: parsedSound.rolloffFactor,
  18963. refDistance: parsedSound.refDistance,
  18964. distanceModel: parsedSound.distanceModel,
  18965. panningModel: parsedSound.panningModel,
  18966. playbackRate: parsedSound.playbackRate
  18967. };
  18968. var newSound = new BABYLON.Sound(soundName, soundUrl, scene, function () {
  18969. scene._removePendingData(newSound);
  18970. }, options);
  18971. scene._addPendingData(newSound);
  18972. if (parsedSound.position) {
  18973. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  18974. newSound.setPosition(soundPosition);
  18975. }
  18976. if (parsedSound.isDirectional) {
  18977. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  18978. if (parsedSound.localDirectionToMesh) {
  18979. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  18980. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  18981. }
  18982. }
  18983. if (parsedSound.connectedMeshId) {
  18984. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  18985. if (connectedMesh) {
  18986. newSound.attachToMesh(connectedMesh);
  18987. }
  18988. }
  18989. };
  18990. var isDescendantOf = function (mesh, names, hierarchyIds) {
  18991. names = (names instanceof Array) ? names : [names];
  18992. for (var i in names) {
  18993. if (mesh.name === names[i]) {
  18994. hierarchyIds.push(mesh.id);
  18995. return true;
  18996. }
  18997. }
  18998. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  18999. hierarchyIds.push(mesh.id);
  19000. return true;
  19001. }
  19002. return false;
  19003. };
  19004. var importVertexData = function (parsedVertexData, geometry) {
  19005. var vertexData = new BABYLON.VertexData();
  19006. // positions
  19007. var positions = parsedVertexData.positions;
  19008. if (positions) {
  19009. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  19010. }
  19011. // normals
  19012. var normals = parsedVertexData.normals;
  19013. if (normals) {
  19014. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  19015. }
  19016. // uvs
  19017. var uvs = parsedVertexData.uvs;
  19018. if (uvs) {
  19019. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  19020. }
  19021. // uv2s
  19022. var uv2s = parsedVertexData.uv2s;
  19023. if (uv2s) {
  19024. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  19025. }
  19026. // colors
  19027. var colors = parsedVertexData.colors;
  19028. if (colors) {
  19029. vertexData.set(checkColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  19030. }
  19031. // matricesIndices
  19032. var matricesIndices = parsedVertexData.matricesIndices;
  19033. if (matricesIndices) {
  19034. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  19035. }
  19036. // matricesWeights
  19037. var matricesWeights = parsedVertexData.matricesWeights;
  19038. if (matricesWeights) {
  19039. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  19040. }
  19041. // indices
  19042. var indices = parsedVertexData.indices;
  19043. if (indices) {
  19044. vertexData.indices = indices;
  19045. }
  19046. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  19047. };
  19048. var importGeometry = function (parsedGeometry, mesh) {
  19049. var scene = mesh.getScene();
  19050. // Geometry
  19051. var geometryId = parsedGeometry.geometryId;
  19052. if (geometryId) {
  19053. var geometry = scene.getGeometryByID(geometryId);
  19054. if (geometry) {
  19055. geometry.applyToMesh(mesh);
  19056. }
  19057. }
  19058. else if (parsedGeometry instanceof ArrayBuffer) {
  19059. var binaryInfo = mesh._binaryInfo;
  19060. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  19061. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  19062. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  19063. }
  19064. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  19065. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  19066. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  19067. }
  19068. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  19069. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  19070. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  19071. }
  19072. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  19073. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  19074. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  19075. }
  19076. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  19077. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  19078. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false);
  19079. }
  19080. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  19081. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  19082. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  19083. }
  19084. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  19085. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  19086. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  19087. }
  19088. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  19089. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  19090. mesh.setIndices(indicesData);
  19091. }
  19092. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  19093. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  19094. mesh.subMeshes = [];
  19095. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  19096. var materialIndex = subMeshesData[(i * 5) + 0];
  19097. var verticesStart = subMeshesData[(i * 5) + 1];
  19098. var verticesCount = subMeshesData[(i * 5) + 2];
  19099. var indexStart = subMeshesData[(i * 5) + 3];
  19100. var indexCount = subMeshesData[(i * 5) + 4];
  19101. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  19102. }
  19103. }
  19104. }
  19105. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  19106. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  19107. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  19108. if (parsedGeometry.uvs) {
  19109. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  19110. }
  19111. if (parsedGeometry.uvs2) {
  19112. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  19113. }
  19114. if (parsedGeometry.colors) {
  19115. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, checkColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  19116. }
  19117. if (parsedGeometry.matricesIndices) {
  19118. if (!parsedGeometry.matricesIndices._isExpanded) {
  19119. var floatIndices = [];
  19120. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  19121. var matricesIndex = parsedGeometry.matricesIndices[i];
  19122. floatIndices.push(matricesIndex & 0x000000FF);
  19123. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  19124. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  19125. floatIndices.push(matricesIndex >> 24);
  19126. }
  19127. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  19128. }
  19129. else {
  19130. delete parsedGeometry.matricesIndices._isExpanded;
  19131. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  19132. }
  19133. }
  19134. if (parsedGeometry.matricesWeights) {
  19135. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  19136. }
  19137. mesh.setIndices(parsedGeometry.indices);
  19138. // SubMeshes
  19139. if (parsedGeometry.subMeshes) {
  19140. mesh.subMeshes = [];
  19141. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  19142. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  19143. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  19144. }
  19145. }
  19146. }
  19147. // Flat shading
  19148. if (mesh._shouldGenerateFlatShading) {
  19149. mesh.convertToFlatShadedMesh();
  19150. delete mesh._shouldGenerateFlatShading;
  19151. }
  19152. // Update
  19153. mesh.computeWorldMatrix(true);
  19154. // Octree
  19155. if (scene._selectionOctree) {
  19156. scene._selectionOctree.addMesh(mesh);
  19157. }
  19158. };
  19159. BABYLON.SceneLoader.RegisterPlugin({
  19160. extensions: ".babylon",
  19161. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  19162. var parsedData = JSON.parse(data);
  19163. var loadedSkeletonsIds = [];
  19164. var loadedMaterialsIds = [];
  19165. var hierarchyIds = [];
  19166. for (var index = 0; index < parsedData.meshes.length; index++) {
  19167. var parsedMesh = parsedData.meshes[index];
  19168. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  19169. if (meshesNames instanceof Array) {
  19170. // Remove found mesh name from list.
  19171. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  19172. }
  19173. // Material ?
  19174. if (parsedMesh.materialId) {
  19175. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  19176. if (!materialFound) {
  19177. for (var multimatIndex = 0; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
  19178. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  19179. if (parsedMultiMaterial.id == parsedMesh.materialId) {
  19180. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  19181. var subMatId = parsedMultiMaterial.materials[matIndex];
  19182. loadedMaterialsIds.push(subMatId);
  19183. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  19184. }
  19185. loadedMaterialsIds.push(parsedMultiMaterial.id);
  19186. parseMultiMaterial(parsedMultiMaterial, scene);
  19187. materialFound = true;
  19188. break;
  19189. }
  19190. }
  19191. }
  19192. if (!materialFound) {
  19193. loadedMaterialsIds.push(parsedMesh.materialId);
  19194. parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  19195. }
  19196. }
  19197. // Skeleton ?
  19198. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  19199. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  19200. if (!skeletonAlreadyLoaded) {
  19201. for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
  19202. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  19203. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  19204. skeletons.push(parseSkeleton(parsedSkeleton, scene));
  19205. loadedSkeletonsIds.push(parsedSkeleton.id);
  19206. }
  19207. }
  19208. }
  19209. }
  19210. var mesh = parseMesh(parsedMesh, scene, rootUrl);
  19211. meshes.push(mesh);
  19212. }
  19213. }
  19214. for (index = 0; index < scene.meshes.length; index++) {
  19215. var currentMesh = scene.meshes[index];
  19216. if (currentMesh._waitingParentId) {
  19217. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  19218. currentMesh._waitingParentId = undefined;
  19219. }
  19220. }
  19221. // Particles
  19222. if (parsedData.particleSystems) {
  19223. for (index = 0; index < parsedData.particleSystems.length; index++) {
  19224. var parsedParticleSystem = parsedData.particleSystems[index];
  19225. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  19226. particleSystems.push(parseParticleSystem(parsedParticleSystem, scene, rootUrl));
  19227. }
  19228. }
  19229. }
  19230. return true;
  19231. },
  19232. load: function (scene, data, rootUrl) {
  19233. var parsedData = JSON.parse(data);
  19234. // Scene
  19235. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  19236. scene.autoClear = parsedData.autoClear;
  19237. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  19238. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  19239. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  19240. // Fog
  19241. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  19242. scene.fogMode = parsedData.fogMode;
  19243. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  19244. scene.fogStart = parsedData.fogStart;
  19245. scene.fogEnd = parsedData.fogEnd;
  19246. scene.fogDensity = parsedData.fogDensity;
  19247. }
  19248. for (var index = 0; index < parsedData.lights.length; index++) {
  19249. var parsedLight = parsedData.lights[index];
  19250. parseLight(parsedLight, scene);
  19251. }
  19252. // Materials
  19253. if (parsedData.materials) {
  19254. for (index = 0; index < parsedData.materials.length; index++) {
  19255. var parsedMaterial = parsedData.materials[index];
  19256. parseMaterial(parsedMaterial, scene, rootUrl);
  19257. }
  19258. }
  19259. if (parsedData.multiMaterials) {
  19260. for (index = 0; index < parsedData.multiMaterials.length; index++) {
  19261. var parsedMultiMaterial = parsedData.multiMaterials[index];
  19262. parseMultiMaterial(parsedMultiMaterial, scene);
  19263. }
  19264. }
  19265. // Skeletons
  19266. if (parsedData.skeletons) {
  19267. for (index = 0; index < parsedData.skeletons.length; index++) {
  19268. var parsedSkeleton = parsedData.skeletons[index];
  19269. parseSkeleton(parsedSkeleton, scene);
  19270. }
  19271. }
  19272. // Geometries
  19273. var geometries = parsedData.geometries;
  19274. if (geometries) {
  19275. // Boxes
  19276. var boxes = geometries.boxes;
  19277. if (boxes) {
  19278. for (index = 0; index < boxes.length; index++) {
  19279. var parsedBox = boxes[index];
  19280. parseBox(parsedBox, scene);
  19281. }
  19282. }
  19283. // Spheres
  19284. var spheres = geometries.spheres;
  19285. if (spheres) {
  19286. for (index = 0; index < spheres.length; index++) {
  19287. var parsedSphere = spheres[index];
  19288. parseSphere(parsedSphere, scene);
  19289. }
  19290. }
  19291. // Cylinders
  19292. var cylinders = geometries.cylinders;
  19293. if (cylinders) {
  19294. for (index = 0; index < cylinders.length; index++) {
  19295. var parsedCylinder = cylinders[index];
  19296. parseCylinder(parsedCylinder, scene);
  19297. }
  19298. }
  19299. // Toruses
  19300. var toruses = geometries.toruses;
  19301. if (toruses) {
  19302. for (index = 0; index < toruses.length; index++) {
  19303. var parsedTorus = toruses[index];
  19304. parseTorus(parsedTorus, scene);
  19305. }
  19306. }
  19307. // Grounds
  19308. var grounds = geometries.grounds;
  19309. if (grounds) {
  19310. for (index = 0; index < grounds.length; index++) {
  19311. var parsedGround = grounds[index];
  19312. parseGround(parsedGround, scene);
  19313. }
  19314. }
  19315. // Planes
  19316. var planes = geometries.planes;
  19317. if (planes) {
  19318. for (index = 0; index < planes.length; index++) {
  19319. var parsedPlane = planes[index];
  19320. parsePlane(parsedPlane, scene);
  19321. }
  19322. }
  19323. // TorusKnots
  19324. var torusKnots = geometries.torusKnots;
  19325. if (torusKnots) {
  19326. for (index = 0; index < torusKnots.length; index++) {
  19327. var parsedTorusKnot = torusKnots[index];
  19328. parseTorusKnot(parsedTorusKnot, scene);
  19329. }
  19330. }
  19331. // VertexData
  19332. var vertexData = geometries.vertexData;
  19333. if (vertexData) {
  19334. for (index = 0; index < vertexData.length; index++) {
  19335. var parsedVertexData = vertexData[index];
  19336. parseVertexData(parsedVertexData, scene, rootUrl);
  19337. }
  19338. }
  19339. }
  19340. for (index = 0; index < parsedData.meshes.length; index++) {
  19341. var parsedMesh = parsedData.meshes[index];
  19342. parseMesh(parsedMesh, scene, rootUrl);
  19343. }
  19344. for (index = 0; index < parsedData.cameras.length; index++) {
  19345. var parsedCamera = parsedData.cameras[index];
  19346. parseCamera(parsedCamera, scene);
  19347. }
  19348. if (parsedData.activeCameraID) {
  19349. scene.setActiveCameraByID(parsedData.activeCameraID);
  19350. }
  19351. for (index = 0; index < scene.cameras.length; index++) {
  19352. var camera = scene.cameras[index];
  19353. if (camera._waitingParentId) {
  19354. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  19355. camera._waitingParentId = undefined;
  19356. }
  19357. }
  19358. for (index = 0; index < scene.lights.length; index++) {
  19359. var light = scene.lights[index];
  19360. if (light._waitingParentId) {
  19361. light.parent = scene.getLastEntryByID(light._waitingParentId);
  19362. light._waitingParentId = undefined;
  19363. }
  19364. }
  19365. // Sounds
  19366. if (parsedData.sounds) {
  19367. for (index = 0; index < parsedData.sounds.length; index++) {
  19368. var parsedSound = parsedData.sounds[index];
  19369. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  19370. parseSound(parsedSound, scene, rootUrl);
  19371. }
  19372. else {
  19373. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  19374. }
  19375. }
  19376. }
  19377. for (index = 0; index < scene.meshes.length; index++) {
  19378. var mesh = scene.meshes[index];
  19379. if (mesh._waitingParentId) {
  19380. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  19381. mesh._waitingParentId = undefined;
  19382. }
  19383. if (mesh._waitingActions) {
  19384. parseActions(mesh._waitingActions, mesh, scene);
  19385. mesh._waitingActions = undefined;
  19386. }
  19387. }
  19388. // Particles Systems
  19389. if (parsedData.particleSystems) {
  19390. for (index = 0; index < parsedData.particleSystems.length; index++) {
  19391. var parsedParticleSystem = parsedData.particleSystems[index];
  19392. parseParticleSystem(parsedParticleSystem, scene, rootUrl);
  19393. }
  19394. }
  19395. // Lens flares
  19396. if (parsedData.lensFlareSystems) {
  19397. for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
  19398. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  19399. parseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
  19400. }
  19401. }
  19402. // Shadows
  19403. if (parsedData.shadowGenerators) {
  19404. for (index = 0; index < parsedData.shadowGenerators.length; index++) {
  19405. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  19406. parseShadowGenerator(parsedShadowGenerator, scene);
  19407. }
  19408. }
  19409. // Actions (scene)
  19410. if (parsedData.actions) {
  19411. parseActions(parsedData.actions, null, scene);
  19412. }
  19413. // Finish
  19414. return true;
  19415. }
  19416. });
  19417. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  19418. })(BABYLON || (BABYLON = {}));
  19419. //# sourceMappingURL=babylon.babylonFileLoader.js.mapvar BABYLON;
  19420. (function (BABYLON) {
  19421. // Unique ID when we import meshes from Babylon to CSG
  19422. var currentCSGMeshId = 0;
  19423. // # class Vertex
  19424. // Represents a vertex of a polygon. Use your own vertex class instead of this
  19425. // one to provide additional features like texture coordinates and vertex
  19426. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  19427. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  19428. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  19429. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  19430. // is not used anywhere else.
  19431. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  19432. var Vertex = (function () {
  19433. function Vertex(pos, normal, uv) {
  19434. this.pos = pos;
  19435. this.normal = normal;
  19436. this.uv = uv;
  19437. }
  19438. Vertex.prototype.clone = function () {
  19439. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  19440. };
  19441. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  19442. // orientation of a polygon is flipped.
  19443. Vertex.prototype.flip = function () {
  19444. this.normal = this.normal.scale(-1);
  19445. };
  19446. // Create a new vertex between this vertex and `other` by linearly
  19447. // interpolating all properties using a parameter of `t`. Subclasses should
  19448. // override this to interpolate additional properties.
  19449. Vertex.prototype.interpolate = function (other, t) {
  19450. return new Vertex(BABYLON.Vector3.Lerp(this.pos, other.pos, t), BABYLON.Vector3.Lerp(this.normal, other.normal, t), BABYLON.Vector2.Lerp(this.uv, other.uv, t));
  19451. };
  19452. return Vertex;
  19453. })();
  19454. // # class Plane
  19455. // Represents a plane in 3D space.
  19456. var Plane = (function () {
  19457. function Plane(normal, w) {
  19458. this.normal = normal;
  19459. this.w = w;
  19460. }
  19461. Plane.FromPoints = function (a, b, c) {
  19462. var v0 = c.subtract(a);
  19463. var v1 = b.subtract(a);
  19464. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  19465. return null;
  19466. }
  19467. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  19468. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  19469. };
  19470. Plane.prototype.clone = function () {
  19471. return new Plane(this.normal.clone(), this.w);
  19472. };
  19473. Plane.prototype.flip = function () {
  19474. this.normal.scaleInPlace(-1);
  19475. this.w = -this.w;
  19476. };
  19477. // Split `polygon` by this plane if needed, then put the polygon or polygon
  19478. // fragments in the appropriate lists. Coplanar polygons go into either
  19479. // `coplanarFront` or `coplanarBack` depending on their orientation with
  19480. // respect to this plane. Polygons in front or in back of this plane go into
  19481. // either `front` or `back`.
  19482. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  19483. var COPLANAR = 0;
  19484. var FRONT = 1;
  19485. var BACK = 2;
  19486. var SPANNING = 3;
  19487. // Classify each point as well as the entire polygon into one of the above
  19488. // four classes.
  19489. var polygonType = 0;
  19490. var types = [];
  19491. for (var i = 0; i < polygon.vertices.length; i++) {
  19492. var t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  19493. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  19494. polygonType |= type;
  19495. types.push(type);
  19496. }
  19497. switch (polygonType) {
  19498. case COPLANAR:
  19499. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  19500. break;
  19501. case FRONT:
  19502. front.push(polygon);
  19503. break;
  19504. case BACK:
  19505. back.push(polygon);
  19506. break;
  19507. case SPANNING:
  19508. var f = [], b = [];
  19509. for (i = 0; i < polygon.vertices.length; i++) {
  19510. var j = (i + 1) % polygon.vertices.length;
  19511. var ti = types[i], tj = types[j];
  19512. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  19513. if (ti != BACK)
  19514. f.push(vi);
  19515. if (ti != FRONT)
  19516. b.push(ti != BACK ? vi.clone() : vi);
  19517. if ((ti | tj) == SPANNING) {
  19518. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  19519. var v = vi.interpolate(vj, t);
  19520. f.push(v);
  19521. b.push(v.clone());
  19522. }
  19523. }
  19524. if (f.length >= 3) {
  19525. var poly = new Polygon(f, polygon.shared);
  19526. if (poly.plane)
  19527. front.push(poly);
  19528. }
  19529. if (b.length >= 3) {
  19530. poly = new Polygon(b, polygon.shared);
  19531. if (poly.plane)
  19532. back.push(poly);
  19533. }
  19534. break;
  19535. }
  19536. };
  19537. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  19538. // point is on the plane.
  19539. Plane.EPSILON = 1e-5;
  19540. return Plane;
  19541. })();
  19542. // # class Polygon
  19543. // Represents a convex polygon. The vertices used to initialize a polygon must
  19544. // be coplanar and form a convex loop.
  19545. //
  19546. // Each convex polygon has a `shared` property, which is shared between all
  19547. // polygons that are clones of each other or were split from the same polygon.
  19548. // This can be used to define per-polygon properties (such as surface color).
  19549. var Polygon = (function () {
  19550. function Polygon(vertices, shared) {
  19551. this.vertices = vertices;
  19552. this.shared = shared;
  19553. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  19554. }
  19555. Polygon.prototype.clone = function () {
  19556. var vertices = this.vertices.map(function (v) { return v.clone(); });
  19557. return new Polygon(vertices, this.shared);
  19558. };
  19559. Polygon.prototype.flip = function () {
  19560. this.vertices.reverse().map(function (v) {
  19561. v.flip();
  19562. });
  19563. this.plane.flip();
  19564. };
  19565. return Polygon;
  19566. })();
  19567. // # class Node
  19568. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  19569. // by picking a polygon to split along. That polygon (and all other coplanar
  19570. // polygons) are added directly to that node and the other polygons are added to
  19571. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  19572. // no distinction between internal and leaf nodes.
  19573. var Node = (function () {
  19574. function Node(polygons) {
  19575. this.plane = null;
  19576. this.front = null;
  19577. this.back = null;
  19578. this.polygons = [];
  19579. if (polygons) {
  19580. this.build(polygons);
  19581. }
  19582. }
  19583. Node.prototype.clone = function () {
  19584. var node = new Node();
  19585. node.plane = this.plane && this.plane.clone();
  19586. node.front = this.front && this.front.clone();
  19587. node.back = this.back && this.back.clone();
  19588. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  19589. return node;
  19590. };
  19591. // Convert solid space to empty space and empty space to solid space.
  19592. Node.prototype.invert = function () {
  19593. for (var i = 0; i < this.polygons.length; i++) {
  19594. this.polygons[i].flip();
  19595. }
  19596. if (this.plane) {
  19597. this.plane.flip();
  19598. }
  19599. if (this.front) {
  19600. this.front.invert();
  19601. }
  19602. if (this.back) {
  19603. this.back.invert();
  19604. }
  19605. var temp = this.front;
  19606. this.front = this.back;
  19607. this.back = temp;
  19608. };
  19609. // Recursively remove all polygons in `polygons` that are inside this BSP
  19610. // tree.
  19611. Node.prototype.clipPolygons = function (polygons) {
  19612. if (!this.plane)
  19613. return polygons.slice();
  19614. var front = [], back = [];
  19615. for (var i = 0; i < polygons.length; i++) {
  19616. this.plane.splitPolygon(polygons[i], front, back, front, back);
  19617. }
  19618. if (this.front) {
  19619. front = this.front.clipPolygons(front);
  19620. }
  19621. if (this.back) {
  19622. back = this.back.clipPolygons(back);
  19623. }
  19624. else {
  19625. back = [];
  19626. }
  19627. return front.concat(back);
  19628. };
  19629. // Remove all polygons in this BSP tree that are inside the other BSP tree
  19630. // `bsp`.
  19631. Node.prototype.clipTo = function (bsp) {
  19632. this.polygons = bsp.clipPolygons(this.polygons);
  19633. if (this.front)
  19634. this.front.clipTo(bsp);
  19635. if (this.back)
  19636. this.back.clipTo(bsp);
  19637. };
  19638. // Return a list of all polygons in this BSP tree.
  19639. Node.prototype.allPolygons = function () {
  19640. var polygons = this.polygons.slice();
  19641. if (this.front)
  19642. polygons = polygons.concat(this.front.allPolygons());
  19643. if (this.back)
  19644. polygons = polygons.concat(this.back.allPolygons());
  19645. return polygons;
  19646. };
  19647. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  19648. // new polygons are filtered down to the bottom of the tree and become new
  19649. // nodes there. Each set of polygons is partitioned using the first polygon
  19650. // (no heuristic is used to pick a good split).
  19651. Node.prototype.build = function (polygons) {
  19652. if (!polygons.length)
  19653. return;
  19654. if (!this.plane)
  19655. this.plane = polygons[0].plane.clone();
  19656. var front = [], back = [];
  19657. for (var i = 0; i < polygons.length; i++) {
  19658. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  19659. }
  19660. if (front.length) {
  19661. if (!this.front)
  19662. this.front = new Node();
  19663. this.front.build(front);
  19664. }
  19665. if (back.length) {
  19666. if (!this.back)
  19667. this.back = new Node();
  19668. this.back.build(back);
  19669. }
  19670. };
  19671. return Node;
  19672. })();
  19673. var CSG = (function () {
  19674. function CSG() {
  19675. this.polygons = new Array();
  19676. }
  19677. // Convert BABYLON.Mesh to BABYLON.CSG
  19678. CSG.FromMesh = function (mesh) {
  19679. var vertex, normal, uv, position, polygon, polygons = [], vertices;
  19680. if (mesh instanceof BABYLON.Mesh) {
  19681. mesh.computeWorldMatrix(true);
  19682. var matrix = mesh.getWorldMatrix();
  19683. var meshPosition = mesh.position.clone();
  19684. var meshRotation = mesh.rotation.clone();
  19685. var meshScaling = mesh.scaling.clone();
  19686. }
  19687. else {
  19688. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  19689. }
  19690. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  19691. var subMeshes = mesh.subMeshes;
  19692. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  19693. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  19694. vertices = [];
  19695. for (var j = 0; j < 3; j++) {
  19696. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  19697. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  19698. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  19699. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  19700. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  19701. vertex = new Vertex(position, normal, uv);
  19702. vertices.push(vertex);
  19703. }
  19704. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  19705. // To handle the case of degenerated triangle
  19706. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  19707. if (polygon.plane)
  19708. polygons.push(polygon);
  19709. }
  19710. }
  19711. var csg = CSG.FromPolygons(polygons);
  19712. csg.matrix = matrix;
  19713. csg.position = meshPosition;
  19714. csg.rotation = meshRotation;
  19715. csg.scaling = meshScaling;
  19716. currentCSGMeshId++;
  19717. return csg;
  19718. };
  19719. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  19720. CSG.FromPolygons = function (polygons) {
  19721. var csg = new BABYLON.CSG();
  19722. csg.polygons = polygons;
  19723. return csg;
  19724. };
  19725. CSG.prototype.clone = function () {
  19726. var csg = new BABYLON.CSG();
  19727. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  19728. csg.copyTransformAttributes(this);
  19729. return csg;
  19730. };
  19731. CSG.prototype.toPolygons = function () {
  19732. return this.polygons;
  19733. };
  19734. CSG.prototype.union = function (csg) {
  19735. var a = new Node(this.clone().polygons);
  19736. var b = new Node(csg.clone().polygons);
  19737. a.clipTo(b);
  19738. b.clipTo(a);
  19739. b.invert();
  19740. b.clipTo(a);
  19741. b.invert();
  19742. a.build(b.allPolygons());
  19743. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  19744. };
  19745. CSG.prototype.unionInPlace = function (csg) {
  19746. var a = new Node(this.polygons);
  19747. var b = new Node(csg.polygons);
  19748. a.clipTo(b);
  19749. b.clipTo(a);
  19750. b.invert();
  19751. b.clipTo(a);
  19752. b.invert();
  19753. a.build(b.allPolygons());
  19754. this.polygons = a.allPolygons();
  19755. };
  19756. CSG.prototype.subtract = function (csg) {
  19757. var a = new Node(this.clone().polygons);
  19758. var b = new Node(csg.clone().polygons);
  19759. a.invert();
  19760. a.clipTo(b);
  19761. b.clipTo(a);
  19762. b.invert();
  19763. b.clipTo(a);
  19764. b.invert();
  19765. a.build(b.allPolygons());
  19766. a.invert();
  19767. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  19768. };
  19769. CSG.prototype.subtractInPlace = function (csg) {
  19770. var a = new Node(this.polygons);
  19771. var b = new Node(csg.polygons);
  19772. a.invert();
  19773. a.clipTo(b);
  19774. b.clipTo(a);
  19775. b.invert();
  19776. b.clipTo(a);
  19777. b.invert();
  19778. a.build(b.allPolygons());
  19779. a.invert();
  19780. this.polygons = a.allPolygons();
  19781. };
  19782. CSG.prototype.intersect = function (csg) {
  19783. var a = new Node(this.clone().polygons);
  19784. var b = new Node(csg.clone().polygons);
  19785. a.invert();
  19786. b.clipTo(a);
  19787. b.invert();
  19788. a.clipTo(b);
  19789. b.clipTo(a);
  19790. a.build(b.allPolygons());
  19791. a.invert();
  19792. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  19793. };
  19794. CSG.prototype.intersectInPlace = function (csg) {
  19795. var a = new Node(this.polygons);
  19796. var b = new Node(csg.polygons);
  19797. a.invert();
  19798. b.clipTo(a);
  19799. b.invert();
  19800. a.clipTo(b);
  19801. b.clipTo(a);
  19802. a.build(b.allPolygons());
  19803. a.invert();
  19804. this.polygons = a.allPolygons();
  19805. };
  19806. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  19807. // not modified.
  19808. CSG.prototype.inverse = function () {
  19809. var csg = this.clone();
  19810. csg.inverseInPlace();
  19811. return csg;
  19812. };
  19813. CSG.prototype.inverseInPlace = function () {
  19814. this.polygons.map(function (p) {
  19815. p.flip();
  19816. });
  19817. };
  19818. // This is used to keep meshes transformations so they can be restored
  19819. // when we build back a Babylon Mesh
  19820. // NB : All CSG operations are performed in world coordinates
  19821. CSG.prototype.copyTransformAttributes = function (csg) {
  19822. this.matrix = csg.matrix;
  19823. this.position = csg.position;
  19824. this.rotation = csg.rotation;
  19825. this.scaling = csg.scaling;
  19826. return this;
  19827. };
  19828. // Build Raw mesh from CSG
  19829. // Coordinates here are in world space
  19830. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  19831. var matrix = this.matrix.clone();
  19832. matrix.invert();
  19833. var mesh = new BABYLON.Mesh(name, scene), vertices = [], indices = [], normals = [], uvs = [], vertex = BABYLON.Vector3.Zero(), normal = BABYLON.Vector3.Zero(), uv = BABYLON.Vector2.Zero(), polygons = this.polygons, polygonIndices = [0, 0, 0], polygon, vertice_dict = {}, vertex_idx, currentIndex = 0, subMesh_dict = {}, subMesh_obj;
  19834. if (keepSubMeshes) {
  19835. // Sort Polygons, since subMeshes are indices range
  19836. polygons.sort(function (a, b) {
  19837. if (a.shared.meshId === b.shared.meshId) {
  19838. return a.shared.subMeshId - b.shared.subMeshId;
  19839. }
  19840. else {
  19841. return a.shared.meshId - b.shared.meshId;
  19842. }
  19843. });
  19844. }
  19845. for (var i = 0, il = polygons.length; i < il; i++) {
  19846. polygon = polygons[i];
  19847. // Building SubMeshes
  19848. if (!subMesh_dict[polygon.shared.meshId]) {
  19849. subMesh_dict[polygon.shared.meshId] = {};
  19850. }
  19851. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  19852. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  19853. indexStart: +Infinity,
  19854. indexEnd: -Infinity,
  19855. materialIndex: polygon.shared.materialIndex
  19856. };
  19857. }
  19858. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  19859. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  19860. polygonIndices[0] = 0;
  19861. polygonIndices[1] = j - 1;
  19862. polygonIndices[2] = j;
  19863. for (var k = 0; k < 3; k++) {
  19864. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  19865. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  19866. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  19867. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  19868. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  19869. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  19870. // Check if 2 points can be merged
  19871. if (!(typeof vertex_idx !== 'undefined' && normals[vertex_idx * 3] === localNormal.x && normals[vertex_idx * 3 + 1] === localNormal.y && normals[vertex_idx * 3 + 2] === localNormal.z && uvs[vertex_idx * 2] === uv.x && uvs[vertex_idx * 2 + 1] === uv.y)) {
  19872. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  19873. uvs.push(uv.x, uv.y);
  19874. normals.push(normal.x, normal.y, normal.z);
  19875. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  19876. }
  19877. indices.push(vertex_idx);
  19878. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  19879. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  19880. currentIndex++;
  19881. }
  19882. }
  19883. }
  19884. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  19885. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  19886. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  19887. mesh.setIndices(indices);
  19888. if (keepSubMeshes) {
  19889. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  19890. var materialIndexOffset = 0, materialMaxIndex;
  19891. mesh.subMeshes.length = 0;
  19892. for (var m in subMesh_dict) {
  19893. materialMaxIndex = -1;
  19894. for (var sm in subMesh_dict[m]) {
  19895. subMesh_obj = subMesh_dict[m][sm];
  19896. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  19897. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  19898. }
  19899. materialIndexOffset += ++materialMaxIndex;
  19900. }
  19901. }
  19902. return mesh;
  19903. };
  19904. // Build Mesh from CSG taking material and transforms into account
  19905. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  19906. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  19907. mesh.material = material;
  19908. mesh.position.copyFrom(this.position);
  19909. mesh.rotation.copyFrom(this.rotation);
  19910. mesh.scaling.copyFrom(this.scaling);
  19911. mesh.computeWorldMatrix(true);
  19912. return mesh;
  19913. };
  19914. return CSG;
  19915. })();
  19916. BABYLON.CSG = CSG;
  19917. })(BABYLON || (BABYLON = {}));
  19918. //# sourceMappingURL=babylon.csg.js.map
  19919. var BABYLON;
  19920. (function (BABYLON) {
  19921. var OculusDistortionCorrectionPostProcess = (function (_super) {
  19922. __extends(OculusDistortionCorrectionPostProcess, _super);
  19923. //ANY
  19924. function OculusDistortionCorrectionPostProcess(name, camera, isRightEye, cameraSettings) {
  19925. var _this = this;
  19926. _super.call(this, name, "oculusDistortionCorrection", [
  19927. 'LensCenter',
  19928. 'Scale',
  19929. 'ScaleIn',
  19930. 'HmdWarpParam'
  19931. ], null, cameraSettings.PostProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  19932. this._isRightEye = isRightEye;
  19933. this._distortionFactors = cameraSettings.DistortionK;
  19934. this._postProcessScaleFactor = cameraSettings.PostProcessScaleFactor;
  19935. this._lensCenterOffset = cameraSettings.LensCenterOffset;
  19936. this.onSizeChanged = function () {
  19937. _this.aspectRatio = _this.width * .5 / _this.height;
  19938. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  19939. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  19940. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  19941. };
  19942. this.onApply = function (effect) {
  19943. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  19944. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  19945. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  19946. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  19947. };
  19948. }
  19949. return OculusDistortionCorrectionPostProcess;
  19950. })(BABYLON.PostProcess);
  19951. BABYLON.OculusDistortionCorrectionPostProcess = OculusDistortionCorrectionPostProcess;
  19952. })(BABYLON || (BABYLON = {}));
  19953. //# sourceMappingURL=babylon.oculusDistortionCorrectionPostProcess.js.map// Mainly based on these 2 articles :
  19954. // Creating an universal virtual touch joystick working for all Touch models thanks to Hand.JS : http://blogs.msdn.com/b/davrous/archive/2013/02/22/creating-an-universal-virtual-touch-joystick-working-for-all-touch-models-thanks-to-hand-js.aspx
  19955. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  19956. var BABYLON;
  19957. (function (BABYLON) {
  19958. (function (JoystickAxis) {
  19959. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  19960. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  19961. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  19962. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  19963. var JoystickAxis = BABYLON.JoystickAxis;
  19964. var VirtualJoystick = (function () {
  19965. function VirtualJoystick(leftJoystick) {
  19966. var _this = this;
  19967. if (leftJoystick) {
  19968. this._leftJoystick = true;
  19969. }
  19970. else {
  19971. this._leftJoystick = false;
  19972. }
  19973. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  19974. VirtualJoystick._globalJoystickIndex++;
  19975. // By default left & right arrow keys are moving the X
  19976. // and up & down keys are moving the Y
  19977. this._axisTargetedByLeftAndRight = 0 /* X */;
  19978. this._axisTargetedByUpAndDown = 1 /* Y */;
  19979. this.reverseLeftRight = false;
  19980. this.reverseUpDown = false;
  19981. // collections of pointers
  19982. this._touches = new BABYLON.VirtualJoystick.Collection();
  19983. this.deltaPosition = BABYLON.Vector3.Zero();
  19984. this._joystickSensibility = 25;
  19985. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  19986. this._rotationSpeed = 25;
  19987. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  19988. this._rotateOnAxisRelativeToMesh = false;
  19989. // injecting a canvas element on top of the canvas 3D game
  19990. if (!VirtualJoystick.vjCanvas) {
  19991. window.addEventListener("resize", function () {
  19992. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  19993. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  19994. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  19995. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  19996. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  19997. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  19998. }, false);
  19999. VirtualJoystick.vjCanvas = document.createElement("canvas");
  20000. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  20001. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  20002. VirtualJoystick.vjCanvas.width = window.innerWidth;
  20003. VirtualJoystick.vjCanvas.height = window.innerHeight;
  20004. VirtualJoystick.vjCanvas.style.width = "100%";
  20005. VirtualJoystick.vjCanvas.style.height = "100%";
  20006. VirtualJoystick.vjCanvas.style.position = "absolute";
  20007. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  20008. VirtualJoystick.vjCanvas.style.top = "0px";
  20009. VirtualJoystick.vjCanvas.style.left = "0px";
  20010. VirtualJoystick.vjCanvas.style.zIndex = "5";
  20011. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  20012. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  20013. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  20014. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  20015. document.body.appendChild(VirtualJoystick.vjCanvas);
  20016. }
  20017. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  20018. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  20019. this.pressed = false;
  20020. // default joystick color
  20021. this._joystickColor = "cyan";
  20022. this._joystickPointerID = -1;
  20023. // current joystick position
  20024. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  20025. // origin joystick position
  20026. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  20027. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  20028. VirtualJoystick.vjCanvas.addEventListener('pointerdown', function (evt) {
  20029. _this._onPointerDown(evt);
  20030. }, false);
  20031. VirtualJoystick.vjCanvas.addEventListener('pointermove', function (evt) {
  20032. _this._onPointerMove(evt);
  20033. }, false);
  20034. VirtualJoystick.vjCanvas.addEventListener('pointerup', function (evt) {
  20035. _this._onPointerUp(evt);
  20036. }, false);
  20037. VirtualJoystick.vjCanvas.addEventListener('pointerout', function (evt) {
  20038. _this._onPointerUp(evt);
  20039. }, false);
  20040. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  20041. evt.preventDefault(); // Disables system menu
  20042. }, false);
  20043. requestAnimationFrame(function () {
  20044. _this._drawVirtualJoystick();
  20045. });
  20046. }
  20047. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  20048. this._joystickSensibility = newJoystickSensibility;
  20049. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  20050. };
  20051. VirtualJoystick.prototype._onPointerDown = function (e) {
  20052. var positionOnScreenCondition;
  20053. e.preventDefault();
  20054. if (this._leftJoystick === true) {
  20055. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  20056. }
  20057. else {
  20058. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  20059. }
  20060. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  20061. // First contact will be dedicated to the virtual joystick
  20062. this._joystickPointerID = e.pointerId;
  20063. this._joystickPointerStartPos.x = e.clientX;
  20064. this._joystickPointerStartPos.y = e.clientY;
  20065. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  20066. this._deltaJoystickVector.x = 0;
  20067. this._deltaJoystickVector.y = 0;
  20068. this.pressed = true;
  20069. this._touches.add(e.pointerId.toString(), e);
  20070. }
  20071. else {
  20072. // You can only trigger the action buttons with a joystick declared
  20073. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  20074. this._action();
  20075. this._touches.add(e.pointerId.toString(), e);
  20076. }
  20077. }
  20078. };
  20079. VirtualJoystick.prototype._onPointerMove = function (e) {
  20080. // If the current pointer is the one associated to the joystick (first touch contact)
  20081. if (this._joystickPointerID == e.pointerId) {
  20082. this._joystickPointerPos.x = e.clientX;
  20083. this._joystickPointerPos.y = e.clientY;
  20084. this._deltaJoystickVector = this._joystickPointerPos.clone();
  20085. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  20086. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  20087. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  20088. switch (this._axisTargetedByLeftAndRight) {
  20089. case 0 /* X */:
  20090. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  20091. break;
  20092. case 1 /* Y */:
  20093. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  20094. break;
  20095. case 2 /* Z */:
  20096. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  20097. break;
  20098. }
  20099. var directionUpDown = this.reverseUpDown ? 1 : -1;
  20100. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  20101. switch (this._axisTargetedByUpAndDown) {
  20102. case 0 /* X */:
  20103. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  20104. break;
  20105. case 1 /* Y */:
  20106. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  20107. break;
  20108. case 2 /* Z */:
  20109. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  20110. break;
  20111. }
  20112. }
  20113. else {
  20114. if (this._touches.item(e.pointerId.toString())) {
  20115. this._touches.item(e.pointerId.toString()).x = e.clientX;
  20116. this._touches.item(e.pointerId.toString()).y = e.clientY;
  20117. }
  20118. }
  20119. };
  20120. VirtualJoystick.prototype._onPointerUp = function (e) {
  20121. this._clearCanvas();
  20122. if (this._joystickPointerID == e.pointerId) {
  20123. this._joystickPointerID = -1;
  20124. this.pressed = false;
  20125. }
  20126. this._deltaJoystickVector.x = 0;
  20127. this._deltaJoystickVector.y = 0;
  20128. this._touches.remove(e.pointerId.toString());
  20129. };
  20130. /**
  20131. * Change the color of the virtual joystick
  20132. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  20133. */
  20134. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  20135. this._joystickColor = newColor;
  20136. };
  20137. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  20138. this._action = action;
  20139. };
  20140. // Define which axis you'd like to control for left & right
  20141. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  20142. switch (axis) {
  20143. case 0 /* X */:
  20144. case 1 /* Y */:
  20145. case 2 /* Z */:
  20146. this._axisTargetedByLeftAndRight = axis;
  20147. break;
  20148. default:
  20149. this._axisTargetedByLeftAndRight = 0 /* X */;
  20150. break;
  20151. }
  20152. };
  20153. // Define which axis you'd like to control for up & down
  20154. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  20155. switch (axis) {
  20156. case 0 /* X */:
  20157. case 1 /* Y */:
  20158. case 2 /* Z */:
  20159. this._axisTargetedByUpAndDown = axis;
  20160. break;
  20161. default:
  20162. this._axisTargetedByUpAndDown = 1 /* Y */;
  20163. break;
  20164. }
  20165. };
  20166. VirtualJoystick.prototype._clearCanvas = function () {
  20167. if (this._leftJoystick) {
  20168. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  20169. }
  20170. else {
  20171. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  20172. }
  20173. };
  20174. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  20175. var _this = this;
  20176. if (this.pressed) {
  20177. this._clearCanvas();
  20178. this._touches.forEach(function (touch) {
  20179. if (touch.pointerId === _this._joystickPointerID) {
  20180. VirtualJoystick.vjCanvasContext.beginPath();
  20181. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  20182. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  20183. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  20184. VirtualJoystick.vjCanvasContext.stroke();
  20185. VirtualJoystick.vjCanvasContext.beginPath();
  20186. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  20187. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  20188. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  20189. VirtualJoystick.vjCanvasContext.stroke();
  20190. VirtualJoystick.vjCanvasContext.beginPath();
  20191. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  20192. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  20193. VirtualJoystick.vjCanvasContext.stroke();
  20194. }
  20195. else {
  20196. VirtualJoystick.vjCanvasContext.beginPath();
  20197. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  20198. VirtualJoystick.vjCanvasContext.beginPath();
  20199. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  20200. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  20201. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  20202. VirtualJoystick.vjCanvasContext.stroke();
  20203. }
  20204. ;
  20205. });
  20206. }
  20207. requestAnimationFrame(function () {
  20208. _this._drawVirtualJoystick();
  20209. });
  20210. };
  20211. VirtualJoystick.prototype.releaseCanvas = function () {
  20212. if (VirtualJoystick.vjCanvas) {
  20213. document.body.removeChild(VirtualJoystick.vjCanvas);
  20214. VirtualJoystick.vjCanvas = null;
  20215. }
  20216. };
  20217. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  20218. VirtualJoystick._globalJoystickIndex = 0;
  20219. return VirtualJoystick;
  20220. })();
  20221. BABYLON.VirtualJoystick = VirtualJoystick;
  20222. })(BABYLON || (BABYLON = {}));
  20223. var BABYLON;
  20224. (function (BABYLON) {
  20225. var VirtualJoystick;
  20226. (function (VirtualJoystick) {
  20227. var Collection = (function () {
  20228. function Collection() {
  20229. this._count = 0;
  20230. this._collection = new Array();
  20231. }
  20232. Collection.prototype.Count = function () {
  20233. return this._count;
  20234. };
  20235. Collection.prototype.add = function (key, item) {
  20236. if (this._collection[key] != undefined) {
  20237. return undefined;
  20238. }
  20239. this._collection[key] = item;
  20240. return ++this._count;
  20241. };
  20242. Collection.prototype.remove = function (key) {
  20243. if (this._collection[key] == undefined) {
  20244. return undefined;
  20245. }
  20246. delete this._collection[key];
  20247. return --this._count;
  20248. };
  20249. Collection.prototype.item = function (key) {
  20250. return this._collection[key];
  20251. };
  20252. Collection.prototype.forEach = function (block) {
  20253. var key;
  20254. for (key in this._collection) {
  20255. if (this._collection.hasOwnProperty(key)) {
  20256. block(this._collection[key]);
  20257. }
  20258. }
  20259. };
  20260. return Collection;
  20261. })();
  20262. VirtualJoystick.Collection = Collection;
  20263. })(VirtualJoystick = BABYLON.VirtualJoystick || (BABYLON.VirtualJoystick = {}));
  20264. })(BABYLON || (BABYLON = {}));
  20265. //# sourceMappingURL=babylon.virtualJoystick.js.map
  20266. var BABYLON;
  20267. (function (BABYLON) {
  20268. var OculusRiftDevKit2013_Metric = {
  20269. HResolution: 1280,
  20270. VResolution: 800,
  20271. HScreenSize: 0.149759993,
  20272. VScreenSize: 0.0935999975,
  20273. VScreenCenter: 0.0467999987,
  20274. EyeToScreenDistance: 0.0410000011,
  20275. LensSeparationDistance: 0.0635000020,
  20276. InterpupillaryDistance: 0.0640000030,
  20277. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  20278. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  20279. PostProcessScaleFactor: 1.714605507808412,
  20280. LensCenterOffset: 0.151976421
  20281. };
  20282. var _OculusInnerCamera = (function (_super) {
  20283. __extends(_OculusInnerCamera, _super);
  20284. function _OculusInnerCamera(name, position, scene, isLeftEye) {
  20285. _super.call(this, name, position, scene);
  20286. this._workMatrix = new BABYLON.Matrix();
  20287. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  20288. // Constants
  20289. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  20290. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  20291. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  20292. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  20293. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  20294. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  20295. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  20296. // Postprocess
  20297. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  20298. }
  20299. _OculusInnerCamera.prototype.getProjectionMatrix = function () {
  20300. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  20301. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  20302. return this._projectionMatrix;
  20303. };
  20304. _OculusInnerCamera.prototype._getViewMatrix = function () {
  20305. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  20306. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  20307. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  20308. // Computing target and final matrix
  20309. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  20310. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  20311. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  20312. return this._viewMatrix;
  20313. };
  20314. return _OculusInnerCamera;
  20315. })(BABYLON.FreeCamera);
  20316. var OculusCamera = (function (_super) {
  20317. __extends(OculusCamera, _super);
  20318. function OculusCamera(name, position, scene) {
  20319. _super.call(this, name, position, scene);
  20320. this._leftCamera = new _OculusInnerCamera(name + "_left", position.clone(), scene, true);
  20321. this._rightCamera = new _OculusInnerCamera(name + "_right", position.clone(), scene, false);
  20322. this.subCameras.push(this._leftCamera);
  20323. this.subCameras.push(this._rightCamera);
  20324. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  20325. }
  20326. OculusCamera.prototype._update = function () {
  20327. this._leftCamera.position.copyFrom(this.position);
  20328. this._rightCamera.position.copyFrom(this.position);
  20329. this._updateCamera(this._leftCamera);
  20330. this._updateCamera(this._rightCamera);
  20331. _super.prototype._update.call(this);
  20332. };
  20333. OculusCamera.prototype._updateCamera = function (camera) {
  20334. camera.minZ = this.minZ;
  20335. camera.maxZ = this.maxZ;
  20336. camera.rotation.x = this.rotation.x;
  20337. camera.rotation.y = this.rotation.y;
  20338. camera.rotation.z = this.rotation.z;
  20339. };
  20340. // Oculus events
  20341. OculusCamera.prototype._onOrientationEvent = function (evt) {
  20342. var yaw = evt.alpha / 180 * Math.PI;
  20343. var pitch = evt.beta / 180 * Math.PI;
  20344. var roll = evt.gamma / 180 * Math.PI;
  20345. if (!this._offsetOrientation) {
  20346. this._offsetOrientation = {
  20347. yaw: yaw,
  20348. pitch: pitch,
  20349. roll: roll
  20350. };
  20351. return;
  20352. }
  20353. else {
  20354. this.rotation.y += yaw - this._offsetOrientation.yaw;
  20355. this.rotation.x += pitch - this._offsetOrientation.pitch;
  20356. this.rotation.z += this._offsetOrientation.roll - roll;
  20357. this._offsetOrientation.yaw = yaw;
  20358. this._offsetOrientation.pitch = pitch;
  20359. this._offsetOrientation.roll = roll;
  20360. }
  20361. };
  20362. OculusCamera.prototype.attachControl = function (element, noPreventDefault) {
  20363. _super.prototype.attachControl.call(this, element, noPreventDefault);
  20364. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  20365. };
  20366. OculusCamera.prototype.detachControl = function (element) {
  20367. _super.prototype.detachControl.call(this, element);
  20368. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  20369. };
  20370. return OculusCamera;
  20371. })(BABYLON.FreeCamera);
  20372. BABYLON.OculusCamera = OculusCamera;
  20373. })(BABYLON || (BABYLON = {}));
  20374. //# sourceMappingURL=babylon.oculusCamera.js.map
  20375. var BABYLON;
  20376. (function (BABYLON) {
  20377. var OculusRiftDevKit2013_Metric = {
  20378. HResolution: 1280,
  20379. VResolution: 800,
  20380. HScreenSize: 0.149759993,
  20381. VScreenSize: 0.0935999975,
  20382. VScreenCenter: 0.0467999987,
  20383. EyeToScreenDistance: 0.0410000011,
  20384. LensSeparationDistance: 0.0635000020,
  20385. InterpupillaryDistance: 0.0640000030,
  20386. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  20387. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  20388. PostProcessScaleFactor: 1.714605507808412,
  20389. LensCenterOffset: 0.151976421
  20390. };
  20391. var _OculusInnerGamepadCamera = (function (_super) {
  20392. __extends(_OculusInnerGamepadCamera, _super);
  20393. function _OculusInnerGamepadCamera(name, position, scene, isLeftEye) {
  20394. _super.call(this, name, position, scene);
  20395. this._workMatrix = new BABYLON.Matrix();
  20396. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  20397. // Constants
  20398. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  20399. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  20400. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  20401. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  20402. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  20403. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  20404. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  20405. // Postprocess
  20406. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  20407. }
  20408. _OculusInnerGamepadCamera.prototype.getProjectionMatrix = function () {
  20409. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  20410. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  20411. return this._projectionMatrix;
  20412. };
  20413. _OculusInnerGamepadCamera.prototype._getViewMatrix = function () {
  20414. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  20415. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  20416. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  20417. // Computing target and final matrix
  20418. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  20419. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  20420. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  20421. return this._viewMatrix;
  20422. };
  20423. return _OculusInnerGamepadCamera;
  20424. })(BABYLON.FreeCamera);
  20425. var OculusGamepadCamera = (function (_super) {
  20426. __extends(OculusGamepadCamera, _super);
  20427. function OculusGamepadCamera(name, position, scene) {
  20428. var _this = this;
  20429. _super.call(this, name, position, scene);
  20430. this.angularSensibility = 200;
  20431. this.moveSensibility = 75;
  20432. this._leftCamera = new _OculusInnerGamepadCamera(name + "_left", position.clone(), scene, true);
  20433. this._rightCamera = new _OculusInnerGamepadCamera(name + "_right", position.clone(), scene, false);
  20434. this.subCameras.push(this._leftCamera);
  20435. this.subCameras.push(this._rightCamera);
  20436. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  20437. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  20438. _this._onNewGameConnected(gamepad);
  20439. });
  20440. }
  20441. OculusGamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  20442. // Only the first gamepad can control the camera
  20443. if (gamepad.index === 0) {
  20444. this._gamepad = gamepad;
  20445. }
  20446. };
  20447. OculusGamepadCamera.prototype._update = function () {
  20448. this._leftCamera.position.copyFrom(this.position);
  20449. this._rightCamera.position.copyFrom(this.position);
  20450. this._updateCamera(this._leftCamera);
  20451. this._updateCamera(this._rightCamera);
  20452. _super.prototype._update.call(this);
  20453. };
  20454. OculusGamepadCamera.prototype._checkInputs = function () {
  20455. if (!this._gamepad) {
  20456. return;
  20457. }
  20458. var LSValues = this._gamepad.leftStick;
  20459. var normalizedLX = LSValues.x / this.moveSensibility;
  20460. var normalizedLY = LSValues.y / this.moveSensibility;
  20461. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  20462. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  20463. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  20464. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x, 0, -LSValues.y), cameraTransform);
  20465. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  20466. };
  20467. OculusGamepadCamera.prototype._updateCamera = function (camera) {
  20468. camera.minZ = this.minZ;
  20469. camera.maxZ = this.maxZ;
  20470. camera.rotation.x = this.rotation.x;
  20471. camera.rotation.y = this.rotation.y;
  20472. camera.rotation.z = this.rotation.z;
  20473. };
  20474. // Oculus events
  20475. OculusGamepadCamera.prototype._onOrientationEvent = function (evt) {
  20476. var yaw = evt.alpha / 180 * Math.PI;
  20477. var pitch = evt.beta / 180 * Math.PI;
  20478. var roll = evt.gamma / 180 * Math.PI;
  20479. if (!this._offsetOrientation) {
  20480. this._offsetOrientation = {
  20481. yaw: yaw,
  20482. pitch: pitch,
  20483. roll: roll
  20484. };
  20485. return;
  20486. }
  20487. else {
  20488. this.rotation.y += yaw - this._offsetOrientation.yaw;
  20489. this.rotation.x += pitch - this._offsetOrientation.pitch;
  20490. this.rotation.z += this._offsetOrientation.roll - roll;
  20491. this._offsetOrientation.yaw = yaw;
  20492. this._offsetOrientation.pitch = pitch;
  20493. this._offsetOrientation.roll = roll;
  20494. }
  20495. };
  20496. OculusGamepadCamera.prototype.attachControl = function (element, noPreventDefault) {
  20497. _super.prototype.attachControl.call(this, element, noPreventDefault);
  20498. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  20499. };
  20500. OculusGamepadCamera.prototype.detachControl = function (element) {
  20501. _super.prototype.detachControl.call(this, element);
  20502. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  20503. };
  20504. OculusGamepadCamera.prototype.dispose = function () {
  20505. this._gamepads.dispose();
  20506. _super.prototype.dispose.call(this);
  20507. };
  20508. return OculusGamepadCamera;
  20509. })(BABYLON.FreeCamera);
  20510. BABYLON.OculusGamepadCamera = OculusGamepadCamera;
  20511. })(BABYLON || (BABYLON = {}));
  20512. //# sourceMappingURL=babylon.oculusGamepadCamera.js.map
  20513. var BABYLON;
  20514. (function (BABYLON) {
  20515. // We're mainly based on the logic defined into the FreeCamera code
  20516. var VirtualJoysticksCamera = (function (_super) {
  20517. __extends(VirtualJoysticksCamera, _super);
  20518. function VirtualJoysticksCamera(name, position, scene) {
  20519. _super.call(this, name, position, scene);
  20520. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  20521. this._leftjoystick.setAxisForUpDown(2 /* Z */);
  20522. this._leftjoystick.setAxisForLeftRight(0 /* X */);
  20523. this._leftjoystick.setJoystickSensibility(0.15);
  20524. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  20525. this._rightjoystick.setAxisForUpDown(0 /* X */);
  20526. this._rightjoystick.setAxisForLeftRight(1 /* Y */);
  20527. this._rightjoystick.reverseUpDown = true;
  20528. this._rightjoystick.setJoystickSensibility(0.05);
  20529. this._rightjoystick.setJoystickColor("yellow");
  20530. }
  20531. VirtualJoysticksCamera.prototype._checkInputs = function () {
  20532. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  20533. var deltaTransform = BABYLON.Vector3.TransformCoordinates(this._leftjoystick.deltaPosition, cameraTransform);
  20534. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  20535. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  20536. if (!this._leftjoystick.pressed) {
  20537. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  20538. }
  20539. if (!this._rightjoystick.pressed) {
  20540. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  20541. }
  20542. };
  20543. VirtualJoysticksCamera.prototype.dispose = function () {
  20544. this._leftjoystick.releaseCanvas();
  20545. _super.prototype.dispose.call(this);
  20546. };
  20547. return VirtualJoysticksCamera;
  20548. })(BABYLON.FreeCamera);
  20549. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  20550. })(BABYLON || (BABYLON = {}));
  20551. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  20552. var BABYLON;
  20553. (function (BABYLON) {
  20554. var ShaderMaterial = (function (_super) {
  20555. __extends(ShaderMaterial, _super);
  20556. function ShaderMaterial(name, scene, shaderPath, options) {
  20557. _super.call(this, name, scene);
  20558. this._textures = new Array();
  20559. this._floats = new Array();
  20560. this._floatsArrays = {};
  20561. this._colors3 = new Array();
  20562. this._colors4 = new Array();
  20563. this._vectors2 = new Array();
  20564. this._vectors3 = new Array();
  20565. this._matrices = new Array();
  20566. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  20567. this._shaderPath = shaderPath;
  20568. options.needAlphaBlending = options.needAlphaBlending || false;
  20569. options.needAlphaTesting = options.needAlphaTesting || false;
  20570. options.attributes = options.attributes || ["position", "normal", "uv"];
  20571. options.uniforms = options.uniforms || ["worldViewProjection"];
  20572. options.samplers = options.samplers || [];
  20573. this._options = options;
  20574. }
  20575. ShaderMaterial.prototype.needAlphaBlending = function () {
  20576. return this._options.needAlphaBlending;
  20577. };
  20578. ShaderMaterial.prototype.needAlphaTesting = function () {
  20579. return this._options.needAlphaTesting;
  20580. };
  20581. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  20582. if (this._options.uniforms.indexOf(uniformName) === -1) {
  20583. this._options.uniforms.push(uniformName);
  20584. }
  20585. };
  20586. ShaderMaterial.prototype.setTexture = function (name, texture) {
  20587. if (this._options.samplers.indexOf(name) === -1) {
  20588. this._options.samplers.push(name);
  20589. }
  20590. this._textures[name] = texture;
  20591. return this;
  20592. };
  20593. ShaderMaterial.prototype.setFloat = function (name, value) {
  20594. this._checkUniform(name);
  20595. this._floats[name] = value;
  20596. return this;
  20597. };
  20598. ShaderMaterial.prototype.setFloats = function (name, value) {
  20599. this._checkUniform(name);
  20600. this._floatsArrays[name] = value;
  20601. return this;
  20602. };
  20603. ShaderMaterial.prototype.setColor3 = function (name, value) {
  20604. this._checkUniform(name);
  20605. this._colors3[name] = value;
  20606. return this;
  20607. };
  20608. ShaderMaterial.prototype.setColor4 = function (name, value) {
  20609. this._checkUniform(name);
  20610. this._colors4[name] = value;
  20611. return this;
  20612. };
  20613. ShaderMaterial.prototype.setVector2 = function (name, value) {
  20614. this._checkUniform(name);
  20615. this._vectors2[name] = value;
  20616. return this;
  20617. };
  20618. ShaderMaterial.prototype.setVector3 = function (name, value) {
  20619. this._checkUniform(name);
  20620. this._vectors3[name] = value;
  20621. return this;
  20622. };
  20623. ShaderMaterial.prototype.setMatrix = function (name, value) {
  20624. this._checkUniform(name);
  20625. this._matrices[name] = value;
  20626. return this;
  20627. };
  20628. ShaderMaterial.prototype.isReady = function () {
  20629. var scene = this.getScene();
  20630. var engine = scene.getEngine();
  20631. if (!this.checkReadyOnEveryCall) {
  20632. if (this._renderId === scene.getRenderId()) {
  20633. return true;
  20634. }
  20635. }
  20636. var previousEffect = this._effect;
  20637. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, "", null, this.onCompiled, this.onError);
  20638. if (!this._effect.isReady()) {
  20639. return false;
  20640. }
  20641. if (previousEffect !== this._effect) {
  20642. scene.resetCachedMaterial();
  20643. }
  20644. this._renderId = scene.getRenderId();
  20645. return true;
  20646. };
  20647. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  20648. var scene = this.getScene();
  20649. if (this._options.uniforms.indexOf("world") !== -1) {
  20650. this._effect.setMatrix("world", world);
  20651. }
  20652. if (this._options.uniforms.indexOf("worldView") !== -1) {
  20653. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  20654. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  20655. }
  20656. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  20657. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  20658. }
  20659. };
  20660. ShaderMaterial.prototype.bind = function (world) {
  20661. // Std values
  20662. this.bindOnlyWorldMatrix(world);
  20663. if (this.getScene().getCachedMaterial() !== this) {
  20664. if (this._options.uniforms.indexOf("view") !== -1) {
  20665. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  20666. }
  20667. if (this._options.uniforms.indexOf("projection") !== -1) {
  20668. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  20669. }
  20670. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  20671. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  20672. }
  20673. for (var name in this._textures) {
  20674. this._effect.setTexture(name, this._textures[name]);
  20675. }
  20676. for (name in this._floats) {
  20677. this._effect.setFloat(name, this._floats[name]);
  20678. }
  20679. for (name in this._floatsArrays) {
  20680. this._effect.setArray(name, this._floatsArrays[name]);
  20681. }
  20682. for (name in this._colors3) {
  20683. this._effect.setColor3(name, this._colors3[name]);
  20684. }
  20685. for (name in this._colors4) {
  20686. var color = this._colors4[name];
  20687. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  20688. }
  20689. for (name in this._vectors2) {
  20690. this._effect.setVector2(name, this._vectors2[name]);
  20691. }
  20692. for (name in this._vectors3) {
  20693. this._effect.setVector3(name, this._vectors3[name]);
  20694. }
  20695. for (name in this._matrices) {
  20696. this._effect.setMatrix(name, this._matrices[name]);
  20697. }
  20698. }
  20699. _super.prototype.bind.call(this, world, null);
  20700. };
  20701. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  20702. for (var name in this._textures) {
  20703. this._textures[name].dispose();
  20704. }
  20705. this._textures = [];
  20706. _super.prototype.dispose.call(this, forceDisposeEffect);
  20707. };
  20708. return ShaderMaterial;
  20709. })(BABYLON.Material);
  20710. BABYLON.ShaderMaterial = ShaderMaterial;
  20711. })(BABYLON || (BABYLON = {}));
  20712. //# sourceMappingURL=babylon.shaderMaterial.js.mapvar BABYLON;
  20713. (function (BABYLON) {
  20714. var VertexData = (function () {
  20715. function VertexData() {
  20716. }
  20717. VertexData.prototype.set = function (data, kind) {
  20718. switch (kind) {
  20719. case BABYLON.VertexBuffer.PositionKind:
  20720. this.positions = data;
  20721. break;
  20722. case BABYLON.VertexBuffer.NormalKind:
  20723. this.normals = data;
  20724. break;
  20725. case BABYLON.VertexBuffer.UVKind:
  20726. this.uvs = data;
  20727. break;
  20728. case BABYLON.VertexBuffer.UV2Kind:
  20729. this.uv2s = data;
  20730. break;
  20731. case BABYLON.VertexBuffer.ColorKind:
  20732. this.colors = data;
  20733. break;
  20734. case BABYLON.VertexBuffer.MatricesIndicesKind:
  20735. this.matricesIndices = data;
  20736. break;
  20737. case BABYLON.VertexBuffer.MatricesWeightsKind:
  20738. this.matricesWeights = data;
  20739. break;
  20740. }
  20741. };
  20742. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  20743. this._applyTo(mesh, updatable);
  20744. };
  20745. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  20746. this._applyTo(geometry, updatable);
  20747. };
  20748. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  20749. this._update(mesh);
  20750. };
  20751. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  20752. this._update(geometry);
  20753. };
  20754. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  20755. if (this.positions) {
  20756. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  20757. }
  20758. if (this.normals) {
  20759. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  20760. }
  20761. if (this.uvs) {
  20762. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  20763. }
  20764. if (this.uv2s) {
  20765. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updatable);
  20766. }
  20767. if (this.colors) {
  20768. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  20769. }
  20770. if (this.matricesIndices) {
  20771. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  20772. }
  20773. if (this.matricesWeights) {
  20774. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  20775. }
  20776. if (this.indices) {
  20777. meshOrGeometry.setIndices(this.indices);
  20778. }
  20779. };
  20780. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  20781. if (this.positions) {
  20782. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  20783. }
  20784. if (this.normals) {
  20785. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  20786. }
  20787. if (this.uvs) {
  20788. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  20789. }
  20790. if (this.uv2s) {
  20791. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updateExtends, makeItUnique);
  20792. }
  20793. if (this.colors) {
  20794. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  20795. }
  20796. if (this.matricesIndices) {
  20797. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  20798. }
  20799. if (this.matricesWeights) {
  20800. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  20801. }
  20802. if (this.indices) {
  20803. meshOrGeometry.setIndices(this.indices);
  20804. }
  20805. };
  20806. VertexData.prototype.transform = function (matrix) {
  20807. var transformed = BABYLON.Vector3.Zero();
  20808. if (this.positions) {
  20809. var position = BABYLON.Vector3.Zero();
  20810. for (var index = 0; index < this.positions.length; index += 3) {
  20811. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  20812. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  20813. this.positions[index] = transformed.x;
  20814. this.positions[index + 1] = transformed.y;
  20815. this.positions[index + 2] = transformed.z;
  20816. }
  20817. }
  20818. if (this.normals) {
  20819. var normal = BABYLON.Vector3.Zero();
  20820. for (index = 0; index < this.normals.length; index += 3) {
  20821. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  20822. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  20823. this.normals[index] = transformed.x;
  20824. this.normals[index + 1] = transformed.y;
  20825. this.normals[index + 2] = transformed.z;
  20826. }
  20827. }
  20828. };
  20829. VertexData.prototype.merge = function (other) {
  20830. if (other.indices) {
  20831. if (!this.indices) {
  20832. this.indices = [];
  20833. }
  20834. var offset = this.positions ? this.positions.length / 3 : 0;
  20835. for (var index = 0; index < other.indices.length; index++) {
  20836. this.indices.push(other.indices[index] + offset);
  20837. }
  20838. }
  20839. if (other.positions) {
  20840. if (!this.positions) {
  20841. this.positions = [];
  20842. }
  20843. for (index = 0; index < other.positions.length; index++) {
  20844. this.positions.push(other.positions[index]);
  20845. }
  20846. }
  20847. if (other.normals) {
  20848. if (!this.normals) {
  20849. this.normals = [];
  20850. }
  20851. for (index = 0; index < other.normals.length; index++) {
  20852. this.normals.push(other.normals[index]);
  20853. }
  20854. }
  20855. if (other.uvs) {
  20856. if (!this.uvs) {
  20857. this.uvs = [];
  20858. }
  20859. for (index = 0; index < other.uvs.length; index++) {
  20860. this.uvs.push(other.uvs[index]);
  20861. }
  20862. }
  20863. if (other.uv2s) {
  20864. if (!this.uv2s) {
  20865. this.uv2s = [];
  20866. }
  20867. for (index = 0; index < other.uv2s.length; index++) {
  20868. this.uv2s.push(other.uv2s[index]);
  20869. }
  20870. }
  20871. if (other.matricesIndices) {
  20872. if (!this.matricesIndices) {
  20873. this.matricesIndices = [];
  20874. }
  20875. for (index = 0; index < other.matricesIndices.length; index++) {
  20876. this.matricesIndices.push(other.matricesIndices[index]);
  20877. }
  20878. }
  20879. if (other.matricesWeights) {
  20880. if (!this.matricesWeights) {
  20881. this.matricesWeights = [];
  20882. }
  20883. for (index = 0; index < other.matricesWeights.length; index++) {
  20884. this.matricesWeights.push(other.matricesWeights[index]);
  20885. }
  20886. }
  20887. if (other.colors) {
  20888. if (!this.colors) {
  20889. this.colors = [];
  20890. }
  20891. for (index = 0; index < other.colors.length; index++) {
  20892. this.colors.push(other.colors[index]);
  20893. }
  20894. }
  20895. };
  20896. // Statics
  20897. VertexData.ExtractFromMesh = function (mesh) {
  20898. return VertexData._ExtractFrom(mesh);
  20899. };
  20900. VertexData.ExtractFromGeometry = function (geometry) {
  20901. return VertexData._ExtractFrom(geometry);
  20902. };
  20903. VertexData._ExtractFrom = function (meshOrGeometry) {
  20904. var result = new BABYLON.VertexData();
  20905. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  20906. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20907. }
  20908. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20909. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20910. }
  20911. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  20912. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind);
  20913. }
  20914. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  20915. result.uv2s = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  20916. }
  20917. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  20918. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  20919. }
  20920. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  20921. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  20922. }
  20923. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  20924. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  20925. }
  20926. result.indices = meshOrGeometry.getIndices();
  20927. return result;
  20928. };
  20929. VertexData.CreateBox = function (size) {
  20930. var normalsSource = [
  20931. new BABYLON.Vector3(0, 0, 1),
  20932. new BABYLON.Vector3(0, 0, -1),
  20933. new BABYLON.Vector3(1, 0, 0),
  20934. new BABYLON.Vector3(-1, 0, 0),
  20935. new BABYLON.Vector3(0, 1, 0),
  20936. new BABYLON.Vector3(0, -1, 0)
  20937. ];
  20938. var indices = [];
  20939. var positions = [];
  20940. var normals = [];
  20941. var uvs = [];
  20942. size = size || 1;
  20943. for (var index = 0; index < normalsSource.length; index++) {
  20944. var normal = normalsSource[index];
  20945. // Get two vectors perpendicular to the face normal and to each other.
  20946. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  20947. var side2 = BABYLON.Vector3.Cross(normal, side1);
  20948. // Six indices (two triangles) per face.
  20949. var verticesLength = positions.length / 3;
  20950. indices.push(verticesLength);
  20951. indices.push(verticesLength + 1);
  20952. indices.push(verticesLength + 2);
  20953. indices.push(verticesLength);
  20954. indices.push(verticesLength + 2);
  20955. indices.push(verticesLength + 3);
  20956. // Four vertices per face.
  20957. var vertex = normal.subtract(side1).subtract(side2).scale(size / 2);
  20958. positions.push(vertex.x, vertex.y, vertex.z);
  20959. normals.push(normal.x, normal.y, normal.z);
  20960. uvs.push(1.0, 1.0);
  20961. vertex = normal.subtract(side1).add(side2).scale(size / 2);
  20962. positions.push(vertex.x, vertex.y, vertex.z);
  20963. normals.push(normal.x, normal.y, normal.z);
  20964. uvs.push(0.0, 1.0);
  20965. vertex = normal.add(side1).add(side2).scale(size / 2);
  20966. positions.push(vertex.x, vertex.y, vertex.z);
  20967. normals.push(normal.x, normal.y, normal.z);
  20968. uvs.push(0.0, 0.0);
  20969. vertex = normal.add(side1).subtract(side2).scale(size / 2);
  20970. positions.push(vertex.x, vertex.y, vertex.z);
  20971. normals.push(normal.x, normal.y, normal.z);
  20972. uvs.push(1.0, 0.0);
  20973. }
  20974. // Result
  20975. var vertexData = new BABYLON.VertexData();
  20976. vertexData.indices = indices;
  20977. vertexData.positions = positions;
  20978. vertexData.normals = normals;
  20979. vertexData.uvs = uvs;
  20980. return vertexData;
  20981. };
  20982. VertexData.CreateSphere = function (segments, diameter) {
  20983. segments = segments || 32;
  20984. diameter = diameter || 1;
  20985. var radius = diameter / 2;
  20986. var totalZRotationSteps = 2 + segments;
  20987. var totalYRotationSteps = 2 * totalZRotationSteps;
  20988. var indices = [];
  20989. var positions = [];
  20990. var normals = [];
  20991. var uvs = [];
  20992. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  20993. var normalizedZ = zRotationStep / totalZRotationSteps;
  20994. var angleZ = (normalizedZ * Math.PI);
  20995. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  20996. var normalizedY = yRotationStep / totalYRotationSteps;
  20997. var angleY = normalizedY * Math.PI * 2;
  20998. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  20999. var rotationY = BABYLON.Matrix.RotationY(angleY);
  21000. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  21001. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  21002. var vertex = complete.scale(radius);
  21003. var normal = BABYLON.Vector3.Normalize(vertex);
  21004. positions.push(vertex.x, vertex.y, vertex.z);
  21005. normals.push(normal.x, normal.y, normal.z);
  21006. uvs.push(normalizedZ, normalizedY);
  21007. }
  21008. if (zRotationStep > 0) {
  21009. var verticesCount = positions.length / 3;
  21010. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  21011. indices.push((firstIndex));
  21012. indices.push((firstIndex + 1));
  21013. indices.push(firstIndex + totalYRotationSteps + 1);
  21014. indices.push((firstIndex + totalYRotationSteps + 1));
  21015. indices.push((firstIndex + 1));
  21016. indices.push((firstIndex + totalYRotationSteps + 2));
  21017. }
  21018. }
  21019. }
  21020. // Result
  21021. var vertexData = new BABYLON.VertexData();
  21022. vertexData.indices = indices;
  21023. vertexData.positions = positions;
  21024. vertexData.normals = normals;
  21025. vertexData.uvs = uvs;
  21026. return vertexData;
  21027. };
  21028. VertexData.CreateCylinder = function (height, diameterTop, diameterBottom, tessellation, subdivisions) {
  21029. if (subdivisions === void 0) { subdivisions = 1; }
  21030. var radiusTop = diameterTop / 2;
  21031. var radiusBottom = diameterBottom / 2;
  21032. var indices = [];
  21033. var positions = [];
  21034. var normals = [];
  21035. var uvs = [];
  21036. height = height || 1;
  21037. diameterTop = diameterTop || 0.5;
  21038. diameterBottom = diameterBottom || 1;
  21039. tessellation = tessellation || 16;
  21040. subdivisions = subdivisions || 1;
  21041. subdivisions = (subdivisions < 1) ? 1 : subdivisions;
  21042. var getCircleVector = function (i) {
  21043. var angle = (i * 2.0 * Math.PI / tessellation);
  21044. var dx = Math.cos(angle);
  21045. var dz = Math.sin(angle);
  21046. return new BABYLON.Vector3(dx, 0, dz);
  21047. };
  21048. var createCylinderCap = function (isTop) {
  21049. var radius = isTop ? radiusTop : radiusBottom;
  21050. if (radius == 0) {
  21051. return;
  21052. }
  21053. var vbase = positions.length / 3;
  21054. var offset = new BABYLON.Vector3(0, height / 2, 0);
  21055. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  21056. if (!isTop) {
  21057. offset.scaleInPlace(-1);
  21058. textureScale.x = -textureScale.x;
  21059. }
  21060. for (i = 0; i < tessellation; i++) {
  21061. var circleVector = getCircleVector(i);
  21062. var position = circleVector.scale(radius).add(offset);
  21063. var textureCoordinate = new BABYLON.Vector2(circleVector.x * textureScale.x + 0.5, circleVector.z * textureScale.y + 0.5);
  21064. positions.push(position.x, position.y, position.z);
  21065. uvs.push(textureCoordinate.x, textureCoordinate.y);
  21066. }
  21067. for (var i = 0; i < tessellation - 2; i++) {
  21068. if (!isTop) {
  21069. indices.push(vbase);
  21070. indices.push(vbase + (i + 2) % tessellation);
  21071. indices.push(vbase + (i + 1) % tessellation);
  21072. }
  21073. else {
  21074. indices.push(vbase);
  21075. indices.push(vbase + (i + 1) % tessellation);
  21076. indices.push(vbase + (i + 2) % tessellation);
  21077. }
  21078. }
  21079. };
  21080. var base = new BABYLON.Vector3(0, -1, 0).scale(height / 2);
  21081. var offset = new BABYLON.Vector3(0, 1, 0).scale(height / subdivisions);
  21082. var stride = tessellation + 1;
  21083. for (var i = 0; i <= tessellation; i++) {
  21084. var circleVector = getCircleVector(i);
  21085. var textureCoordinate = new BABYLON.Vector2(i / tessellation, 0);
  21086. var position, radius = radiusBottom;
  21087. for (var s = 0; s <= subdivisions; s++) {
  21088. // Update variables
  21089. position = circleVector.scale(radius);
  21090. position.addInPlace(base.add(offset.scale(s)));
  21091. textureCoordinate.y += 1 / subdivisions;
  21092. radius += (radiusTop - radiusBottom) / subdivisions;
  21093. // Push in arrays
  21094. positions.push(position.x, position.y, position.z);
  21095. uvs.push(textureCoordinate.x, textureCoordinate.y);
  21096. }
  21097. }
  21098. subdivisions += 1;
  21099. for (var s = 0; s < subdivisions - 1; s++) {
  21100. for (var i = 0; i <= tessellation; i++) {
  21101. indices.push(i * subdivisions + s);
  21102. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  21103. indices.push(i * subdivisions + (s + 1));
  21104. indices.push(i * subdivisions + (s + 1));
  21105. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  21106. indices.push((i * subdivisions + (s + subdivisions + 1)) % (stride * subdivisions));
  21107. }
  21108. }
  21109. // Create flat triangle fan caps to seal the top and bottom.
  21110. createCylinderCap(true);
  21111. createCylinderCap(false);
  21112. // Normals
  21113. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  21114. // Result
  21115. var vertexData = new BABYLON.VertexData();
  21116. vertexData.indices = indices;
  21117. vertexData.positions = positions;
  21118. vertexData.normals = normals;
  21119. vertexData.uvs = uvs;
  21120. return vertexData;
  21121. };
  21122. VertexData.CreateTorus = function (diameter, thickness, tessellation) {
  21123. var indices = [];
  21124. var positions = [];
  21125. var normals = [];
  21126. var uvs = [];
  21127. diameter = diameter || 1;
  21128. thickness = thickness || 0.5;
  21129. tessellation = tessellation || 16;
  21130. var stride = tessellation + 1;
  21131. for (var i = 0; i <= tessellation; i++) {
  21132. var u = i / tessellation;
  21133. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  21134. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  21135. for (var j = 0; j <= tessellation; j++) {
  21136. var v = 1 - j / tessellation;
  21137. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  21138. var dx = Math.cos(innerAngle);
  21139. var dy = Math.sin(innerAngle);
  21140. // Create a vertex.
  21141. var normal = new BABYLON.Vector3(dx, dy, 0);
  21142. var position = normal.scale(thickness / 2);
  21143. var textureCoordinate = new BABYLON.Vector2(u, v);
  21144. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  21145. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  21146. positions.push(position.x, position.y, position.z);
  21147. normals.push(normal.x, normal.y, normal.z);
  21148. uvs.push(textureCoordinate.x, textureCoordinate.y);
  21149. // And create indices for two triangles.
  21150. var nextI = (i + 1) % stride;
  21151. var nextJ = (j + 1) % stride;
  21152. indices.push(i * stride + j);
  21153. indices.push(i * stride + nextJ);
  21154. indices.push(nextI * stride + j);
  21155. indices.push(i * stride + nextJ);
  21156. indices.push(nextI * stride + nextJ);
  21157. indices.push(nextI * stride + j);
  21158. }
  21159. }
  21160. // Result
  21161. var vertexData = new BABYLON.VertexData();
  21162. vertexData.indices = indices;
  21163. vertexData.positions = positions;
  21164. vertexData.normals = normals;
  21165. vertexData.uvs = uvs;
  21166. return vertexData;
  21167. };
  21168. VertexData.CreateLines = function (points) {
  21169. var indices = [];
  21170. var positions = [];
  21171. for (var index = 0; index < points.length; index++) {
  21172. positions.push(points[index].x, points[index].y, points[index].z);
  21173. if (index > 0) {
  21174. indices.push(index - 1);
  21175. indices.push(index);
  21176. }
  21177. }
  21178. // Result
  21179. var vertexData = new BABYLON.VertexData();
  21180. vertexData.indices = indices;
  21181. vertexData.positions = positions;
  21182. return vertexData;
  21183. };
  21184. VertexData.CreateGround = function (width, height, subdivisions) {
  21185. var indices = [];
  21186. var positions = [];
  21187. var normals = [];
  21188. var uvs = [];
  21189. var row, col;
  21190. width = width || 1;
  21191. height = height || 1;
  21192. subdivisions = subdivisions || 1;
  21193. for (row = 0; row <= subdivisions; row++) {
  21194. for (col = 0; col <= subdivisions; col++) {
  21195. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  21196. var normal = new BABYLON.Vector3(0, 1.0, 0);
  21197. positions.push(position.x, position.y, position.z);
  21198. normals.push(normal.x, normal.y, normal.z);
  21199. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  21200. }
  21201. }
  21202. for (row = 0; row < subdivisions; row++) {
  21203. for (col = 0; col < subdivisions; col++) {
  21204. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  21205. indices.push(col + 1 + row * (subdivisions + 1));
  21206. indices.push(col + row * (subdivisions + 1));
  21207. indices.push(col + (row + 1) * (subdivisions + 1));
  21208. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  21209. indices.push(col + row * (subdivisions + 1));
  21210. }
  21211. }
  21212. // Result
  21213. var vertexData = new BABYLON.VertexData();
  21214. vertexData.indices = indices;
  21215. vertexData.positions = positions;
  21216. vertexData.normals = normals;
  21217. vertexData.uvs = uvs;
  21218. return vertexData;
  21219. };
  21220. VertexData.CreateTiledGround = function (xmin, zmin, xmax, zmax, subdivisions, precision) {
  21221. if (subdivisions === void 0) { subdivisions = { w: 1, h: 1 }; }
  21222. if (precision === void 0) { precision = { w: 1, h: 1 }; }
  21223. var indices = [];
  21224. var positions = [];
  21225. var normals = [];
  21226. var uvs = [];
  21227. var row, col, tileRow, tileCol;
  21228. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  21229. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  21230. precision.w = (precision.w < 1) ? 1 : precision.w;
  21231. precision.h = (precision.h < 1) ? 1 : precision.h;
  21232. var tileSize = {
  21233. 'w': (xmax - xmin) / subdivisions.w,
  21234. 'h': (zmax - zmin) / subdivisions.h
  21235. };
  21236. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  21237. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  21238. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  21239. }
  21240. }
  21241. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  21242. // Indices
  21243. var base = positions.length / 3;
  21244. var rowLength = precision.w + 1;
  21245. for (row = 0; row < precision.h; row++) {
  21246. for (col = 0; col < precision.w; col++) {
  21247. var square = [
  21248. base + col + row * rowLength,
  21249. base + (col + 1) + row * rowLength,
  21250. base + (col + 1) + (row + 1) * rowLength,
  21251. base + col + (row + 1) * rowLength
  21252. ];
  21253. indices.push(square[1]);
  21254. indices.push(square[2]);
  21255. indices.push(square[3]);
  21256. indices.push(square[0]);
  21257. indices.push(square[1]);
  21258. indices.push(square[3]);
  21259. }
  21260. }
  21261. // Position, normals and uvs
  21262. var position = BABYLON.Vector3.Zero();
  21263. var normal = new BABYLON.Vector3(0, 1.0, 0);
  21264. for (row = 0; row <= precision.h; row++) {
  21265. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  21266. for (col = 0; col <= precision.w; col++) {
  21267. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  21268. position.y = 0;
  21269. positions.push(position.x, position.y, position.z);
  21270. normals.push(normal.x, normal.y, normal.z);
  21271. uvs.push(col / precision.w, row / precision.h);
  21272. }
  21273. }
  21274. }
  21275. // Result
  21276. var vertexData = new BABYLON.VertexData();
  21277. vertexData.indices = indices;
  21278. vertexData.positions = positions;
  21279. vertexData.normals = normals;
  21280. vertexData.uvs = uvs;
  21281. return vertexData;
  21282. };
  21283. VertexData.CreateGroundFromHeightMap = function (width, height, subdivisions, minHeight, maxHeight, buffer, bufferWidth, bufferHeight) {
  21284. var indices = [];
  21285. var positions = [];
  21286. var normals = [];
  21287. var uvs = [];
  21288. var row, col;
  21289. for (row = 0; row <= subdivisions; row++) {
  21290. for (col = 0; col <= subdivisions; col++) {
  21291. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  21292. // Compute height
  21293. var heightMapX = (((position.x + width / 2) / width) * (bufferWidth - 1)) | 0;
  21294. var heightMapY = ((1.0 - (position.z + height / 2) / height) * (bufferHeight - 1)) | 0;
  21295. var pos = (heightMapX + heightMapY * bufferWidth) * 4;
  21296. var r = buffer[pos] / 255.0;
  21297. var g = buffer[pos + 1] / 255.0;
  21298. var b = buffer[pos + 2] / 255.0;
  21299. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  21300. position.y = minHeight + (maxHeight - minHeight) * gradient;
  21301. // Add vertex
  21302. positions.push(position.x, position.y, position.z);
  21303. normals.push(0, 0, 0);
  21304. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  21305. }
  21306. }
  21307. for (row = 0; row < subdivisions; row++) {
  21308. for (col = 0; col < subdivisions; col++) {
  21309. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  21310. indices.push(col + 1 + row * (subdivisions + 1));
  21311. indices.push(col + row * (subdivisions + 1));
  21312. indices.push(col + (row + 1) * (subdivisions + 1));
  21313. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  21314. indices.push(col + row * (subdivisions + 1));
  21315. }
  21316. }
  21317. // Normals
  21318. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  21319. // Result
  21320. var vertexData = new BABYLON.VertexData();
  21321. vertexData.indices = indices;
  21322. vertexData.positions = positions;
  21323. vertexData.normals = normals;
  21324. vertexData.uvs = uvs;
  21325. return vertexData;
  21326. };
  21327. VertexData.CreatePlane = function (size) {
  21328. var indices = [];
  21329. var positions = [];
  21330. var normals = [];
  21331. var uvs = [];
  21332. size = size || 1;
  21333. // Vertices
  21334. var halfSize = size / 2.0;
  21335. positions.push(-halfSize, -halfSize, 0);
  21336. normals.push(0, 0, -1.0);
  21337. uvs.push(0.0, 0.0);
  21338. positions.push(halfSize, -halfSize, 0);
  21339. normals.push(0, 0, -1.0);
  21340. uvs.push(1.0, 0.0);
  21341. positions.push(halfSize, halfSize, 0);
  21342. normals.push(0, 0, -1.0);
  21343. uvs.push(1.0, 1.0);
  21344. positions.push(-halfSize, halfSize, 0);
  21345. normals.push(0, 0, -1.0);
  21346. uvs.push(0.0, 1.0);
  21347. // Indices
  21348. indices.push(0);
  21349. indices.push(1);
  21350. indices.push(2);
  21351. indices.push(0);
  21352. indices.push(2);
  21353. indices.push(3);
  21354. // Result
  21355. var vertexData = new BABYLON.VertexData();
  21356. vertexData.indices = indices;
  21357. vertexData.positions = positions;
  21358. vertexData.normals = normals;
  21359. vertexData.uvs = uvs;
  21360. return vertexData;
  21361. };
  21362. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  21363. VertexData.CreateTorusKnot = function (radius, tube, radialSegments, tubularSegments, p, q) {
  21364. var indices = [];
  21365. var positions = [];
  21366. var normals = [];
  21367. var uvs = [];
  21368. radius = radius || 2;
  21369. tube = tube || 0.5;
  21370. radialSegments = radialSegments || 32;
  21371. tubularSegments = tubularSegments || 32;
  21372. p = p || 2;
  21373. q = q || 3;
  21374. // Helper
  21375. var getPos = function (angle) {
  21376. var cu = Math.cos(angle);
  21377. var su = Math.sin(angle);
  21378. var quOverP = q / p * angle;
  21379. var cs = Math.cos(quOverP);
  21380. var tx = radius * (2 + cs) * 0.5 * cu;
  21381. var ty = radius * (2 + cs) * su * 0.5;
  21382. var tz = radius * Math.sin(quOverP) * 0.5;
  21383. return new BABYLON.Vector3(tx, ty, tz);
  21384. };
  21385. for (var i = 0; i <= radialSegments; i++) {
  21386. var modI = i % radialSegments;
  21387. var u = modI / radialSegments * 2 * p * Math.PI;
  21388. var p1 = getPos(u);
  21389. var p2 = getPos(u + 0.01);
  21390. var tang = p2.subtract(p1);
  21391. var n = p2.add(p1);
  21392. var bitan = BABYLON.Vector3.Cross(tang, n);
  21393. n = BABYLON.Vector3.Cross(bitan, tang);
  21394. bitan.normalize();
  21395. n.normalize();
  21396. for (var j = 0; j < tubularSegments; j++) {
  21397. var modJ = j % tubularSegments;
  21398. var v = modJ / tubularSegments * 2 * Math.PI;
  21399. var cx = -tube * Math.cos(v);
  21400. var cy = tube * Math.sin(v);
  21401. positions.push(p1.x + cx * n.x + cy * bitan.x);
  21402. positions.push(p1.y + cx * n.y + cy * bitan.y);
  21403. positions.push(p1.z + cx * n.z + cy * bitan.z);
  21404. uvs.push(i / radialSegments);
  21405. uvs.push(j / tubularSegments);
  21406. }
  21407. }
  21408. for (i = 0; i < radialSegments; i++) {
  21409. for (j = 0; j < tubularSegments; j++) {
  21410. var jNext = (j + 1) % tubularSegments;
  21411. var a = i * tubularSegments + j;
  21412. var b = (i + 1) * tubularSegments + j;
  21413. var c = (i + 1) * tubularSegments + jNext;
  21414. var d = i * tubularSegments + jNext;
  21415. indices.push(d);
  21416. indices.push(b);
  21417. indices.push(a);
  21418. indices.push(d);
  21419. indices.push(c);
  21420. indices.push(b);
  21421. }
  21422. }
  21423. // Normals
  21424. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  21425. // Result
  21426. var vertexData = new BABYLON.VertexData();
  21427. vertexData.indices = indices;
  21428. vertexData.positions = positions;
  21429. vertexData.normals = normals;
  21430. vertexData.uvs = uvs;
  21431. return vertexData;
  21432. };
  21433. // Tools
  21434. VertexData.ComputeNormals = function (positions, indices, normals) {
  21435. var positionVectors = [];
  21436. var facesOfVertices = [];
  21437. var index;
  21438. for (index = 0; index < positions.length; index += 3) {
  21439. var vector3 = new BABYLON.Vector3(positions[index], positions[index + 1], positions[index + 2]);
  21440. positionVectors.push(vector3);
  21441. facesOfVertices.push([]);
  21442. }
  21443. // Compute normals
  21444. var facesNormals = [];
  21445. for (index = 0; index < indices.length / 3; index++) {
  21446. var i1 = indices[index * 3];
  21447. var i2 = indices[index * 3 + 1];
  21448. var i3 = indices[index * 3 + 2];
  21449. var p1 = positionVectors[i1];
  21450. var p2 = positionVectors[i2];
  21451. var p3 = positionVectors[i3];
  21452. var p1p2 = p1.subtract(p2);
  21453. var p3p2 = p3.subtract(p2);
  21454. facesNormals[index] = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  21455. facesOfVertices[i1].push(index);
  21456. facesOfVertices[i2].push(index);
  21457. facesOfVertices[i3].push(index);
  21458. }
  21459. for (index = 0; index < positionVectors.length; index++) {
  21460. var faces = facesOfVertices[index];
  21461. var normal = BABYLON.Vector3.Zero();
  21462. for (var faceIndex = 0; faceIndex < faces.length; faceIndex++) {
  21463. normal.addInPlace(facesNormals[faces[faceIndex]]);
  21464. }
  21465. normal = BABYLON.Vector3.Normalize(normal.scale(1.0 / faces.length));
  21466. normals[index * 3] = normal.x;
  21467. normals[index * 3 + 1] = normal.y;
  21468. normals[index * 3 + 2] = normal.z;
  21469. }
  21470. };
  21471. return VertexData;
  21472. })();
  21473. BABYLON.VertexData = VertexData;
  21474. })(BABYLON || (BABYLON = {}));
  21475. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  21476. var BABYLON;
  21477. (function (BABYLON) {
  21478. var buildCamera = function (that, name) {
  21479. that._leftCamera.isIntermediate = true;
  21480. that.subCameras.push(that._leftCamera);
  21481. that.subCameras.push(that._rightCamera);
  21482. that._leftTexture = new BABYLON.PassPostProcess(name + "_leftTexture", 1.0, that._leftCamera);
  21483. that._anaglyphPostProcess = new BABYLON.AnaglyphPostProcess(name + "_anaglyph", 1.0, that._rightCamera);
  21484. that._anaglyphPostProcess.onApply = function (effect) {
  21485. effect.setTextureFromPostProcess("leftSampler", that._leftTexture);
  21486. };
  21487. that._update();
  21488. };
  21489. var AnaglyphArcRotateCamera = (function (_super) {
  21490. __extends(AnaglyphArcRotateCamera, _super);
  21491. // ANY
  21492. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, eyeSpace, scene) {
  21493. _super.call(this, name, alpha, beta, radius, target, scene);
  21494. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  21495. this._leftCamera = new BABYLON.ArcRotateCamera(name + "_left", alpha - this._eyeSpace, beta, radius, target, scene);
  21496. this._rightCamera = new BABYLON.ArcRotateCamera(name + "_right", alpha + this._eyeSpace, beta, radius, target, scene);
  21497. buildCamera(this, name);
  21498. }
  21499. AnaglyphArcRotateCamera.prototype._update = function () {
  21500. this._updateCamera(this._leftCamera);
  21501. this._updateCamera(this._rightCamera);
  21502. this._leftCamera.alpha = this.alpha - this._eyeSpace;
  21503. this._rightCamera.alpha = this.alpha + this._eyeSpace;
  21504. _super.prototype._update.call(this);
  21505. };
  21506. AnaglyphArcRotateCamera.prototype._updateCamera = function (camera) {
  21507. camera.beta = this.beta;
  21508. camera.radius = this.radius;
  21509. camera.minZ = this.minZ;
  21510. camera.maxZ = this.maxZ;
  21511. camera.fov = this.fov;
  21512. camera.target = this.target;
  21513. };
  21514. return AnaglyphArcRotateCamera;
  21515. })(BABYLON.ArcRotateCamera);
  21516. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  21517. var AnaglyphFreeCamera = (function (_super) {
  21518. __extends(AnaglyphFreeCamera, _super);
  21519. function AnaglyphFreeCamera(name, position, eyeSpace, scene) {
  21520. _super.call(this, name, position, scene);
  21521. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  21522. this._transformMatrix = new BABYLON.Matrix();
  21523. this._leftCamera = new BABYLON.FreeCamera(name + "_left", position.clone(), scene);
  21524. this._rightCamera = new BABYLON.FreeCamera(name + "_right", position.clone(), scene);
  21525. buildCamera(this, name);
  21526. }
  21527. AnaglyphFreeCamera.prototype._getSubCameraPosition = function (eyeSpace, result) {
  21528. var target = this.getTarget();
  21529. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(eyeSpace), this._transformMatrix);
  21530. this._transformMatrix = this._transformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  21531. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._transformMatrix, result);
  21532. };
  21533. AnaglyphFreeCamera.prototype._update = function () {
  21534. this._getSubCameraPosition(-this._eyeSpace, this._leftCamera.position);
  21535. this._getSubCameraPosition(this._eyeSpace, this._rightCamera.position);
  21536. this._updateCamera(this._leftCamera);
  21537. this._updateCamera(this._rightCamera);
  21538. _super.prototype._update.call(this);
  21539. };
  21540. AnaglyphFreeCamera.prototype._updateCamera = function (camera) {
  21541. camera.minZ = this.minZ;
  21542. camera.maxZ = this.maxZ;
  21543. camera.fov = this.fov;
  21544. camera.viewport = this.viewport;
  21545. camera.setTarget(this.getTarget());
  21546. };
  21547. return AnaglyphFreeCamera;
  21548. })(BABYLON.FreeCamera);
  21549. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  21550. })(BABYLON || (BABYLON = {}));
  21551. //# sourceMappingURL=babylon.anaglyphCamera.js.map
  21552. var BABYLON;
  21553. (function (BABYLON) {
  21554. var AnaglyphPostProcess = (function (_super) {
  21555. __extends(AnaglyphPostProcess, _super);
  21556. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  21557. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  21558. }
  21559. return AnaglyphPostProcess;
  21560. })(BABYLON.PostProcess);
  21561. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  21562. })(BABYLON || (BABYLON = {}));
  21563. //# sourceMappingURL=babylon.anaglyphPostProcess.js.mapvar BABYLON;
  21564. (function (BABYLON) {
  21565. var Tags = (function () {
  21566. function Tags() {
  21567. }
  21568. Tags.EnableFor = function (obj) {
  21569. obj._tags = obj._tags || {};
  21570. obj.hasTags = function () {
  21571. return Tags.HasTags(obj);
  21572. };
  21573. obj.addTags = function (tagsString) {
  21574. return Tags.AddTagsTo(obj, tagsString);
  21575. };
  21576. obj.removeTags = function (tagsString) {
  21577. return Tags.RemoveTagsFrom(obj, tagsString);
  21578. };
  21579. obj.matchesTagsQuery = function (tagsQuery) {
  21580. return Tags.MatchesQuery(obj, tagsQuery);
  21581. };
  21582. };
  21583. Tags.DisableFor = function (obj) {
  21584. delete obj._tags;
  21585. delete obj.hasTags;
  21586. delete obj.addTags;
  21587. delete obj.removeTags;
  21588. delete obj.matchesTagsQuery;
  21589. };
  21590. Tags.HasTags = function (obj) {
  21591. if (!obj._tags) {
  21592. return false;
  21593. }
  21594. return !BABYLON.Tools.IsEmpty(obj._tags);
  21595. };
  21596. Tags.GetTags = function (obj) {
  21597. if (!obj._tags) {
  21598. return null;
  21599. }
  21600. return obj._tags;
  21601. };
  21602. // the tags 'true' and 'false' are reserved and cannot be used as tags
  21603. // a tag cannot start with '||', '&&', and '!'
  21604. // it cannot contain whitespaces
  21605. Tags.AddTagsTo = function (obj, tagsString) {
  21606. if (!tagsString) {
  21607. return;
  21608. }
  21609. var tags = tagsString.split(" ");
  21610. for (var t in tags) {
  21611. Tags._AddTagTo(obj, tags[t]);
  21612. }
  21613. };
  21614. Tags._AddTagTo = function (obj, tag) {
  21615. tag = tag.trim();
  21616. if (tag === "" || tag === "true" || tag === "false") {
  21617. return;
  21618. }
  21619. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  21620. return;
  21621. }
  21622. Tags.EnableFor(obj);
  21623. obj._tags[tag] = true;
  21624. };
  21625. Tags.RemoveTagsFrom = function (obj, tagsString) {
  21626. if (!Tags.HasTags(obj)) {
  21627. return;
  21628. }
  21629. var tags = tagsString.split(" ");
  21630. for (var t in tags) {
  21631. Tags._RemoveTagFrom(obj, tags[t]);
  21632. }
  21633. };
  21634. Tags._RemoveTagFrom = function (obj, tag) {
  21635. delete obj._tags[tag];
  21636. };
  21637. Tags.MatchesQuery = function (obj, tagsQuery) {
  21638. if (tagsQuery === undefined) {
  21639. return true;
  21640. }
  21641. if (tagsQuery === "") {
  21642. return Tags.HasTags(obj);
  21643. }
  21644. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  21645. };
  21646. return Tags;
  21647. })();
  21648. BABYLON.Tags = Tags;
  21649. })(BABYLON || (BABYLON = {}));
  21650. //# sourceMappingURL=babylon.tags.js.mapvar BABYLON;
  21651. (function (BABYLON) {
  21652. var Internals;
  21653. (function (Internals) {
  21654. var AndOrNotEvaluator = (function () {
  21655. function AndOrNotEvaluator() {
  21656. }
  21657. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  21658. if (!query.match(/\([^\(\)]*\)/g)) {
  21659. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  21660. }
  21661. else {
  21662. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  21663. // remove parenthesis
  21664. r = r.slice(1, r.length - 1);
  21665. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  21666. });
  21667. }
  21668. if (query === "true") {
  21669. return true;
  21670. }
  21671. if (query === "false") {
  21672. return false;
  21673. }
  21674. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  21675. };
  21676. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  21677. evaluateCallback = evaluateCallback || (function (r) {
  21678. return r === "true" ? true : false;
  21679. });
  21680. var result;
  21681. var or = parenthesisContent.split("||");
  21682. for (var i in or) {
  21683. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  21684. var and = ori.split("&&");
  21685. if (and.length > 1) {
  21686. for (var j = 0; j < and.length; ++j) {
  21687. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  21688. if (andj !== "true" && andj !== "false") {
  21689. if (andj[0] === "!") {
  21690. result = !evaluateCallback(andj.substring(1));
  21691. }
  21692. else {
  21693. result = evaluateCallback(andj);
  21694. }
  21695. }
  21696. else {
  21697. result = andj === "true" ? true : false;
  21698. }
  21699. if (!result) {
  21700. ori = "false";
  21701. break;
  21702. }
  21703. }
  21704. }
  21705. if (result || ori === "true") {
  21706. result = true;
  21707. break;
  21708. }
  21709. // result equals false (or undefined)
  21710. if (ori !== "true" && ori !== "false") {
  21711. if (ori[0] === "!") {
  21712. result = !evaluateCallback(ori.substring(1));
  21713. }
  21714. else {
  21715. result = evaluateCallback(ori);
  21716. }
  21717. }
  21718. else {
  21719. result = ori === "true" ? true : false;
  21720. }
  21721. }
  21722. // the whole parenthesis scope is replaced by 'true' or 'false'
  21723. return result ? "true" : "false";
  21724. };
  21725. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  21726. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  21727. // remove whitespaces
  21728. r = r.replace(/[\s]/g, function () { return ""; });
  21729. return r.length % 2 ? "!" : "";
  21730. });
  21731. booleanString = booleanString.trim();
  21732. if (booleanString === "!true") {
  21733. booleanString = "false";
  21734. }
  21735. else if (booleanString === "!false") {
  21736. booleanString = "true";
  21737. }
  21738. return booleanString;
  21739. };
  21740. return AndOrNotEvaluator;
  21741. })();
  21742. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  21743. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  21744. })(BABYLON || (BABYLON = {}));
  21745. //# sourceMappingURL=babylon.andOrNotEvaluator.js.mapvar BABYLON;
  21746. (function (BABYLON) {
  21747. var PostProcessRenderPass = (function () {
  21748. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  21749. this._enabled = true;
  21750. this._refCount = 0;
  21751. this._name = name;
  21752. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  21753. this.setRenderList(renderList);
  21754. this._renderTexture.onBeforeRender = beforeRender;
  21755. this._renderTexture.onAfterRender = afterRender;
  21756. this._scene = scene;
  21757. this._renderList = renderList;
  21758. }
  21759. // private
  21760. PostProcessRenderPass.prototype._incRefCount = function () {
  21761. if (this._refCount === 0) {
  21762. this._scene.customRenderTargets.push(this._renderTexture);
  21763. }
  21764. return ++this._refCount;
  21765. };
  21766. PostProcessRenderPass.prototype._decRefCount = function () {
  21767. this._refCount--;
  21768. if (this._refCount <= 0) {
  21769. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  21770. }
  21771. return this._refCount;
  21772. };
  21773. PostProcessRenderPass.prototype._update = function () {
  21774. this.setRenderList(this._renderList);
  21775. };
  21776. // public
  21777. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  21778. this._renderTexture.renderList = renderList;
  21779. };
  21780. PostProcessRenderPass.prototype.getRenderTexture = function () {
  21781. return this._renderTexture;
  21782. };
  21783. return PostProcessRenderPass;
  21784. })();
  21785. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  21786. })(BABYLON || (BABYLON = {}));
  21787. //# sourceMappingURL=babylon.postProcessRenderPass.js.mapvar BABYLON;
  21788. (function (BABYLON) {
  21789. var PostProcessRenderEffect = (function () {
  21790. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  21791. this._engine = engine;
  21792. this._name = name;
  21793. this._singleInstance = singleInstance || true;
  21794. this._getPostProcess = getPostProcess;
  21795. this._cameras = [];
  21796. this._indicesForCamera = [];
  21797. this._postProcesses = {};
  21798. this._renderPasses = {};
  21799. this._renderEffectAsPasses = {};
  21800. }
  21801. PostProcessRenderEffect.prototype._update = function () {
  21802. for (var renderPassName in this._renderPasses) {
  21803. this._renderPasses[renderPassName]._update();
  21804. }
  21805. };
  21806. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  21807. this._renderPasses[renderPass._name] = renderPass;
  21808. this._linkParameters();
  21809. };
  21810. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  21811. delete this._renderPasses[renderPass._name];
  21812. this._linkParameters();
  21813. };
  21814. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  21815. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  21816. this._linkParameters();
  21817. };
  21818. PostProcessRenderEffect.prototype.getPass = function (passName) {
  21819. for (var renderPassName in this._renderPasses) {
  21820. if (renderPassName === passName) {
  21821. return this._renderPasses[passName];
  21822. }
  21823. }
  21824. };
  21825. PostProcessRenderEffect.prototype.emptyPasses = function () {
  21826. this._renderPasses = {};
  21827. this._linkParameters();
  21828. };
  21829. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  21830. var cameraKey;
  21831. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  21832. for (var i = 0; i < _cam.length; i++) {
  21833. var camera = _cam[i];
  21834. var cameraName = camera.name;
  21835. if (this._singleInstance) {
  21836. cameraKey = 0;
  21837. }
  21838. else {
  21839. cameraKey = cameraName;
  21840. }
  21841. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  21842. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  21843. if (!this._indicesForCamera[cameraName]) {
  21844. this._indicesForCamera[cameraName] = [];
  21845. }
  21846. this._indicesForCamera[cameraName].push(index);
  21847. if (this._cameras.indexOf(camera) === -1) {
  21848. this._cameras[cameraName] = camera;
  21849. }
  21850. for (var passName in this._renderPasses) {
  21851. this._renderPasses[passName]._incRefCount();
  21852. }
  21853. }
  21854. this._linkParameters();
  21855. };
  21856. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  21857. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  21858. for (var i = 0; i < _cam.length; i++) {
  21859. var camera = _cam[i];
  21860. var cameraName = camera.name;
  21861. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  21862. var index = this._cameras.indexOf(cameraName);
  21863. this._indicesForCamera.splice(index, 1);
  21864. this._cameras.splice(index, 1);
  21865. for (var passName in this._renderPasses) {
  21866. this._renderPasses[passName]._decRefCount();
  21867. }
  21868. }
  21869. };
  21870. PostProcessRenderEffect.prototype._enable = function (cameras) {
  21871. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  21872. for (var i = 0; i < _cam.length; i++) {
  21873. var camera = _cam[i];
  21874. var cameraName = camera.name;
  21875. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  21876. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  21877. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  21878. }
  21879. }
  21880. for (var passName in this._renderPasses) {
  21881. this._renderPasses[passName]._incRefCount();
  21882. }
  21883. }
  21884. };
  21885. PostProcessRenderEffect.prototype._disable = function (cameras) {
  21886. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  21887. for (var i = 0; i < _cam.length; i++) {
  21888. var camera = _cam[i];
  21889. var cameraName = camera.Name;
  21890. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  21891. for (var passName in this._renderPasses) {
  21892. this._renderPasses[passName]._decRefCount();
  21893. }
  21894. }
  21895. };
  21896. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  21897. if (this._singleInstance) {
  21898. return this._postProcesses[0];
  21899. }
  21900. else {
  21901. return this._postProcesses[camera.name];
  21902. }
  21903. };
  21904. PostProcessRenderEffect.prototype._linkParameters = function () {
  21905. var _this = this;
  21906. for (var index in this._postProcesses) {
  21907. if (this.applyParameters) {
  21908. this.applyParameters(this._postProcesses[index]);
  21909. }
  21910. this._postProcesses[index].onBeforeRender = function (effect) {
  21911. _this._linkTextures(effect);
  21912. };
  21913. }
  21914. };
  21915. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  21916. for (var renderPassName in this._renderPasses) {
  21917. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  21918. }
  21919. for (var renderEffectName in this._renderEffectAsPasses) {
  21920. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  21921. }
  21922. };
  21923. return PostProcessRenderEffect;
  21924. })();
  21925. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  21926. })(BABYLON || (BABYLON = {}));
  21927. //# sourceMappingURL=babylon.postProcessRenderEffect.js.mapvar BABYLON;
  21928. (function (BABYLON) {
  21929. var PostProcessRenderPipeline = (function () {
  21930. function PostProcessRenderPipeline(engine, name) {
  21931. this._engine = engine;
  21932. this._name = name;
  21933. this._renderEffects = {};
  21934. this._renderEffectsForIsolatedPass = {};
  21935. this._cameras = [];
  21936. }
  21937. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  21938. this._renderEffects[renderEffect._name] = renderEffect;
  21939. };
  21940. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  21941. var renderEffects = this._renderEffects[renderEffectName];
  21942. if (!renderEffects) {
  21943. return;
  21944. }
  21945. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  21946. };
  21947. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  21948. var renderEffects = this._renderEffects[renderEffectName];
  21949. if (!renderEffects) {
  21950. return;
  21951. }
  21952. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  21953. };
  21954. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  21955. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  21956. var indicesToDelete = [];
  21957. for (var i = 0; i < _cam.length; i++) {
  21958. var camera = _cam[i];
  21959. var cameraName = camera.name;
  21960. if (this._cameras.indexOf(camera) === -1) {
  21961. this._cameras[cameraName] = camera;
  21962. }
  21963. else if (unique) {
  21964. indicesToDelete.push(i);
  21965. }
  21966. }
  21967. for (var i = 0; i < indicesToDelete.length; i++) {
  21968. cameras.splice(indicesToDelete[i], 1);
  21969. }
  21970. for (var renderEffectName in this._renderEffects) {
  21971. this._renderEffects[renderEffectName]._attachCameras(_cam);
  21972. }
  21973. };
  21974. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  21975. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  21976. for (var renderEffectName in this._renderEffects) {
  21977. this._renderEffects[renderEffectName]._detachCameras(_cam);
  21978. }
  21979. for (var i = 0; i < _cam.length; i++) {
  21980. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  21981. }
  21982. };
  21983. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  21984. var _this = this;
  21985. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  21986. var pass = null;
  21987. for (var renderEffectName in this._renderEffects) {
  21988. pass = this._renderEffects[renderEffectName].getPass(passName);
  21989. if (pass != null) {
  21990. break;
  21991. }
  21992. }
  21993. if (pass === null) {
  21994. return;
  21995. }
  21996. for (var renderEffectName in this._renderEffects) {
  21997. this._renderEffects[renderEffectName]._disable(_cam);
  21998. }
  21999. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  22000. for (var i = 0; i < _cam.length; i++) {
  22001. var camera = _cam[i];
  22002. var cameraName = camera.name;
  22003. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  22004. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  22005. });
  22006. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  22007. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  22008. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  22009. }
  22010. };
  22011. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  22012. var _this = this;
  22013. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  22014. for (var i = 0; i < _cam.length; i++) {
  22015. var camera = _cam[i];
  22016. var cameraName = camera.name;
  22017. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  22018. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  22019. });
  22020. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  22021. }
  22022. for (var renderEffectName in this._renderEffects) {
  22023. this._renderEffects[renderEffectName]._enable(_cam);
  22024. }
  22025. };
  22026. PostProcessRenderPipeline.prototype._update = function () {
  22027. for (var renderEffectName in this._renderEffects) {
  22028. this._renderEffects[renderEffectName]._update();
  22029. }
  22030. for (var i = 0; i < this._cameras.length; i++) {
  22031. var cameraName = this._cameras[i].name;
  22032. if (this._renderEffectsForIsolatedPass[cameraName]) {
  22033. this._renderEffectsForIsolatedPass[cameraName]._update();
  22034. }
  22035. }
  22036. };
  22037. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  22038. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  22039. return PostProcessRenderPipeline;
  22040. })();
  22041. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  22042. })(BABYLON || (BABYLON = {}));
  22043. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.mapvar BABYLON;
  22044. (function (BABYLON) {
  22045. var PostProcessRenderPipelineManager = (function () {
  22046. function PostProcessRenderPipelineManager() {
  22047. this._renderPipelines = {};
  22048. }
  22049. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  22050. this._renderPipelines[renderPipeline._name] = renderPipeline;
  22051. };
  22052. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  22053. var renderPipeline = this._renderPipelines[renderPipelineName];
  22054. if (!renderPipeline) {
  22055. return;
  22056. }
  22057. renderPipeline._attachCameras(cameras, unique);
  22058. };
  22059. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  22060. var renderPipeline = this._renderPipelines[renderPipelineName];
  22061. if (!renderPipeline) {
  22062. return;
  22063. }
  22064. renderPipeline._detachCameras(cameras);
  22065. };
  22066. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  22067. var renderPipeline = this._renderPipelines[renderPipelineName];
  22068. if (!renderPipeline) {
  22069. return;
  22070. }
  22071. renderPipeline._enableEffect(renderEffectName, cameras);
  22072. };
  22073. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  22074. var renderPipeline = this._renderPipelines[renderPipelineName];
  22075. if (!renderPipeline) {
  22076. return;
  22077. }
  22078. renderPipeline._disableEffect(renderEffectName, cameras);
  22079. };
  22080. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  22081. var renderPipeline = this._renderPipelines[renderPipelineName];
  22082. if (!renderPipeline) {
  22083. return;
  22084. }
  22085. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  22086. };
  22087. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  22088. var renderPipeline = this._renderPipelines[renderPipelineName];
  22089. if (!renderPipeline) {
  22090. return;
  22091. }
  22092. renderPipeline._disableDisplayOnlyPass(cameras);
  22093. };
  22094. PostProcessRenderPipelineManager.prototype.update = function () {
  22095. for (var renderPipelineName in this._renderPipelines) {
  22096. this._renderPipelines[renderPipelineName]._update();
  22097. }
  22098. };
  22099. return PostProcessRenderPipelineManager;
  22100. })();
  22101. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  22102. })(BABYLON || (BABYLON = {}));
  22103. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  22104. var BABYLON;
  22105. (function (BABYLON) {
  22106. var DisplayPassPostProcess = (function (_super) {
  22107. __extends(DisplayPassPostProcess, _super);
  22108. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  22109. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  22110. }
  22111. return DisplayPassPostProcess;
  22112. })(BABYLON.PostProcess);
  22113. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  22114. })(BABYLON || (BABYLON = {}));
  22115. //# sourceMappingURL=babylon.displayPassPostProcess.js.mapvar BABYLON;
  22116. (function (BABYLON) {
  22117. var BoundingBoxRenderer = (function () {
  22118. function BoundingBoxRenderer(scene) {
  22119. this.frontColor = new BABYLON.Color3(1, 1, 1);
  22120. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  22121. this.showBackLines = true;
  22122. this.renderList = new BABYLON.SmartArray(32);
  22123. this._scene = scene;
  22124. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  22125. attributes: ["position"],
  22126. uniforms: ["worldViewProjection", "color"]
  22127. });
  22128. var engine = this._scene.getEngine();
  22129. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  22130. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  22131. this._ib = engine.createIndexBuffer([0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 7, 1, 6, 2, 5, 3, 4]);
  22132. }
  22133. BoundingBoxRenderer.prototype.reset = function () {
  22134. this.renderList.reset();
  22135. };
  22136. BoundingBoxRenderer.prototype.render = function () {
  22137. if (this.renderList.length === 0 || !this._colorShader.isReady()) {
  22138. return;
  22139. }
  22140. var engine = this._scene.getEngine();
  22141. engine.setDepthWrite(false);
  22142. this._colorShader._preBind();
  22143. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  22144. var boundingBox = this.renderList.data[boundingBoxIndex];
  22145. var min = boundingBox.minimum;
  22146. var max = boundingBox.maximum;
  22147. var diff = max.subtract(min);
  22148. var median = min.add(diff.scale(0.5));
  22149. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z).multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z)).multiply(boundingBox.getWorldMatrix());
  22150. // VBOs
  22151. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  22152. if (this.showBackLines) {
  22153. // Back
  22154. engine.setDepthFunctionToGreaterOrEqual();
  22155. this._scene.resetCachedMaterial();
  22156. this._colorShader.setColor4("color", this.backColor.toColor4());
  22157. this._colorShader.bind(worldMatrix);
  22158. // Draw order
  22159. engine.draw(false, 0, 24);
  22160. }
  22161. // Front
  22162. engine.setDepthFunctionToLess();
  22163. this._scene.resetCachedMaterial();
  22164. this._colorShader.setColor4("color", this.frontColor.toColor4());
  22165. this._colorShader.bind(worldMatrix);
  22166. // Draw order
  22167. engine.draw(false, 0, 24);
  22168. }
  22169. this._colorShader.unbind();
  22170. engine.setDepthFunctionToLessOrEqual();
  22171. engine.setDepthWrite(true);
  22172. };
  22173. BoundingBoxRenderer.prototype.dispose = function () {
  22174. this._colorShader.dispose();
  22175. this._vb.dispose();
  22176. this._scene.getEngine()._releaseBuffer(this._ib);
  22177. };
  22178. return BoundingBoxRenderer;
  22179. })();
  22180. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  22181. })(BABYLON || (BABYLON = {}));
  22182. //# sourceMappingURL=babylon.boundingBoxRenderer.js.mapvar BABYLON;
  22183. (function (BABYLON) {
  22184. var Internals;
  22185. (function (Internals) {
  22186. /*
  22187. * Based on jsTGALoader - Javascript loader for TGA file
  22188. * By Vincent Thibault
  22189. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  22190. */
  22191. var TGATools = (function () {
  22192. function TGATools() {
  22193. }
  22194. TGATools.GetTGAHeader = function (data) {
  22195. var offset = 0;
  22196. var header = {
  22197. id_length: data[offset++],
  22198. colormap_type: data[offset++],
  22199. image_type: data[offset++],
  22200. colormap_index: data[offset++] | data[offset++] << 8,
  22201. colormap_length: data[offset++] | data[offset++] << 8,
  22202. colormap_size: data[offset++],
  22203. origin: [
  22204. data[offset++] | data[offset++] << 8,
  22205. data[offset++] | data[offset++] << 8
  22206. ],
  22207. width: data[offset++] | data[offset++] << 8,
  22208. height: data[offset++] | data[offset++] << 8,
  22209. pixel_size: data[offset++],
  22210. flags: data[offset++]
  22211. };
  22212. return header;
  22213. };
  22214. TGATools.UploadContent = function (gl, data) {
  22215. // Not enough data to contain header ?
  22216. if (data.length < 19) {
  22217. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  22218. return;
  22219. }
  22220. // Read Header
  22221. var offset = 18;
  22222. var header = TGATools.GetTGAHeader(data);
  22223. // Assume it's a valid Targa file.
  22224. if (header.id_length + offset > data.length) {
  22225. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  22226. return;
  22227. }
  22228. // Skip not needed data
  22229. offset += header.id_length;
  22230. var use_rle = false;
  22231. var use_pal = false;
  22232. var use_rgb = false;
  22233. var use_grey = false;
  22234. switch (header.image_type) {
  22235. case TGATools._TYPE_RLE_INDEXED:
  22236. use_rle = true;
  22237. case TGATools._TYPE_INDEXED:
  22238. use_pal = true;
  22239. break;
  22240. case TGATools._TYPE_RLE_RGB:
  22241. use_rle = true;
  22242. case TGATools._TYPE_RGB:
  22243. use_rgb = true;
  22244. break;
  22245. case TGATools._TYPE_RLE_GREY:
  22246. use_rle = true;
  22247. case TGATools._TYPE_GREY:
  22248. use_grey = true;
  22249. break;
  22250. }
  22251. var pixel_data;
  22252. var numAlphaBits = header.flags & 0xf;
  22253. var pixel_size = header.pixel_size >> 3;
  22254. var pixel_total = header.width * header.height * pixel_size;
  22255. // Read palettes
  22256. var palettes;
  22257. if (use_pal) {
  22258. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  22259. }
  22260. // Read LRE
  22261. if (use_rle) {
  22262. pixel_data = new Uint8Array(pixel_total);
  22263. var c, count, i;
  22264. var localOffset = 0;
  22265. var pixels = new Uint8Array(pixel_size);
  22266. while (offset < pixel_total && localOffset < pixel_total) {
  22267. c = data[offset++];
  22268. count = (c & 0x7f) + 1;
  22269. // RLE pixels
  22270. if (c & 0x80) {
  22271. for (i = 0; i < pixel_size; ++i) {
  22272. pixels[i] = data[offset++];
  22273. }
  22274. for (i = 0; i < count; ++i) {
  22275. pixel_data.set(pixels, localOffset + i * pixel_size);
  22276. }
  22277. localOffset += pixel_size * count;
  22278. }
  22279. else {
  22280. count *= pixel_size;
  22281. for (i = 0; i < count; ++i) {
  22282. pixel_data[localOffset + i] = data[offset++];
  22283. }
  22284. localOffset += count;
  22285. }
  22286. }
  22287. }
  22288. else {
  22289. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  22290. }
  22291. // Load to texture
  22292. var x_start, y_start, x_step, y_step, y_end, x_end;
  22293. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  22294. default:
  22295. case TGATools._ORIGIN_UL:
  22296. x_start = 0;
  22297. x_step = 1;
  22298. x_end = header.width;
  22299. y_start = 0;
  22300. y_step = 1;
  22301. y_end = header.height;
  22302. break;
  22303. case TGATools._ORIGIN_BL:
  22304. x_start = 0;
  22305. x_step = 1;
  22306. x_end = header.width;
  22307. y_start = header.height - 1;
  22308. y_step = -1;
  22309. y_end = -1;
  22310. break;
  22311. case TGATools._ORIGIN_UR:
  22312. x_start = header.width - 1;
  22313. x_step = -1;
  22314. x_end = -1;
  22315. y_start = 0;
  22316. y_step = 1;
  22317. y_end = header.height;
  22318. break;
  22319. case TGATools._ORIGIN_BR:
  22320. x_start = header.width - 1;
  22321. x_step = -1;
  22322. x_end = -1;
  22323. y_start = header.height - 1;
  22324. y_step = -1;
  22325. y_end = -1;
  22326. break;
  22327. }
  22328. // Load the specify method
  22329. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  22330. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  22331. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  22332. };
  22333. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  22334. var image = pixel_data, colormap = palettes;
  22335. var width = header.width, height = header.height;
  22336. var color, i = 0, x, y;
  22337. var imageData = new Uint8Array(width * height * 4);
  22338. for (y = y_start; y !== y_end; y += y_step) {
  22339. for (x = x_start; x !== x_end; x += x_step, i++) {
  22340. color = image[i];
  22341. imageData[(x + width * y) * 4 + 3] = 255;
  22342. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  22343. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  22344. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  22345. }
  22346. }
  22347. return imageData;
  22348. };
  22349. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  22350. var image = pixel_data;
  22351. var width = header.width, height = header.height;
  22352. var color, i = 0, x, y;
  22353. var imageData = new Uint8Array(width * height * 4);
  22354. for (y = y_start; y !== y_end; y += y_step) {
  22355. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  22356. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  22357. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  22358. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  22359. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  22360. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  22361. }
  22362. }
  22363. return imageData;
  22364. };
  22365. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  22366. var image = pixel_data;
  22367. var width = header.width, height = header.height;
  22368. var i = 0, x, y;
  22369. var imageData = new Uint8Array(width * height * 4);
  22370. for (y = y_start; y !== y_end; y += y_step) {
  22371. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  22372. imageData[(x + width * y) * 4 + 3] = 255;
  22373. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  22374. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  22375. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  22376. }
  22377. }
  22378. return imageData;
  22379. };
  22380. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  22381. var image = pixel_data;
  22382. var width = header.width, height = header.height;
  22383. var i = 0, x, y;
  22384. var imageData = new Uint8Array(width * height * 4);
  22385. for (y = y_start; y !== y_end; y += y_step) {
  22386. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  22387. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  22388. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  22389. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  22390. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  22391. }
  22392. }
  22393. return imageData;
  22394. };
  22395. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  22396. var image = pixel_data;
  22397. var width = header.width, height = header.height;
  22398. var color, i = 0, x, y;
  22399. var imageData = new Uint8Array(width * height * 4);
  22400. for (y = y_start; y !== y_end; y += y_step) {
  22401. for (x = x_start; x !== x_end; x += x_step, i++) {
  22402. color = image[i];
  22403. imageData[(x + width * y) * 4 + 0] = color;
  22404. imageData[(x + width * y) * 4 + 1] = color;
  22405. imageData[(x + width * y) * 4 + 2] = color;
  22406. imageData[(x + width * y) * 4 + 3] = 255;
  22407. }
  22408. }
  22409. return imageData;
  22410. };
  22411. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  22412. var image = pixel_data;
  22413. var width = header.width, height = header.height;
  22414. var i = 0, x, y;
  22415. var imageData = new Uint8Array(width * height * 4);
  22416. for (y = y_start; y !== y_end; y += y_step) {
  22417. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  22418. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  22419. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  22420. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  22421. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  22422. }
  22423. }
  22424. return imageData;
  22425. };
  22426. TGATools._TYPE_NO_DATA = 0;
  22427. TGATools._TYPE_INDEXED = 1;
  22428. TGATools._TYPE_RGB = 2;
  22429. TGATools._TYPE_GREY = 3;
  22430. TGATools._TYPE_RLE_INDEXED = 9;
  22431. TGATools._TYPE_RLE_RGB = 10;
  22432. TGATools._TYPE_RLE_GREY = 11;
  22433. TGATools._ORIGIN_MASK = 0x30;
  22434. TGATools._ORIGIN_SHIFT = 0x04;
  22435. TGATools._ORIGIN_BL = 0x00;
  22436. TGATools._ORIGIN_BR = 0x01;
  22437. TGATools._ORIGIN_UL = 0x02;
  22438. TGATools._ORIGIN_UR = 0x03;
  22439. return TGATools;
  22440. })();
  22441. Internals.TGATools = TGATools;
  22442. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  22443. })(BABYLON || (BABYLON = {}));
  22444. //# sourceMappingURL=babylon.tools.tga.js.mapvar BABYLON;
  22445. (function (BABYLON) {
  22446. var Internals;
  22447. (function (Internals) {
  22448. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  22449. // All values and structures referenced from:
  22450. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  22451. var DDS_MAGIC = 0x20534444;
  22452. var DDSD_CAPS = 0x1, DDSD_HEIGHT = 0x2, DDSD_WIDTH = 0x4, DDSD_PITCH = 0x8, DDSD_PIXELFORMAT = 0x1000, DDSD_MIPMAPCOUNT = 0x20000, DDSD_LINEARSIZE = 0x80000, DDSD_DEPTH = 0x800000;
  22453. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  22454. var DDSCAPS2_CUBEMAP = 0x200, DDSCAPS2_CUBEMAP_POSITIVEX = 0x400, DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800, DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000, DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000, DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000, DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000, DDSCAPS2_VOLUME = 0x200000;
  22455. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  22456. function FourCCToInt32(value) {
  22457. return value.charCodeAt(0) + (value.charCodeAt(1) << 8) + (value.charCodeAt(2) << 16) + (value.charCodeAt(3) << 24);
  22458. }
  22459. function Int32ToFourCC(value) {
  22460. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  22461. }
  22462. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  22463. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  22464. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  22465. var headerLengthInt = 31; // The header length in 32 bit ints
  22466. // Offsets into the header array
  22467. var off_magic = 0;
  22468. var off_size = 1;
  22469. var off_flags = 2;
  22470. var off_height = 3;
  22471. var off_width = 4;
  22472. var off_mipmapCount = 7;
  22473. var off_pfFlags = 20;
  22474. var off_pfFourCC = 21;
  22475. var off_RGBbpp = 22;
  22476. var off_RMask = 23;
  22477. var off_GMask = 24;
  22478. var off_BMask = 25;
  22479. var off_AMask = 26;
  22480. var off_caps1 = 27;
  22481. var off_caps2 = 28;
  22482. ;
  22483. var DDSTools = (function () {
  22484. function DDSTools() {
  22485. }
  22486. DDSTools.GetDDSInfo = function (arrayBuffer) {
  22487. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  22488. var mipmapCount = 1;
  22489. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  22490. mipmapCount = Math.max(1, header[off_mipmapCount]);
  22491. }
  22492. return {
  22493. width: header[off_width],
  22494. height: header[off_height],
  22495. mipmapCount: mipmapCount,
  22496. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  22497. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  22498. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  22499. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  22500. };
  22501. };
  22502. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  22503. var byteArray = new Uint8Array(dataLength);
  22504. var srcData = new Uint8Array(arrayBuffer);
  22505. var index = 0;
  22506. for (var y = height - 1; y >= 0; y--) {
  22507. for (var x = 0; x < width; x++) {
  22508. var srcPos = dataOffset + (x + y * width) * 4;
  22509. byteArray[index + 2] = srcData[srcPos];
  22510. byteArray[index + 1] = srcData[srcPos + 1];
  22511. byteArray[index] = srcData[srcPos + 2];
  22512. byteArray[index + 3] = srcData[srcPos + 3];
  22513. index += 4;
  22514. }
  22515. }
  22516. return byteArray;
  22517. };
  22518. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  22519. var byteArray = new Uint8Array(dataLength);
  22520. var srcData = new Uint8Array(arrayBuffer);
  22521. var index = 0;
  22522. for (var y = height - 1; y >= 0; y--) {
  22523. for (var x = 0; x < width; x++) {
  22524. var srcPos = dataOffset + (x + y * width) * 3;
  22525. byteArray[index + 2] = srcData[srcPos];
  22526. byteArray[index + 1] = srcData[srcPos + 1];
  22527. byteArray[index] = srcData[srcPos + 2];
  22528. index += 3;
  22529. }
  22530. }
  22531. return byteArray;
  22532. };
  22533. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  22534. var byteArray = new Uint8Array(dataLength);
  22535. var srcData = new Uint8Array(arrayBuffer);
  22536. var index = 0;
  22537. for (var y = height - 1; y >= 0; y--) {
  22538. for (var x = 0; x < width; x++) {
  22539. var srcPos = dataOffset + (x + y * width);
  22540. byteArray[index] = srcData[srcPos];
  22541. index++;
  22542. }
  22543. }
  22544. return byteArray;
  22545. };
  22546. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  22547. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  22548. if (header[off_magic] != DDS_MAGIC) {
  22549. BABYLON.Tools.Error("Invalid magic number in DDS header");
  22550. return;
  22551. }
  22552. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  22553. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  22554. return;
  22555. }
  22556. if (info.isFourCC) {
  22557. fourCC = header[off_pfFourCC];
  22558. switch (fourCC) {
  22559. case FOURCC_DXT1:
  22560. blockBytes = 8;
  22561. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  22562. break;
  22563. case FOURCC_DXT3:
  22564. blockBytes = 16;
  22565. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  22566. break;
  22567. case FOURCC_DXT5:
  22568. blockBytes = 16;
  22569. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  22570. break;
  22571. default:
  22572. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  22573. return;
  22574. }
  22575. }
  22576. mipmapCount = 1;
  22577. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  22578. mipmapCount = Math.max(1, header[off_mipmapCount]);
  22579. }
  22580. var bpp = header[off_RGBbpp];
  22581. for (var face = 0; face < faces; face++) {
  22582. var sampler = faces == 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  22583. width = header[off_width];
  22584. height = header[off_height];
  22585. dataOffset = header[off_size] + 4;
  22586. for (i = 0; i < mipmapCount; ++i) {
  22587. if (info.isRGB) {
  22588. if (bpp == 24) {
  22589. dataLength = width * height * 3;
  22590. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  22591. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  22592. }
  22593. else {
  22594. dataLength = width * height * 4;
  22595. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  22596. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  22597. }
  22598. }
  22599. else if (info.isLuminance) {
  22600. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  22601. var unpaddedRowSize = width;
  22602. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  22603. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  22604. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  22605. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  22606. }
  22607. else {
  22608. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  22609. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  22610. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  22611. }
  22612. dataOffset += dataLength;
  22613. width *= 0.5;
  22614. height *= 0.5;
  22615. width = Math.max(1.0, width);
  22616. height = Math.max(1.0, height);
  22617. }
  22618. }
  22619. };
  22620. return DDSTools;
  22621. })();
  22622. Internals.DDSTools = DDSTools;
  22623. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  22624. })(BABYLON || (BABYLON = {}));
  22625. //# sourceMappingURL=babylon.tools.dds.js.mapvar BABYLON;
  22626. (function (BABYLON) {
  22627. var SmartArray = (function () {
  22628. function SmartArray(capacity) {
  22629. this.length = 0;
  22630. this._duplicateId = 0;
  22631. this.data = new Array(capacity);
  22632. this._id = SmartArray._GlobalId++;
  22633. }
  22634. SmartArray.prototype.push = function (value) {
  22635. this.data[this.length++] = value;
  22636. if (this.length > this.data.length) {
  22637. this.data.length *= 2;
  22638. }
  22639. if (!value.__smartArrayFlags) {
  22640. value.__smartArrayFlags = {};
  22641. }
  22642. value.__smartArrayFlags[this._id] = this._duplicateId;
  22643. };
  22644. SmartArray.prototype.pushNoDuplicate = function (value) {
  22645. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  22646. return;
  22647. }
  22648. this.push(value);
  22649. };
  22650. SmartArray.prototype.sort = function (compareFn) {
  22651. this.data.sort(compareFn);
  22652. };
  22653. SmartArray.prototype.reset = function () {
  22654. this.length = 0;
  22655. this._duplicateId++;
  22656. };
  22657. SmartArray.prototype.concat = function (array) {
  22658. if (array.length === 0) {
  22659. return;
  22660. }
  22661. if (this.length + array.length > this.data.length) {
  22662. this.data.length = (this.length + array.length) * 2;
  22663. }
  22664. for (var index = 0; index < array.length; index++) {
  22665. this.data[this.length++] = (array.data || array)[index];
  22666. }
  22667. };
  22668. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  22669. if (array.length === 0) {
  22670. return;
  22671. }
  22672. if (this.length + array.length > this.data.length) {
  22673. this.data.length = (this.length + array.length) * 2;
  22674. }
  22675. for (var index = 0; index < array.length; index++) {
  22676. var item = (array.data || array)[index];
  22677. this.pushNoDuplicate(item);
  22678. }
  22679. };
  22680. SmartArray.prototype.indexOf = function (value) {
  22681. var position = this.data.indexOf(value);
  22682. if (position >= this.length) {
  22683. return -1;
  22684. }
  22685. return position;
  22686. };
  22687. // Statics
  22688. SmartArray._GlobalId = 0;
  22689. return SmartArray;
  22690. })();
  22691. BABYLON.SmartArray = SmartArray;
  22692. })(BABYLON || (BABYLON = {}));
  22693. //# sourceMappingURL=babylon.smartArray.js.mapvar BABYLON;
  22694. (function (BABYLON) {
  22695. var CannonJSPlugin = (function () {
  22696. function CannonJSPlugin() {
  22697. this._registeredMeshes = [];
  22698. this._physicsMaterials = [];
  22699. this.updateBodyPosition = function (mesh) {
  22700. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22701. var registeredMesh = this._registeredMeshes[index];
  22702. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  22703. var body = registeredMesh.body;
  22704. var center = mesh.getBoundingInfo().boundingBox.center;
  22705. body.position.set(center.x, center.z, center.y);
  22706. body.quaternion.x = mesh.rotationQuaternion.x;
  22707. body.quaternion.z = mesh.rotationQuaternion.y;
  22708. body.quaternion.y = mesh.rotationQuaternion.z;
  22709. body.quaternion.w = -mesh.rotationQuaternion.w;
  22710. return;
  22711. }
  22712. }
  22713. };
  22714. }
  22715. CannonJSPlugin.prototype.initialize = function (iterations) {
  22716. if (iterations === void 0) { iterations = 10; }
  22717. this._world = new CANNON.World();
  22718. this._world.broadphase = new CANNON.NaiveBroadphase();
  22719. this._world.solver.iterations = iterations;
  22720. };
  22721. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  22722. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  22723. };
  22724. CannonJSPlugin.prototype.runOneStep = function (delta) {
  22725. this._world.step(delta);
  22726. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22727. var registeredMesh = this._registeredMeshes[index];
  22728. if (registeredMesh.isChild) {
  22729. continue;
  22730. }
  22731. // Body position
  22732. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  22733. var deltaPos = registeredMesh.delta;
  22734. if (deltaPos) {
  22735. registeredMesh.mesh.position.x = bodyX + deltaPos.x;
  22736. registeredMesh.mesh.position.y = bodyZ + deltaPos.y;
  22737. registeredMesh.mesh.position.z = bodyY + deltaPos.z;
  22738. }
  22739. else {
  22740. registeredMesh.mesh.position.x = bodyX;
  22741. registeredMesh.mesh.position.y = bodyZ;
  22742. registeredMesh.mesh.position.z = bodyY;
  22743. }
  22744. if (!registeredMesh.mesh.rotationQuaternion) {
  22745. registeredMesh.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  22746. }
  22747. registeredMesh.mesh.rotationQuaternion.x = registeredMesh.body.quaternion.x;
  22748. registeredMesh.mesh.rotationQuaternion.y = registeredMesh.body.quaternion.z;
  22749. registeredMesh.mesh.rotationQuaternion.z = registeredMesh.body.quaternion.y;
  22750. registeredMesh.mesh.rotationQuaternion.w = -registeredMesh.body.quaternion.w;
  22751. }
  22752. };
  22753. CannonJSPlugin.prototype.setGravity = function (gravity) {
  22754. this._world.gravity.set(gravity.x, gravity.z, gravity.y);
  22755. };
  22756. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  22757. this.unregisterMesh(mesh);
  22758. mesh.computeWorldMatrix(true);
  22759. switch (impostor) {
  22760. case BABYLON.PhysicsEngine.SphereImpostor:
  22761. var bbox = mesh.getBoundingInfo().boundingBox;
  22762. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  22763. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  22764. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  22765. return this._createSphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2, mesh, options);
  22766. case BABYLON.PhysicsEngine.BoxImpostor:
  22767. bbox = mesh.getBoundingInfo().boundingBox;
  22768. var min = bbox.minimumWorld;
  22769. var max = bbox.maximumWorld;
  22770. var box = max.subtract(min).scale(0.5);
  22771. return this._createBox(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z), mesh, options);
  22772. case BABYLON.PhysicsEngine.PlaneImpostor:
  22773. return this._createPlane(mesh, options);
  22774. case BABYLON.PhysicsEngine.MeshImpostor:
  22775. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22776. var rawFaces = mesh.getIndices();
  22777. return this._createConvexPolyhedron(rawVerts, rawFaces, mesh, options);
  22778. }
  22779. return null;
  22780. };
  22781. CannonJSPlugin.prototype._createSphere = function (radius, mesh, options) {
  22782. var shape = new CANNON.Sphere(radius);
  22783. if (!options) {
  22784. return shape;
  22785. }
  22786. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  22787. };
  22788. CannonJSPlugin.prototype._createBox = function (x, y, z, mesh, options) {
  22789. var shape = new CANNON.Box(new CANNON.Vec3(x, z, y));
  22790. if (!options) {
  22791. return shape;
  22792. }
  22793. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  22794. };
  22795. CannonJSPlugin.prototype._createPlane = function (mesh, options) {
  22796. var shape = new CANNON.Plane();
  22797. if (!options) {
  22798. return shape;
  22799. }
  22800. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  22801. };
  22802. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh, options) {
  22803. var verts = [], faces = [];
  22804. mesh.computeWorldMatrix(true);
  22805. for (var i = 0; i < rawVerts.length; i += 3) {
  22806. var transformed = BABYLON.Vector3.Zero();
  22807. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  22808. verts.push(new CANNON.Vec3(transformed.x, transformed.z, transformed.y));
  22809. }
  22810. for (var j = 0; j < rawFaces.length; j += 3) {
  22811. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  22812. }
  22813. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  22814. if (!options) {
  22815. return shape;
  22816. }
  22817. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  22818. };
  22819. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  22820. var index;
  22821. var mat;
  22822. for (index = 0; index < this._physicsMaterials.length; index++) {
  22823. mat = this._physicsMaterials[index];
  22824. if (mat.friction === friction && mat.restitution === restitution) {
  22825. return mat;
  22826. }
  22827. }
  22828. var currentMat = new CANNON.Material();
  22829. currentMat.friction = friction;
  22830. currentMat.restitution = restitution;
  22831. this._physicsMaterials.push(currentMat);
  22832. for (index = 0; index < this._physicsMaterials.length; index++) {
  22833. mat = this._physicsMaterials[index];
  22834. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, mat.friction * currentMat.friction, mat.restitution * currentMat.restitution);
  22835. contactMaterial.contactEquationStiffness = 1e10;
  22836. contactMaterial.contactEquationRegularizationTime = 10;
  22837. this._world.addContactMaterial(contactMaterial);
  22838. }
  22839. return currentMat;
  22840. };
  22841. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, mass, friction, restitution) {
  22842. var initialRotation = null;
  22843. if (mesh.rotationQuaternion) {
  22844. initialRotation = mesh.rotationQuaternion.clone();
  22845. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  22846. }
  22847. // The delta between the mesh position and the mesh bounding box center
  22848. var bbox = mesh.getBoundingInfo().boundingBox;
  22849. var deltaPosition = mesh.position.subtract(bbox.center);
  22850. var material = this._addMaterial(friction, restitution);
  22851. var body = new CANNON.RigidBody(mass, shape, material);
  22852. if (initialRotation) {
  22853. body.quaternion.x = initialRotation.x;
  22854. body.quaternion.z = initialRotation.y;
  22855. body.quaternion.y = initialRotation.z;
  22856. body.quaternion.w = -initialRotation.w;
  22857. }
  22858. body.position.set(bbox.center.x, bbox.center.z, bbox.center.y);
  22859. this._world.add(body);
  22860. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition });
  22861. return body;
  22862. };
  22863. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  22864. var compoundShape = new CANNON.Compound();
  22865. for (var index = 0; index < parts.length; index++) {
  22866. var mesh = parts[index].mesh;
  22867. var shape = this.registerMesh(mesh, parts[index].impostor);
  22868. if (index == 0) {
  22869. compoundShape.addChild(shape, new CANNON.Vec3(0, 0, 0));
  22870. }
  22871. else {
  22872. compoundShape.addChild(shape, new CANNON.Vec3(mesh.position.x, mesh.position.z, mesh.position.y));
  22873. }
  22874. }
  22875. var initialMesh = parts[0].mesh;
  22876. var body = this._createRigidBodyFromShape(compoundShape, initialMesh, options.mass, options.friction, options.restitution);
  22877. body.parts = parts;
  22878. return body;
  22879. };
  22880. CannonJSPlugin.prototype._unbindBody = function (body) {
  22881. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22882. var registeredMesh = this._registeredMeshes[index];
  22883. if (registeredMesh.body === body) {
  22884. registeredMesh.body = null;
  22885. registeredMesh.delta = 0;
  22886. }
  22887. }
  22888. };
  22889. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  22890. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22891. var registeredMesh = this._registeredMeshes[index];
  22892. if (registeredMesh.mesh === mesh) {
  22893. // Remove body
  22894. if (registeredMesh.body) {
  22895. this._world.remove(registeredMesh.body);
  22896. this._unbindBody(registeredMesh.body);
  22897. }
  22898. this._registeredMeshes.splice(index, 1);
  22899. return;
  22900. }
  22901. }
  22902. };
  22903. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  22904. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.z, contactPoint.y);
  22905. var impulse = new CANNON.Vec3(force.x, force.z, force.y);
  22906. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22907. var registeredMesh = this._registeredMeshes[index];
  22908. if (registeredMesh.mesh === mesh) {
  22909. registeredMesh.body.applyImpulse(impulse, worldPoint);
  22910. return;
  22911. }
  22912. }
  22913. };
  22914. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  22915. var body1 = null, body2 = null;
  22916. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22917. var registeredMesh = this._registeredMeshes[index];
  22918. if (registeredMesh.mesh === mesh1) {
  22919. body1 = registeredMesh.body;
  22920. }
  22921. else if (registeredMesh.mesh === mesh2) {
  22922. body2 = registeredMesh.body;
  22923. }
  22924. }
  22925. if (!body1 || !body2) {
  22926. return false;
  22927. }
  22928. var constraint = new CANNON.PointToPointConstraint(body1, new CANNON.Vec3(pivot1.x, pivot1.z, pivot1.y), body2, new CANNON.Vec3(pivot2.x, pivot2.z, pivot2.y));
  22929. this._world.addConstraint(constraint);
  22930. return true;
  22931. };
  22932. CannonJSPlugin.prototype.dispose = function () {
  22933. while (this._registeredMeshes.length) {
  22934. this.unregisterMesh(this._registeredMeshes[0].mesh);
  22935. }
  22936. };
  22937. CannonJSPlugin.prototype.isSupported = function () {
  22938. return window.CANNON !== undefined;
  22939. };
  22940. return CannonJSPlugin;
  22941. })();
  22942. BABYLON.CannonJSPlugin = CannonJSPlugin;
  22943. })(BABYLON || (BABYLON = {}));
  22944. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  22945. var BABYLON;
  22946. (function (BABYLON) {
  22947. var Condition = (function () {
  22948. function Condition(actionManager) {
  22949. this._actionManager = actionManager;
  22950. }
  22951. Condition.prototype.isValid = function () {
  22952. return true;
  22953. };
  22954. Condition.prototype._getProperty = function (propertyPath) {
  22955. return this._actionManager._getProperty(propertyPath);
  22956. };
  22957. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  22958. return this._actionManager._getEffectiveTarget(target, propertyPath);
  22959. };
  22960. return Condition;
  22961. })();
  22962. BABYLON.Condition = Condition;
  22963. var ValueCondition = (function (_super) {
  22964. __extends(ValueCondition, _super);
  22965. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  22966. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  22967. _super.call(this, actionManager);
  22968. this.propertyPath = propertyPath;
  22969. this.value = value;
  22970. this.operator = operator;
  22971. this._target = this._getEffectiveTarget(target, this.propertyPath);
  22972. this._property = this._getProperty(this.propertyPath);
  22973. }
  22974. Object.defineProperty(ValueCondition, "IsEqual", {
  22975. get: function () {
  22976. return ValueCondition._IsEqual;
  22977. },
  22978. enumerable: true,
  22979. configurable: true
  22980. });
  22981. Object.defineProperty(ValueCondition, "IsDifferent", {
  22982. get: function () {
  22983. return ValueCondition._IsDifferent;
  22984. },
  22985. enumerable: true,
  22986. configurable: true
  22987. });
  22988. Object.defineProperty(ValueCondition, "IsGreater", {
  22989. get: function () {
  22990. return ValueCondition._IsGreater;
  22991. },
  22992. enumerable: true,
  22993. configurable: true
  22994. });
  22995. Object.defineProperty(ValueCondition, "IsLesser", {
  22996. get: function () {
  22997. return ValueCondition._IsLesser;
  22998. },
  22999. enumerable: true,
  23000. configurable: true
  23001. });
  23002. // Methods
  23003. ValueCondition.prototype.isValid = function () {
  23004. switch (this.operator) {
  23005. case ValueCondition.IsGreater:
  23006. return this._target[this._property] > this.value;
  23007. case ValueCondition.IsLesser:
  23008. return this._target[this._property] < this.value;
  23009. case ValueCondition.IsEqual:
  23010. case ValueCondition.IsDifferent:
  23011. var check;
  23012. if (this.value.equals) {
  23013. check = this.value.equals(this._target[this._property]);
  23014. }
  23015. else {
  23016. check = this.value === this._target[this._property];
  23017. }
  23018. return this.operator === ValueCondition.IsEqual ? check : !check;
  23019. }
  23020. return false;
  23021. };
  23022. // Statics
  23023. ValueCondition._IsEqual = 0;
  23024. ValueCondition._IsDifferent = 1;
  23025. ValueCondition._IsGreater = 2;
  23026. ValueCondition._IsLesser = 3;
  23027. return ValueCondition;
  23028. })(Condition);
  23029. BABYLON.ValueCondition = ValueCondition;
  23030. var PredicateCondition = (function (_super) {
  23031. __extends(PredicateCondition, _super);
  23032. function PredicateCondition(actionManager, predicate) {
  23033. _super.call(this, actionManager);
  23034. this.predicate = predicate;
  23035. }
  23036. PredicateCondition.prototype.isValid = function () {
  23037. return this.predicate();
  23038. };
  23039. return PredicateCondition;
  23040. })(Condition);
  23041. BABYLON.PredicateCondition = PredicateCondition;
  23042. var StateCondition = (function (_super) {
  23043. __extends(StateCondition, _super);
  23044. function StateCondition(actionManager, target, value) {
  23045. _super.call(this, actionManager);
  23046. this.value = value;
  23047. this._target = target;
  23048. }
  23049. // Methods
  23050. StateCondition.prototype.isValid = function () {
  23051. return this._target.state === this.value;
  23052. };
  23053. return StateCondition;
  23054. })(Condition);
  23055. BABYLON.StateCondition = StateCondition;
  23056. })(BABYLON || (BABYLON = {}));
  23057. //# sourceMappingURL=babylon.condition.js.mapvar BABYLON;
  23058. (function (BABYLON) {
  23059. var Action = (function () {
  23060. function Action(triggerOptions, condition) {
  23061. this.triggerOptions = triggerOptions;
  23062. if (triggerOptions.parameter) {
  23063. this.trigger = triggerOptions.trigger;
  23064. this._triggerParameter = triggerOptions.parameter;
  23065. }
  23066. else {
  23067. this.trigger = triggerOptions;
  23068. }
  23069. this._nextActiveAction = this;
  23070. this._condition = condition;
  23071. }
  23072. // Methods
  23073. Action.prototype._prepare = function () {
  23074. };
  23075. Action.prototype.getTriggerParameter = function () {
  23076. return this._triggerParameter;
  23077. };
  23078. Action.prototype._executeCurrent = function (evt) {
  23079. if (this._condition) {
  23080. var currentRenderId = this._actionManager.getScene().getRenderId();
  23081. // We cache the current evaluation for the current frame
  23082. if (this._condition._evaluationId === currentRenderId) {
  23083. if (!this._condition._currentResult) {
  23084. return;
  23085. }
  23086. }
  23087. else {
  23088. this._condition._evaluationId = currentRenderId;
  23089. if (!this._condition.isValid()) {
  23090. this._condition._currentResult = false;
  23091. return;
  23092. }
  23093. this._condition._currentResult = true;
  23094. }
  23095. }
  23096. this._nextActiveAction.execute(evt);
  23097. if (this._nextActiveAction._child) {
  23098. if (!this._nextActiveAction._child._actionManager) {
  23099. this._nextActiveAction._child._actionManager = this._actionManager;
  23100. }
  23101. this._nextActiveAction = this._nextActiveAction._child;
  23102. }
  23103. else {
  23104. this._nextActiveAction = this;
  23105. }
  23106. };
  23107. Action.prototype.execute = function (evt) {
  23108. };
  23109. Action.prototype.then = function (action) {
  23110. this._child = action;
  23111. action._actionManager = this._actionManager;
  23112. action._prepare();
  23113. return action;
  23114. };
  23115. Action.prototype._getProperty = function (propertyPath) {
  23116. return this._actionManager._getProperty(propertyPath);
  23117. };
  23118. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  23119. return this._actionManager._getEffectiveTarget(target, propertyPath);
  23120. };
  23121. return Action;
  23122. })();
  23123. BABYLON.Action = Action;
  23124. })(BABYLON || (BABYLON = {}));
  23125. //# sourceMappingURL=babylon.action.js.mapvar BABYLON;
  23126. (function (BABYLON) {
  23127. /**
  23128. * ActionEvent is the event beint sent when an action is triggered.
  23129. */
  23130. var ActionEvent = (function () {
  23131. /**
  23132. * @constructor
  23133. * @param source The mesh that triggered the action.
  23134. * @param pointerX the X mouse cursor position at the time of the event
  23135. * @param pointerY the Y mouse cursor position at the time of the event
  23136. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  23137. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  23138. */
  23139. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent) {
  23140. this.source = source;
  23141. this.pointerX = pointerX;
  23142. this.pointerY = pointerY;
  23143. this.meshUnderPointer = meshUnderPointer;
  23144. this.sourceEvent = sourceEvent;
  23145. }
  23146. /**
  23147. * Helper function to auto-create an ActionEvent from a source mesh.
  23148. * @param source the source mesh that triggered the event
  23149. * @param evt {Event} The original (browser) event
  23150. */
  23151. ActionEvent.CreateNew = function (source, evt) {
  23152. var scene = source.getScene();
  23153. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  23154. };
  23155. /**
  23156. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  23157. * @param scene the scene where the event occurred
  23158. * @param evt {Event} The original (browser) event
  23159. */
  23160. ActionEvent.CreateNewFromScene = function (scene, evt) {
  23161. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  23162. };
  23163. return ActionEvent;
  23164. })();
  23165. BABYLON.ActionEvent = ActionEvent;
  23166. /**
  23167. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  23168. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  23169. */
  23170. var ActionManager = (function () {
  23171. function ActionManager(scene) {
  23172. // Members
  23173. this.actions = new Array();
  23174. this._scene = scene;
  23175. scene._actionManagers.push(this);
  23176. }
  23177. Object.defineProperty(ActionManager, "NothingTrigger", {
  23178. get: function () {
  23179. return ActionManager._NothingTrigger;
  23180. },
  23181. enumerable: true,
  23182. configurable: true
  23183. });
  23184. Object.defineProperty(ActionManager, "OnPickTrigger", {
  23185. get: function () {
  23186. return ActionManager._OnPickTrigger;
  23187. },
  23188. enumerable: true,
  23189. configurable: true
  23190. });
  23191. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  23192. get: function () {
  23193. return ActionManager._OnLeftPickTrigger;
  23194. },
  23195. enumerable: true,
  23196. configurable: true
  23197. });
  23198. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  23199. get: function () {
  23200. return ActionManager._OnRightPickTrigger;
  23201. },
  23202. enumerable: true,
  23203. configurable: true
  23204. });
  23205. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  23206. get: function () {
  23207. return ActionManager._OnCenterPickTrigger;
  23208. },
  23209. enumerable: true,
  23210. configurable: true
  23211. });
  23212. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  23213. get: function () {
  23214. return ActionManager._OnPointerOverTrigger;
  23215. },
  23216. enumerable: true,
  23217. configurable: true
  23218. });
  23219. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  23220. get: function () {
  23221. return ActionManager._OnPointerOutTrigger;
  23222. },
  23223. enumerable: true,
  23224. configurable: true
  23225. });
  23226. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  23227. get: function () {
  23228. return ActionManager._OnEveryFrameTrigger;
  23229. },
  23230. enumerable: true,
  23231. configurable: true
  23232. });
  23233. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  23234. get: function () {
  23235. return ActionManager._OnIntersectionEnterTrigger;
  23236. },
  23237. enumerable: true,
  23238. configurable: true
  23239. });
  23240. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  23241. get: function () {
  23242. return ActionManager._OnIntersectionExitTrigger;
  23243. },
  23244. enumerable: true,
  23245. configurable: true
  23246. });
  23247. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  23248. get: function () {
  23249. return ActionManager._OnKeyDownTrigger;
  23250. },
  23251. enumerable: true,
  23252. configurable: true
  23253. });
  23254. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  23255. get: function () {
  23256. return ActionManager._OnKeyUpTrigger;
  23257. },
  23258. enumerable: true,
  23259. configurable: true
  23260. });
  23261. // Methods
  23262. ActionManager.prototype.dispose = function () {
  23263. var index = this._scene._actionManagers.indexOf(this);
  23264. if (index > -1) {
  23265. this._scene._actionManagers.splice(index, 1);
  23266. }
  23267. };
  23268. ActionManager.prototype.getScene = function () {
  23269. return this._scene;
  23270. };
  23271. /**
  23272. * Does this action manager handles actions of any of the given triggers
  23273. * @param {number[]} triggers - the triggers to be tested
  23274. * @return {boolean} whether one (or more) of the triggers is handeled
  23275. */
  23276. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  23277. for (var index = 0; index < this.actions.length; index++) {
  23278. var action = this.actions[index];
  23279. if (triggers.indexOf(action.trigger) > -1) {
  23280. return true;
  23281. }
  23282. }
  23283. return false;
  23284. };
  23285. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  23286. /**
  23287. * Does this action manager has pointer triggers
  23288. * @return {boolean} whether or not it has pointer triggers
  23289. */
  23290. get: function () {
  23291. for (var index = 0; index < this.actions.length; index++) {
  23292. var action = this.actions[index];
  23293. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  23294. return true;
  23295. }
  23296. }
  23297. return false;
  23298. },
  23299. enumerable: true,
  23300. configurable: true
  23301. });
  23302. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  23303. /**
  23304. * Does this action manager has pick triggers
  23305. * @return {boolean} whether or not it has pick triggers
  23306. */
  23307. get: function () {
  23308. for (var index = 0; index < this.actions.length; index++) {
  23309. var action = this.actions[index];
  23310. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  23311. return true;
  23312. }
  23313. }
  23314. return false;
  23315. },
  23316. enumerable: true,
  23317. configurable: true
  23318. });
  23319. /**
  23320. * Registers an action to this action manager
  23321. * @param {BABYLON.Action} action - the action to be registered
  23322. * @return {BABYLON.Action} the action amended (prepared) after registration
  23323. */
  23324. ActionManager.prototype.registerAction = function (action) {
  23325. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  23326. if (this.getScene().actionManager !== this) {
  23327. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  23328. return null;
  23329. }
  23330. }
  23331. this.actions.push(action);
  23332. action._actionManager = this;
  23333. action._prepare();
  23334. return action;
  23335. };
  23336. /**
  23337. * Process a specific trigger
  23338. * @param {number} trigger - the trigger to process
  23339. * @param evt {BABYLON.ActionEvent} the event details to be processed
  23340. */
  23341. ActionManager.prototype.processTrigger = function (trigger, evt) {
  23342. for (var index = 0; index < this.actions.length; index++) {
  23343. var action = this.actions[index];
  23344. if (action.trigger === trigger) {
  23345. if (trigger === ActionManager.OnKeyUpTrigger || trigger === ActionManager.OnKeyDownTrigger) {
  23346. var parameter = action.getTriggerParameter();
  23347. if (parameter) {
  23348. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  23349. var actualkey = String.fromCharCode(unicode).toLowerCase();
  23350. if (actualkey !== parameter.toLowerCase()) {
  23351. continue;
  23352. }
  23353. }
  23354. }
  23355. action._executeCurrent(evt);
  23356. }
  23357. }
  23358. };
  23359. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  23360. var properties = propertyPath.split(".");
  23361. for (var index = 0; index < properties.length - 1; index++) {
  23362. target = target[properties[index]];
  23363. }
  23364. return target;
  23365. };
  23366. ActionManager.prototype._getProperty = function (propertyPath) {
  23367. var properties = propertyPath.split(".");
  23368. return properties[properties.length - 1];
  23369. };
  23370. // Statics
  23371. ActionManager._NothingTrigger = 0;
  23372. ActionManager._OnPickTrigger = 1;
  23373. ActionManager._OnLeftPickTrigger = 2;
  23374. ActionManager._OnRightPickTrigger = 3;
  23375. ActionManager._OnCenterPickTrigger = 4;
  23376. ActionManager._OnPointerOverTrigger = 5;
  23377. ActionManager._OnPointerOutTrigger = 6;
  23378. ActionManager._OnEveryFrameTrigger = 7;
  23379. ActionManager._OnIntersectionEnterTrigger = 8;
  23380. ActionManager._OnIntersectionExitTrigger = 9;
  23381. ActionManager._OnKeyDownTrigger = 10;
  23382. ActionManager._OnKeyUpTrigger = 11;
  23383. return ActionManager;
  23384. })();
  23385. BABYLON.ActionManager = ActionManager;
  23386. })(BABYLON || (BABYLON = {}));
  23387. //# sourceMappingURL=babylon.actionManager.js.map
  23388. var BABYLON;
  23389. (function (BABYLON) {
  23390. var InterpolateValueAction = (function (_super) {
  23391. __extends(InterpolateValueAction, _super);
  23392. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations) {
  23393. if (duration === void 0) { duration = 1000; }
  23394. _super.call(this, triggerOptions, condition);
  23395. this.propertyPath = propertyPath;
  23396. this.value = value;
  23397. this.duration = duration;
  23398. this.stopOtherAnimations = stopOtherAnimations;
  23399. this._target = target;
  23400. }
  23401. InterpolateValueAction.prototype._prepare = function () {
  23402. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  23403. this._property = this._getProperty(this.propertyPath);
  23404. };
  23405. InterpolateValueAction.prototype.execute = function () {
  23406. var scene = this._actionManager.getScene();
  23407. var keys = [
  23408. {
  23409. frame: 0,
  23410. value: this._target[this._property]
  23411. },
  23412. {
  23413. frame: 100,
  23414. value: this.value
  23415. }
  23416. ];
  23417. var dataType;
  23418. if (typeof this.value === "number") {
  23419. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  23420. }
  23421. else if (this.value instanceof BABYLON.Color3) {
  23422. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  23423. }
  23424. else if (this.value instanceof BABYLON.Vector3) {
  23425. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  23426. }
  23427. else if (this.value instanceof BABYLON.Matrix) {
  23428. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  23429. }
  23430. else if (this.value instanceof BABYLON.Quaternion) {
  23431. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  23432. }
  23433. else {
  23434. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  23435. return;
  23436. }
  23437. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  23438. animation.setKeys(keys);
  23439. if (this.stopOtherAnimations) {
  23440. scene.stopAnimation(this._target);
  23441. }
  23442. scene.beginDirectAnimation(this._target, [animation], 0, 100);
  23443. };
  23444. return InterpolateValueAction;
  23445. })(BABYLON.Action);
  23446. BABYLON.InterpolateValueAction = InterpolateValueAction;
  23447. })(BABYLON || (BABYLON = {}));
  23448. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  23449. var BABYLON;
  23450. (function (BABYLON) {
  23451. var SwitchBooleanAction = (function (_super) {
  23452. __extends(SwitchBooleanAction, _super);
  23453. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  23454. _super.call(this, triggerOptions, condition);
  23455. this.propertyPath = propertyPath;
  23456. this._target = target;
  23457. }
  23458. SwitchBooleanAction.prototype._prepare = function () {
  23459. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  23460. this._property = this._getProperty(this.propertyPath);
  23461. };
  23462. SwitchBooleanAction.prototype.execute = function () {
  23463. this._target[this._property] = !this._target[this._property];
  23464. };
  23465. return SwitchBooleanAction;
  23466. })(BABYLON.Action);
  23467. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  23468. var SetStateAction = (function (_super) {
  23469. __extends(SetStateAction, _super);
  23470. function SetStateAction(triggerOptions, target, value, condition) {
  23471. _super.call(this, triggerOptions, condition);
  23472. this.value = value;
  23473. this._target = target;
  23474. }
  23475. SetStateAction.prototype.execute = function () {
  23476. this._target.state = this.value;
  23477. };
  23478. return SetStateAction;
  23479. })(BABYLON.Action);
  23480. BABYLON.SetStateAction = SetStateAction;
  23481. var SetValueAction = (function (_super) {
  23482. __extends(SetValueAction, _super);
  23483. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  23484. _super.call(this, triggerOptions, condition);
  23485. this.propertyPath = propertyPath;
  23486. this.value = value;
  23487. this._target = target;
  23488. }
  23489. SetValueAction.prototype._prepare = function () {
  23490. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  23491. this._property = this._getProperty(this.propertyPath);
  23492. };
  23493. SetValueAction.prototype.execute = function () {
  23494. this._target[this._property] = this.value;
  23495. };
  23496. return SetValueAction;
  23497. })(BABYLON.Action);
  23498. BABYLON.SetValueAction = SetValueAction;
  23499. var IncrementValueAction = (function (_super) {
  23500. __extends(IncrementValueAction, _super);
  23501. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  23502. _super.call(this, triggerOptions, condition);
  23503. this.propertyPath = propertyPath;
  23504. this.value = value;
  23505. this._target = target;
  23506. }
  23507. IncrementValueAction.prototype._prepare = function () {
  23508. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  23509. this._property = this._getProperty(this.propertyPath);
  23510. if (typeof this._target[this._property] !== "number") {
  23511. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  23512. }
  23513. };
  23514. IncrementValueAction.prototype.execute = function () {
  23515. this._target[this._property] += this.value;
  23516. };
  23517. return IncrementValueAction;
  23518. })(BABYLON.Action);
  23519. BABYLON.IncrementValueAction = IncrementValueAction;
  23520. var PlayAnimationAction = (function (_super) {
  23521. __extends(PlayAnimationAction, _super);
  23522. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  23523. _super.call(this, triggerOptions, condition);
  23524. this.from = from;
  23525. this.to = to;
  23526. this.loop = loop;
  23527. this._target = target;
  23528. }
  23529. PlayAnimationAction.prototype._prepare = function () {
  23530. };
  23531. PlayAnimationAction.prototype.execute = function () {
  23532. var scene = this._actionManager.getScene();
  23533. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  23534. };
  23535. return PlayAnimationAction;
  23536. })(BABYLON.Action);
  23537. BABYLON.PlayAnimationAction = PlayAnimationAction;
  23538. var StopAnimationAction = (function (_super) {
  23539. __extends(StopAnimationAction, _super);
  23540. function StopAnimationAction(triggerOptions, target, condition) {
  23541. _super.call(this, triggerOptions, condition);
  23542. this._target = target;
  23543. }
  23544. StopAnimationAction.prototype._prepare = function () {
  23545. };
  23546. StopAnimationAction.prototype.execute = function () {
  23547. var scene = this._actionManager.getScene();
  23548. scene.stopAnimation(this._target);
  23549. };
  23550. return StopAnimationAction;
  23551. })(BABYLON.Action);
  23552. BABYLON.StopAnimationAction = StopAnimationAction;
  23553. var DoNothingAction = (function (_super) {
  23554. __extends(DoNothingAction, _super);
  23555. function DoNothingAction(triggerOptions, condition) {
  23556. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  23557. _super.call(this, triggerOptions, condition);
  23558. }
  23559. DoNothingAction.prototype.execute = function () {
  23560. };
  23561. return DoNothingAction;
  23562. })(BABYLON.Action);
  23563. BABYLON.DoNothingAction = DoNothingAction;
  23564. var CombineAction = (function (_super) {
  23565. __extends(CombineAction, _super);
  23566. function CombineAction(triggerOptions, children, condition) {
  23567. _super.call(this, triggerOptions, condition);
  23568. this.children = children;
  23569. }
  23570. CombineAction.prototype._prepare = function () {
  23571. for (var index = 0; index < this.children.length; index++) {
  23572. this.children[index]._actionManager = this._actionManager;
  23573. this.children[index]._prepare();
  23574. }
  23575. };
  23576. CombineAction.prototype.execute = function (evt) {
  23577. for (var index = 0; index < this.children.length; index++) {
  23578. this.children[index].execute(evt);
  23579. }
  23580. };
  23581. return CombineAction;
  23582. })(BABYLON.Action);
  23583. BABYLON.CombineAction = CombineAction;
  23584. var ExecuteCodeAction = (function (_super) {
  23585. __extends(ExecuteCodeAction, _super);
  23586. function ExecuteCodeAction(triggerOptions, func, condition) {
  23587. _super.call(this, triggerOptions, condition);
  23588. this.func = func;
  23589. }
  23590. ExecuteCodeAction.prototype.execute = function (evt) {
  23591. this.func(evt);
  23592. };
  23593. return ExecuteCodeAction;
  23594. })(BABYLON.Action);
  23595. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  23596. var SetParentAction = (function (_super) {
  23597. __extends(SetParentAction, _super);
  23598. function SetParentAction(triggerOptions, target, parent, condition) {
  23599. _super.call(this, triggerOptions, condition);
  23600. this._target = target;
  23601. this._parent = parent;
  23602. }
  23603. SetParentAction.prototype._prepare = function () {
  23604. };
  23605. SetParentAction.prototype.execute = function () {
  23606. if (this._target.parent === this._parent) {
  23607. return;
  23608. }
  23609. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  23610. invertParentWorldMatrix.invert();
  23611. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  23612. this._target.parent = this._parent;
  23613. };
  23614. return SetParentAction;
  23615. })(BABYLON.Action);
  23616. BABYLON.SetParentAction = SetParentAction;
  23617. var PlaySoundAction = (function (_super) {
  23618. __extends(PlaySoundAction, _super);
  23619. function PlaySoundAction(triggerOptions, sound, condition) {
  23620. _super.call(this, triggerOptions, condition);
  23621. this._sound = sound;
  23622. }
  23623. PlaySoundAction.prototype._prepare = function () {
  23624. };
  23625. PlaySoundAction.prototype.execute = function () {
  23626. if (this._sound !== undefined)
  23627. this._sound.play();
  23628. };
  23629. return PlaySoundAction;
  23630. })(BABYLON.Action);
  23631. BABYLON.PlaySoundAction = PlaySoundAction;
  23632. var StopSoundAction = (function (_super) {
  23633. __extends(StopSoundAction, _super);
  23634. function StopSoundAction(triggerOptions, sound, condition) {
  23635. _super.call(this, triggerOptions, condition);
  23636. this._sound = sound;
  23637. }
  23638. StopSoundAction.prototype._prepare = function () {
  23639. };
  23640. StopSoundAction.prototype.execute = function () {
  23641. if (this._sound !== undefined)
  23642. this._sound.stop();
  23643. };
  23644. return StopSoundAction;
  23645. })(BABYLON.Action);
  23646. BABYLON.StopSoundAction = StopSoundAction;
  23647. })(BABYLON || (BABYLON = {}));
  23648. //# sourceMappingURL=babylon.directActions.js.map
  23649. var BABYLON;
  23650. (function (BABYLON) {
  23651. var Geometry = (function () {
  23652. function Geometry(id, scene, vertexData, updatable, mesh) {
  23653. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  23654. this._totalVertices = 0;
  23655. this._indices = [];
  23656. this.id = id;
  23657. this._engine = scene.getEngine();
  23658. this._meshes = [];
  23659. this._scene = scene;
  23660. // vertexData
  23661. if (vertexData) {
  23662. this.setAllVerticesData(vertexData, updatable);
  23663. }
  23664. else {
  23665. this._totalVertices = 0;
  23666. this._indices = [];
  23667. }
  23668. // applyToMesh
  23669. if (mesh) {
  23670. this.applyToMesh(mesh);
  23671. mesh.computeWorldMatrix(true);
  23672. }
  23673. }
  23674. Geometry.prototype.getScene = function () {
  23675. return this._scene;
  23676. };
  23677. Geometry.prototype.getEngine = function () {
  23678. return this._engine;
  23679. };
  23680. Geometry.prototype.isReady = function () {
  23681. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  23682. };
  23683. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  23684. vertexData.applyToGeometry(this, updatable);
  23685. };
  23686. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  23687. this._vertexBuffers = this._vertexBuffers || {};
  23688. if (this._vertexBuffers[kind]) {
  23689. this._vertexBuffers[kind].dispose();
  23690. }
  23691. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  23692. if (kind === BABYLON.VertexBuffer.PositionKind) {
  23693. stride = this._vertexBuffers[kind].getStrideSize();
  23694. this._totalVertices = data.length / stride;
  23695. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  23696. var meshes = this._meshes;
  23697. var numOfMeshes = meshes.length;
  23698. for (var index = 0; index < numOfMeshes; index++) {
  23699. var mesh = meshes[index];
  23700. mesh._resetPointsArrayCache();
  23701. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  23702. mesh._createGlobalSubMesh();
  23703. mesh.computeWorldMatrix(true);
  23704. }
  23705. }
  23706. };
  23707. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  23708. var vertexBuffer = this.getVertexBuffer(kind);
  23709. if (!vertexBuffer) {
  23710. return;
  23711. }
  23712. vertexBuffer.updateDirectly(data, offset);
  23713. };
  23714. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  23715. var vertexBuffer = this.getVertexBuffer(kind);
  23716. if (!vertexBuffer) {
  23717. return;
  23718. }
  23719. vertexBuffer.update(data);
  23720. if (kind === BABYLON.VertexBuffer.PositionKind) {
  23721. var extend;
  23722. var stride = vertexBuffer.getStrideSize();
  23723. this._totalVertices = data.length / stride;
  23724. if (updateExtends) {
  23725. extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  23726. }
  23727. var meshes = this._meshes;
  23728. var numOfMeshes = meshes.length;
  23729. for (var index = 0; index < numOfMeshes; index++) {
  23730. var mesh = meshes[index];
  23731. mesh._resetPointsArrayCache();
  23732. if (updateExtends) {
  23733. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  23734. }
  23735. }
  23736. }
  23737. };
  23738. Geometry.prototype.getTotalVertices = function () {
  23739. if (!this.isReady()) {
  23740. return 0;
  23741. }
  23742. return this._totalVertices;
  23743. };
  23744. Geometry.prototype.getVerticesData = function (kind) {
  23745. var vertexBuffer = this.getVertexBuffer(kind);
  23746. if (!vertexBuffer) {
  23747. return null;
  23748. }
  23749. return vertexBuffer.getData();
  23750. };
  23751. Geometry.prototype.getVertexBuffer = function (kind) {
  23752. if (!this.isReady()) {
  23753. return null;
  23754. }
  23755. return this._vertexBuffers[kind];
  23756. };
  23757. Geometry.prototype.getVertexBuffers = function () {
  23758. if (!this.isReady()) {
  23759. return null;
  23760. }
  23761. return this._vertexBuffers;
  23762. };
  23763. Geometry.prototype.isVerticesDataPresent = function (kind) {
  23764. if (!this._vertexBuffers) {
  23765. if (this._delayInfo) {
  23766. return this._delayInfo.indexOf(kind) !== -1;
  23767. }
  23768. return false;
  23769. }
  23770. return this._vertexBuffers[kind] !== undefined;
  23771. };
  23772. Geometry.prototype.getVerticesDataKinds = function () {
  23773. var result = [];
  23774. if (!this._vertexBuffers && this._delayInfo) {
  23775. for (var kind in this._delayInfo) {
  23776. result.push(kind);
  23777. }
  23778. }
  23779. else {
  23780. for (kind in this._vertexBuffers) {
  23781. result.push(kind);
  23782. }
  23783. }
  23784. return result;
  23785. };
  23786. Geometry.prototype.setIndices = function (indices, totalVertices) {
  23787. if (this._indexBuffer) {
  23788. this._engine._releaseBuffer(this._indexBuffer);
  23789. }
  23790. this._indices = indices;
  23791. if (this._meshes.length !== 0 && this._indices) {
  23792. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  23793. }
  23794. if (totalVertices !== undefined) {
  23795. this._totalVertices = totalVertices;
  23796. }
  23797. var meshes = this._meshes;
  23798. var numOfMeshes = meshes.length;
  23799. for (var index = 0; index < numOfMeshes; index++) {
  23800. meshes[index]._createGlobalSubMesh();
  23801. }
  23802. };
  23803. Geometry.prototype.getTotalIndices = function () {
  23804. if (!this.isReady()) {
  23805. return 0;
  23806. }
  23807. return this._indices.length;
  23808. };
  23809. Geometry.prototype.getIndices = function () {
  23810. if (!this.isReady()) {
  23811. return null;
  23812. }
  23813. return this._indices;
  23814. };
  23815. Geometry.prototype.getIndexBuffer = function () {
  23816. if (!this.isReady()) {
  23817. return null;
  23818. }
  23819. return this._indexBuffer;
  23820. };
  23821. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  23822. var meshes = this._meshes;
  23823. var index = meshes.indexOf(mesh);
  23824. if (index === -1) {
  23825. return;
  23826. }
  23827. for (var kind in this._vertexBuffers) {
  23828. this._vertexBuffers[kind].dispose();
  23829. }
  23830. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  23831. this._indexBuffer = null;
  23832. }
  23833. meshes.splice(index, 1);
  23834. mesh._geometry = null;
  23835. if (meshes.length === 0 && shouldDispose) {
  23836. this.dispose();
  23837. }
  23838. };
  23839. Geometry.prototype.applyToMesh = function (mesh) {
  23840. if (mesh._geometry === this) {
  23841. return;
  23842. }
  23843. var previousGeometry = mesh._geometry;
  23844. if (previousGeometry) {
  23845. previousGeometry.releaseForMesh(mesh);
  23846. }
  23847. var meshes = this._meshes;
  23848. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  23849. mesh._geometry = this;
  23850. this._scene.pushGeometry(this);
  23851. meshes.push(mesh);
  23852. if (this.isReady()) {
  23853. this._applyToMesh(mesh);
  23854. }
  23855. else {
  23856. mesh._boundingInfo = this._boundingInfo;
  23857. }
  23858. };
  23859. Geometry.prototype._applyToMesh = function (mesh) {
  23860. var numOfMeshes = this._meshes.length;
  23861. for (var kind in this._vertexBuffers) {
  23862. if (numOfMeshes === 1) {
  23863. this._vertexBuffers[kind].create();
  23864. }
  23865. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  23866. if (kind === BABYLON.VertexBuffer.PositionKind) {
  23867. mesh._resetPointsArrayCache();
  23868. var extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  23869. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  23870. mesh._createGlobalSubMesh();
  23871. //bounding info was just created again, world matrix should be applied again.
  23872. mesh._updateBoundingInfo();
  23873. }
  23874. }
  23875. // indexBuffer
  23876. if (numOfMeshes === 1 && this._indices) {
  23877. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  23878. }
  23879. if (this._indexBuffer) {
  23880. this._indexBuffer.references = numOfMeshes;
  23881. }
  23882. };
  23883. Geometry.prototype.load = function (scene, onLoaded) {
  23884. var _this = this;
  23885. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  23886. return;
  23887. }
  23888. if (this.isReady()) {
  23889. if (onLoaded) {
  23890. onLoaded();
  23891. }
  23892. return;
  23893. }
  23894. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  23895. scene._addPendingData(this);
  23896. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  23897. _this._delayLoadingFunction(JSON.parse(data), _this);
  23898. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  23899. _this._delayInfo = [];
  23900. scene._removePendingData(_this);
  23901. var meshes = _this._meshes;
  23902. var numOfMeshes = meshes.length;
  23903. for (var index = 0; index < numOfMeshes; index++) {
  23904. _this._applyToMesh(meshes[index]);
  23905. }
  23906. if (onLoaded) {
  23907. onLoaded();
  23908. }
  23909. }, function () {
  23910. }, scene.database);
  23911. };
  23912. Geometry.prototype.dispose = function () {
  23913. var meshes = this._meshes;
  23914. var numOfMeshes = meshes.length;
  23915. var index;
  23916. for (index = 0; index < numOfMeshes; index++) {
  23917. this.releaseForMesh(meshes[index]);
  23918. }
  23919. this._meshes = [];
  23920. for (var kind in this._vertexBuffers) {
  23921. this._vertexBuffers[kind].dispose();
  23922. }
  23923. this._vertexBuffers = [];
  23924. this._totalVertices = 0;
  23925. if (this._indexBuffer) {
  23926. this._engine._releaseBuffer(this._indexBuffer);
  23927. }
  23928. this._indexBuffer = null;
  23929. this._indices = [];
  23930. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  23931. this.delayLoadingFile = null;
  23932. this._delayLoadingFunction = null;
  23933. this._delayInfo = [];
  23934. this._boundingInfo = null; // todo: .dispose()
  23935. var geometries = this._scene.getGeometries();
  23936. index = geometries.indexOf(this);
  23937. if (index > -1) {
  23938. geometries.splice(index, 1);
  23939. }
  23940. };
  23941. Geometry.prototype.copy = function (id) {
  23942. var vertexData = new BABYLON.VertexData();
  23943. vertexData.indices = [];
  23944. var indices = this.getIndices();
  23945. for (var index = 0; index < indices.length; index++) {
  23946. vertexData.indices.push(indices[index]);
  23947. }
  23948. var updatable = false;
  23949. var stopChecking = false;
  23950. for (var kind in this._vertexBuffers) {
  23951. vertexData.set(this.getVerticesData(kind), kind);
  23952. if (!stopChecking) {
  23953. updatable = this.getVertexBuffer(kind).isUpdatable();
  23954. stopChecking = !updatable;
  23955. }
  23956. }
  23957. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  23958. geometry.delayLoadState = this.delayLoadState;
  23959. geometry.delayLoadingFile = this.delayLoadingFile;
  23960. geometry._delayLoadingFunction = this._delayLoadingFunction;
  23961. for (kind in this._delayInfo) {
  23962. geometry._delayInfo = geometry._delayInfo || [];
  23963. geometry._delayInfo.push(kind);
  23964. }
  23965. // Bounding info
  23966. var extend = BABYLON.Tools.ExtractMinAndMax(this.getVerticesData(BABYLON.VertexBuffer.PositionKind), 0, this.getTotalVertices());
  23967. geometry._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  23968. return geometry;
  23969. };
  23970. // Statics
  23971. Geometry.ExtractFromMesh = function (mesh, id) {
  23972. var geometry = mesh._geometry;
  23973. if (!geometry) {
  23974. return null;
  23975. }
  23976. return geometry.copy(id);
  23977. };
  23978. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  23979. // be aware Math.random() could cause collisions
  23980. Geometry.RandomId = function () {
  23981. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  23982. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  23983. return v.toString(16);
  23984. });
  23985. };
  23986. return Geometry;
  23987. })();
  23988. BABYLON.Geometry = Geometry;
  23989. /////// Primitives //////////////////////////////////////////////
  23990. var Geometry;
  23991. (function (Geometry) {
  23992. var Primitives;
  23993. (function (Primitives) {
  23994. /// Abstract class
  23995. var _Primitive = (function (_super) {
  23996. __extends(_Primitive, _super);
  23997. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  23998. this._beingRegenerated = true;
  23999. this._canBeRegenerated = canBeRegenerated;
  24000. _super.call(this, id, scene, vertexData, false, mesh); // updatable = false to be sure not to update vertices
  24001. this._beingRegenerated = false;
  24002. }
  24003. _Primitive.prototype.canBeRegenerated = function () {
  24004. return this._canBeRegenerated;
  24005. };
  24006. _Primitive.prototype.regenerate = function () {
  24007. if (!this._canBeRegenerated) {
  24008. return;
  24009. }
  24010. this._beingRegenerated = true;
  24011. this.setAllVerticesData(this._regenerateVertexData(), false);
  24012. this._beingRegenerated = false;
  24013. };
  24014. _Primitive.prototype.asNewGeometry = function (id) {
  24015. return _super.prototype.copy.call(this, id);
  24016. };
  24017. // overrides
  24018. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  24019. if (!this._beingRegenerated) {
  24020. return;
  24021. }
  24022. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  24023. };
  24024. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  24025. if (!this._beingRegenerated) {
  24026. return;
  24027. }
  24028. _super.prototype.setVerticesData.call(this, kind, data, false);
  24029. };
  24030. // to override
  24031. // protected
  24032. _Primitive.prototype._regenerateVertexData = function () {
  24033. throw new Error("Abstract method");
  24034. };
  24035. _Primitive.prototype.copy = function (id) {
  24036. throw new Error("Must be overriden in sub-classes.");
  24037. };
  24038. return _Primitive;
  24039. })(Geometry);
  24040. Primitives._Primitive = _Primitive;
  24041. var Box = (function (_super) {
  24042. __extends(Box, _super);
  24043. function Box(id, scene, size, canBeRegenerated, mesh) {
  24044. this.size = size;
  24045. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  24046. }
  24047. Box.prototype._regenerateVertexData = function () {
  24048. return BABYLON.VertexData.CreateBox(this.size);
  24049. };
  24050. Box.prototype.copy = function (id) {
  24051. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null);
  24052. };
  24053. return Box;
  24054. })(_Primitive);
  24055. Primitives.Box = Box;
  24056. var Sphere = (function (_super) {
  24057. __extends(Sphere, _super);
  24058. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh) {
  24059. this.segments = segments;
  24060. this.diameter = diameter;
  24061. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  24062. }
  24063. Sphere.prototype._regenerateVertexData = function () {
  24064. return BABYLON.VertexData.CreateSphere(this.segments, this.diameter);
  24065. };
  24066. Sphere.prototype.copy = function (id) {
  24067. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null);
  24068. };
  24069. return Sphere;
  24070. })(_Primitive);
  24071. Primitives.Sphere = Sphere;
  24072. var Cylinder = (function (_super) {
  24073. __extends(Cylinder, _super);
  24074. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh) {
  24075. if (subdivisions === void 0) { subdivisions = 1; }
  24076. this.height = height;
  24077. this.diameterTop = diameterTop;
  24078. this.diameterBottom = diameterBottom;
  24079. this.tessellation = tessellation;
  24080. this.subdivisions = subdivisions;
  24081. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  24082. }
  24083. Cylinder.prototype._regenerateVertexData = function () {
  24084. return BABYLON.VertexData.CreateCylinder(this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions);
  24085. };
  24086. Cylinder.prototype.copy = function (id) {
  24087. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null);
  24088. };
  24089. return Cylinder;
  24090. })(_Primitive);
  24091. Primitives.Cylinder = Cylinder;
  24092. var Torus = (function (_super) {
  24093. __extends(Torus, _super);
  24094. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh) {
  24095. this.diameter = diameter;
  24096. this.thickness = thickness;
  24097. this.tessellation = tessellation;
  24098. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  24099. }
  24100. Torus.prototype._regenerateVertexData = function () {
  24101. return BABYLON.VertexData.CreateTorus(this.diameter, this.thickness, this.tessellation);
  24102. };
  24103. Torus.prototype.copy = function (id) {
  24104. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null);
  24105. };
  24106. return Torus;
  24107. })(_Primitive);
  24108. Primitives.Torus = Torus;
  24109. var Ground = (function (_super) {
  24110. __extends(Ground, _super);
  24111. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  24112. this.width = width;
  24113. this.height = height;
  24114. this.subdivisions = subdivisions;
  24115. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  24116. }
  24117. Ground.prototype._regenerateVertexData = function () {
  24118. return BABYLON.VertexData.CreateGround(this.width, this.height, this.subdivisions);
  24119. };
  24120. Ground.prototype.copy = function (id) {
  24121. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  24122. };
  24123. return Ground;
  24124. })(_Primitive);
  24125. Primitives.Ground = Ground;
  24126. var TiledGround = (function (_super) {
  24127. __extends(TiledGround, _super);
  24128. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  24129. this.xmin = xmin;
  24130. this.zmin = zmin;
  24131. this.xmax = xmax;
  24132. this.zmax = zmax;
  24133. this.subdivisions = subdivisions;
  24134. this.precision = precision;
  24135. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  24136. }
  24137. TiledGround.prototype._regenerateVertexData = function () {
  24138. return BABYLON.VertexData.CreateTiledGround(this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision);
  24139. };
  24140. TiledGround.prototype.copy = function (id) {
  24141. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  24142. };
  24143. return TiledGround;
  24144. })(_Primitive);
  24145. Primitives.TiledGround = TiledGround;
  24146. var Plane = (function (_super) {
  24147. __extends(Plane, _super);
  24148. function Plane(id, scene, size, canBeRegenerated, mesh) {
  24149. this.size = size;
  24150. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  24151. }
  24152. Plane.prototype._regenerateVertexData = function () {
  24153. return BABYLON.VertexData.CreatePlane(this.size);
  24154. };
  24155. Plane.prototype.copy = function (id) {
  24156. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null);
  24157. };
  24158. return Plane;
  24159. })(_Primitive);
  24160. Primitives.Plane = Plane;
  24161. var TorusKnot = (function (_super) {
  24162. __extends(TorusKnot, _super);
  24163. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh) {
  24164. this.radius = radius;
  24165. this.tube = tube;
  24166. this.radialSegments = radialSegments;
  24167. this.tubularSegments = tubularSegments;
  24168. this.p = p;
  24169. this.q = q;
  24170. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  24171. }
  24172. TorusKnot.prototype._regenerateVertexData = function () {
  24173. return BABYLON.VertexData.CreateTorusKnot(this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q);
  24174. };
  24175. TorusKnot.prototype.copy = function (id) {
  24176. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null);
  24177. };
  24178. return TorusKnot;
  24179. })(_Primitive);
  24180. Primitives.TorusKnot = TorusKnot;
  24181. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  24182. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  24183. })(BABYLON || (BABYLON = {}));
  24184. //# sourceMappingURL=babylon.geometry.js.map
  24185. var BABYLON;
  24186. (function (BABYLON) {
  24187. var Gamepads = (function () {
  24188. function Gamepads(ongamedpadconnected) {
  24189. var _this = this;
  24190. this.babylonGamepads = [];
  24191. this.oneGamepadConnected = false;
  24192. this.isMonitoring = false;
  24193. this.gamepadEventSupported = 'GamepadEvent' in window;
  24194. this.gamepadSupportAvailable = (navigator.getGamepads || !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  24195. this.buttonADataURL = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAA9aSURBVHja7FtpbBzneX7m3otcihSpm9Z9UJalxPKhVLZlp6ktNzEaxE0CtAnQAgnSoPWPBi3syuiPwordFi5Qt2haFygCoylSV4Vby6os1I3kOLYrS65kXXQoypJJSaFEUTyXy925+rzfzC6HFFlL1kpAIe7i5czO7H7zPs97ft8MtTAMcSu/dNzirxkCZgiYIWCGgBkCZgi4hV/mDR5fSxAt+0ZiX0ucDxMSTJLK+f83BFSA6TFgK75OclshouKBFbA+xaV4k7Z+fD6sNRlmjYFXQMu4NiUVS/oHe5/ecnHo3MYxd7QthN9UcsdW6FqEPwgDOFbqpAajL2VlTrTULzj4Ow8+s4+nipSxWMoxIUkyrl/pGswFtIR7WzHgDCX77K7vfHNkbOA+AryjYZadb27OIJdzCNZBKmXw4kbk35qPsTEfJbeEkZESentHMdBfGtY142gu1bDvqV/925f4tQJlNCaj4hXX7RHXS0AFuJEAXvfHr/zmk67vPjir0V68aFEe8xtuQ6O1FHlrEXLmHBiaDUtzYBlpNYjrF+GFZfhhCcPeBQy53ehzT+H8QBe6uwfRf7l8xjKsvX/y5X98jl8fThDhJ4i46QQkrS5I6v7oX7/++77vPtLUlFnZtnIRlubvxRxnHbJmE79sxD/SqG0oZk8MFarRqufUkQAFrxcXSkfx0eB+nOggKX2jHYZhvf79r/z4L2IiipO84aYRkASfefnAX695p3P3c9mM/UufuaMVdzRvxVx7A0xaWdOMqVULJ6Z3TZv6KmHo0ztK6CkfxpHe3Th0pAuF0fLbn1u+9cmv3vW77bE3fGoSPi0BVfAvvPEHm9rPv//iooWz5m9Z/wCWZx+Go9UrN48QTD9IGMZ1cJIzTPisRQclPMrhME4W9mDfB2+i+2z/+TXz7/z2E7/85+9OIuGGE6BV3H77zm/d33nx6Ktr18zFg2t+DQude2n1tLJ8tcJ90vDhpG5Am7qTkJAQErywiLOld7G3/d9xvL0Hy1vWPbbtS3//00Q4hDeaAFXintrx1fu7+jp2r13bgofX/gaazbVkJQdLT9P6VqRFDSu2hIgXlBUBLgtCr3cce47/CMePX0Rr08qtzz7+8k8TpfKGtcKq1jPZre7oObyjdWkGd628l7AXwvMCeL7HjO6qrS8S1E5kTE9tfbiur665ccU9EB1EF9Ep0WXesEZIJb9j5/b/XUtzNrt29Rw0og2lchmBVqLo8LSAHlCixbTpddGm8Y7pjkttCCUP+JQy3FiatNuxdvUx9F4ayopO/OL9sQeEN4oA/eHn577oWPbGVes11PsrUBxjDafze1Te1VzouqnK2TgmLQljQqmrnAsT+iaPVb5b2co7EC+QhBgUeM1R1AcrsGp9Jy6+4W8U3fZ8r+e3EnOI2uaAX3l+zgNB4O9rW5/B8tY5WGo9BtOrJ4uMfUl+uj0B8HTmPXj8Pex86xVEnTDBBSE2r78fX9i09RPyZfT2A5ceIMSPwDOH8JH7Kk5+fAHtR0Zh6MZ9e7534Wc3wgO0sXLhD9OpFOa0egjGMhguD8BgTJooMfPbV1h/umz25ondcFP90IzY2iTgrfY9uH31aqSc9CeSEHkBEyITv28M8XMGc2/z0HGCpWCs8BS/9sWrDYOrJuCBZ+vu5sUfXbicia5kYGzUw4DWTwJKbApSjHuTBBjT2H68zg0MD4KlEwabZi0Y7wd85u/3O9/B6sVrPlEXeiF9nMmRxPt6Qf4y/HyIbh3HwkdF1zefGt5fUwK8wP2WAGwh02MFE/5ogYr3Qg/STL0W3d8aB1ppa+Pw0uI2Tz6/134Mg+UoIGZlZ2HMLaJYHkPICr6//RBamvPj/UA4dYKsegGrXqAXMaqNsDT6SreOY5Gu/FptCeBFN+caAphGiKFiGaOjA3AJHoGt6r7GgNbjqjo5yQkBUVHQ8PaJExjiaZ2yue12nO27gCNdHSptvf/xGdw11I2UZSmvCIJgQiJMhoEfeqpNDvUSRvUB5hMX9fUecg0aBi+Hm2uaAz633bmbm1VN8+h07LfKJdkOkQB2fL4BTlsj8No4YLG2putMSjwjp3QNvZdH8YsiExV501isFjU30lpF7D8dVfCA8sFHp7BuWYtaIwiCsCrCSDVhh9IX8k0CoHsoMQ84FrfFAE3zQAK0VaLzO9tK79XKAxSj+aYALt3XLfNipZD1v492YexrE/sP0zBgUIQIoYaflAXbz16CzyY6YKqYl8uheTarRioD7xAxCQHUpv18L1Yud+Iloujtk4zQo9WZcKURqjbHclzKvj0Gvcw8UA6oY2WqonSuGQGb5I+TJgEFEsB4daXzc0eopabcX13W0BXwgAnRZL4Q62s8ppnR/pFz/QjF+tRvxeIsY/cizGwRt83P4czACL8HdA1JUivCNGVogvdkNkgaGDNe4CvXFyJ8n+B5XGLJ1FmJXJ53AzjZKgGbatkKL5c/liNWIPO8uM/4VO2uKCQZjLmBqQAGJ4EmI8NMabDTOuyUobYXmPlCEpiqA1IkYdWSBpjpEDl6wsrF9aAjqHNOPXDyXAGprAknY5B0btOGGk/GlfE1taqofCNuuYNIJ+omOiZ1rpUHtEYWjkpWoP5EWV2sb5isA7aIQTHHxaIniNADui8PIs0Eb6SY/Z0UQc+j+mXYuoM7Vy/Age7zkBUyCZGLhRLSOYcWpfXFA1wPhqup8JNKq5UkKeoqSHxPLSoqnUQtw5ioc60IyE/VkOji8mYE2nZELNgCXLaOkGDFJBg4OzCMDEcxCfAzS1pQX5fHSNDLClLGwmwzls6vQ09hGFJYegdZ1hha2bqIBNelB5Qjog02TzpFNVEquYpMuTSYr/lcQPKPJHoRQ8W1GYO3lDgpO9pPWTEZEQGnuodg5Hyk66Lyd8fKOQQ6gqyWict7GeuWz8HQyWEFw+bB7ksF3Nk2V1nfpZTLQqSLslzXlDmHpsQ1osVoy/Solwf/GpdErpaAQUqjWxL2GWcWaSfAMIis7RBwiuCdtD1OgmNHBJCg7r4uZBnbdjaaq+3YewB+USYicY8juYPnMtloqdCjG3f39eO+3JKIAFadSiiZigBdgdcqItMxsmZbIbvUIKlzzQjoEgLGRjU2KTp8AjRCkzEnAG0mtQh8Ku0oAqok8JzP+Lw0MkB3jpKjKpapaL5WKZxafDdBqoC6O8LtyMAQhoZdzG7MwLU8FUYKPINcl+qimismRj26v2I71I3jDxfdpM41I6CTsmG4X0djKyc8RYu9t0Vl2QJbBJ5xFPiICJIg1hdhR3fs5HnWeldleZXABLA98b7Y5HtjkgwNEtbTN4iFC5oI3I1CTsAbsfVjAizJB3Qbx9HphRp6eqr3TDprSYA0FI/3ntOxbpUNM2OjpEcE6HYEWkhIKw+ICeBxi+T09F1WZU+iJq2n8fRDf4Ymu3XSrcOIgg8H9uOFn31fNUVC0oddZ7B5YxtDwlTgo66SEici2fokwCJjju0hw7J54WypQsB7tSRAza+H+nld30Y+m2b7SS+Qn9PKFl1egRciHIfWpxC8x+7tdA97+3zUcNyWX4Ci/THOoD2x/hmlQTox+3gDjWYeg/4gmF853xjBpUsjaGnJR24fu36FNzX5pmfY7EPStlSLIgb6gwk616QRYk8tS88/l/2PT/loyqbQkEmhPpNGNp1CmvtieQHvONGtL4sdy9Hjp5kkpTWmSzM7L529hErHs0cCpt2qW00BymDV3JXSU8HkAXKIjtNnedxS48m4Mr5cR9YlMrx+XTqNRmbP2ZkMOjvHKir/PNa5pouiitFjH44iZ6YwO5tFAy+eo6SdpOUJyhBQTJR+HT9HYLJaFve0PqQmTQLaVOCdmIRIWE+wrmWTzG8iAugF7qgWjSWkGbYa32EjJQTkGFv5dBZNJKCeHdb77UPXZP1rWhKLZ4Rqjv2Fz86lLMNlpusCY9BnqTNUIyTgrVhhs7rVq2KoW2TSxWlXLOCqWX4svmpzZdEjWvgQcdVWPnu+i4ClUS+HyLIFnsVf/9eBduw8eKYy2D1XMxO8Jg+IB9wl+3s/uAC3qKMpXY88m/ecnUHaSis3Na8Ab1UtaCh3j1y+sm8m9o0J+9Fv9MR4Zhw6DufTWasOebsOs+xZKHJOtvtQtertulrwV+0BtH5yWvyW7CxubsCTX9+KUQZ4ga7qmdGUFmrya8QWHwcxlReMF8Mw4QETrR8oy7tq2ivH5Tvya8n8aXZMGc4An/nRDpy52FfR8b5KCJCImt8YkYF/KDtnegfwz3sPodGajQajCTk9z/4mQ6iphMWv9AA9IeMWdyYdn+gBkVc5amwHWV6lHvVaI2YZzfinN95Ngv/htcT/p31CRNbdV8l8e++xD5HPNeHxhx5Bgf18kTN5T1kvjBfEjGjBJCai4gnjHqAnlvqS8e9NeujEjEul/NokDbai4V/2voafHD1S0evdWLeb8ojMNyly5fS//ffbcD0L33j4K4RX4rtMh/UUGLXmr6BWXN9MEFAhYfzmZ6hcXI+TpISRH8061Ui68gTWGUJP4aU9P8ZrB39S+Xkx1ummPSMkbebnJcxU1jm4D5eGhvB7j32HJcpUJHhxLIfxTZpxwGa8eKrHC51a9Tmp+N5P1RsQ01cJAwEflHw8/+pfYn/HgaQ+n7/a1vd6k+BUS2XvVD401TXhu488gQ0r71QUuLJsrWT8mSYtfkBMm0BAmFhNrgDX4oRqqeaJMw4c6TyIv/qPP0Xf8KUJ6sXuP1XluuEEyGsD5TXKgsqBNQvW4RtbnkDb4ttJQlGt/IQqLMJE7tWqOSBZCSrL6dFSqq3AnzhzDC/tewHt5w4nr3suvgN0+P8o3TeegFe3vYDHtj+xhLt/Q3kkeW5d693YuuHXsWHZPcixW4tCwo+trVU9QEs8G6HFqW5kdBiHTu3H64dfxpGuK8r665Tv7tz2D6e/tP23cT0E1OA5QR2iiIbs1i9u/9qTPPC12CtwlIofjZVvW/BZ3LVsC5bPW4u5DQuxaPay2NpRIuy61IkLA+dw8hdHceDUPpw49z9TXUysvWPXtl3bQ4yQtMJ1a18DAsbvRO/atvM5DXXPPbp9yzP8+GXBXTkngKYBdTWvE5RXdm87+HQEfLh2T57UIAdM95Js9+04LKSDbLzG31+Omxpx9xfxKR6AukkhMP0aKuUHsag5VEzE3fGSddsUVu6KFzIE+H/iJry0mX+bu8VfMwTMEDBDwAwBMwTMEHALv/5XgAEASpR5N6rB30UAAAAASUVORK5CYII=";
  24196. this._callbackGamepadConnected = ongamedpadconnected;
  24197. if (this.gamepadSupportAvailable) {
  24198. // Checking if the gamepad connected event is supported (like in Firefox)
  24199. if (this.gamepadEventSupported) {
  24200. window.addEventListener('gamepadconnected', function (evt) {
  24201. _this._onGamepadConnected(evt);
  24202. }, false);
  24203. window.addEventListener('gamepaddisconnected', function (evt) {
  24204. _this._onGamepadDisconnected(evt);
  24205. }, false);
  24206. }
  24207. else {
  24208. this._startMonitoringGamepads();
  24209. }
  24210. if (!this.oneGamepadConnected) {
  24211. this._insertGamepadDOMInstructions();
  24212. }
  24213. }
  24214. else {
  24215. this._insertGamepadDOMNotSupported();
  24216. }
  24217. }
  24218. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  24219. Gamepads.gamepadDOMInfo = document.createElement("div");
  24220. var buttonAImage = document.createElement("img");
  24221. buttonAImage.src = this.buttonADataURL;
  24222. var spanMessage = document.createElement("span");
  24223. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  24224. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  24225. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  24226. Gamepads.gamepadDOMInfo.style.position = "absolute";
  24227. Gamepads.gamepadDOMInfo.style.width = "100%";
  24228. Gamepads.gamepadDOMInfo.style.height = "48px";
  24229. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  24230. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  24231. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  24232. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  24233. buttonAImage.style.position = "relative";
  24234. buttonAImage.style.bottom = "8px";
  24235. spanMessage.style.position = "relative";
  24236. spanMessage.style.fontSize = "32px";
  24237. spanMessage.style.bottom = "32px";
  24238. spanMessage.style.color = "green";
  24239. document.body.appendChild(Gamepads.gamepadDOMInfo);
  24240. };
  24241. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  24242. Gamepads.gamepadDOMInfo = document.createElement("div");
  24243. var spanMessage = document.createElement("span");
  24244. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  24245. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  24246. Gamepads.gamepadDOMInfo.style.position = "absolute";
  24247. Gamepads.gamepadDOMInfo.style.width = "100%";
  24248. Gamepads.gamepadDOMInfo.style.height = "40px";
  24249. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  24250. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  24251. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  24252. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  24253. spanMessage.style.position = "relative";
  24254. spanMessage.style.fontSize = "32px";
  24255. spanMessage.style.color = "red";
  24256. document.body.appendChild(Gamepads.gamepadDOMInfo);
  24257. };
  24258. Gamepads.prototype.dispose = function () {
  24259. if (Gamepads.gamepadDOMInfo) {
  24260. document.body.removeChild(Gamepads.gamepadDOMInfo);
  24261. }
  24262. };
  24263. Gamepads.prototype._onGamepadConnected = function (evt) {
  24264. var newGamepad = this._addNewGamepad(evt.gamepad);
  24265. if (this._callbackGamepadConnected)
  24266. this._callbackGamepadConnected(newGamepad);
  24267. this._startMonitoringGamepads();
  24268. };
  24269. Gamepads.prototype._addNewGamepad = function (gamepad) {
  24270. if (!this.oneGamepadConnected) {
  24271. this.oneGamepadConnected = true;
  24272. if (Gamepads.gamepadDOMInfo) {
  24273. document.body.removeChild(Gamepads.gamepadDOMInfo);
  24274. Gamepads.gamepadDOMInfo = null;
  24275. }
  24276. }
  24277. var newGamepad;
  24278. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  24279. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  24280. }
  24281. else {
  24282. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  24283. }
  24284. this.babylonGamepads.push(newGamepad);
  24285. return newGamepad;
  24286. };
  24287. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  24288. for (var i in this.babylonGamepads) {
  24289. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  24290. this.babylonGamepads.splice(i, 1);
  24291. break;
  24292. }
  24293. }
  24294. // If no gamepads are left, stop the polling loop.
  24295. if (this.babylonGamepads.length == 0) {
  24296. this._stopMonitoringGamepads();
  24297. }
  24298. };
  24299. Gamepads.prototype._startMonitoringGamepads = function () {
  24300. if (!this.isMonitoring) {
  24301. this.isMonitoring = true;
  24302. this._checkGamepadsStatus();
  24303. }
  24304. };
  24305. Gamepads.prototype._stopMonitoringGamepads = function () {
  24306. this.isMonitoring = false;
  24307. };
  24308. Gamepads.prototype._checkGamepadsStatus = function () {
  24309. var _this = this;
  24310. // updating gamepad objects
  24311. this._updateGamepadObjects();
  24312. for (var i in this.babylonGamepads) {
  24313. this.babylonGamepads[i].update();
  24314. }
  24315. if (this.isMonitoring) {
  24316. if (window.requestAnimationFrame) {
  24317. window.requestAnimationFrame(function () {
  24318. _this._checkGamepadsStatus();
  24319. });
  24320. }
  24321. else if (window.mozRequestAnimationFrame) {
  24322. window.mozRequestAnimationFrame(function () {
  24323. _this._checkGamepadsStatus();
  24324. });
  24325. }
  24326. else if (window.webkitRequestAnimationFrame) {
  24327. window.webkitRequestAnimationFrame(function () {
  24328. _this._checkGamepadsStatus();
  24329. });
  24330. }
  24331. }
  24332. };
  24333. // This function is called only on Chrome, which does not yet support
  24334. // connection/disconnection events, but requires you to monitor
  24335. // an array for changes.
  24336. Gamepads.prototype._updateGamepadObjects = function () {
  24337. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  24338. for (var i = 0; i < gamepads.length; i++) {
  24339. if (gamepads[i]) {
  24340. if (!(gamepads[i].index in this.babylonGamepads)) {
  24341. var newGamepad = this._addNewGamepad(gamepads[i]);
  24342. if (this._callbackGamepadConnected) {
  24343. this._callbackGamepadConnected(newGamepad);
  24344. }
  24345. }
  24346. else {
  24347. this.babylonGamepads[i].browserGamepad = gamepads[i];
  24348. }
  24349. }
  24350. }
  24351. };
  24352. return Gamepads;
  24353. })();
  24354. BABYLON.Gamepads = Gamepads;
  24355. var StickValues = (function () {
  24356. function StickValues(x, y) {
  24357. this.x = x;
  24358. this.y = y;
  24359. }
  24360. return StickValues;
  24361. })();
  24362. BABYLON.StickValues = StickValues;
  24363. var Gamepad = (function () {
  24364. function Gamepad(id, index, browserGamepad) {
  24365. this.id = id;
  24366. this.index = index;
  24367. this.browserGamepad = browserGamepad;
  24368. if (this.browserGamepad.axes.length >= 2) {
  24369. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  24370. }
  24371. if (this.browserGamepad.axes.length >= 4) {
  24372. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  24373. }
  24374. }
  24375. Gamepad.prototype.onleftstickchanged = function (callback) {
  24376. this._onleftstickchanged = callback;
  24377. };
  24378. Gamepad.prototype.onrightstickchanged = function (callback) {
  24379. this._onrightstickchanged = callback;
  24380. };
  24381. Object.defineProperty(Gamepad.prototype, "leftStick", {
  24382. get: function () {
  24383. return this._leftStick;
  24384. },
  24385. set: function (newValues) {
  24386. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  24387. this._onleftstickchanged(newValues);
  24388. }
  24389. this._leftStick = newValues;
  24390. },
  24391. enumerable: true,
  24392. configurable: true
  24393. });
  24394. Object.defineProperty(Gamepad.prototype, "rightStick", {
  24395. get: function () {
  24396. return this._rightStick;
  24397. },
  24398. set: function (newValues) {
  24399. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  24400. this._onrightstickchanged(newValues);
  24401. }
  24402. this._rightStick = newValues;
  24403. },
  24404. enumerable: true,
  24405. configurable: true
  24406. });
  24407. Gamepad.prototype.update = function () {
  24408. if (this._leftStick) {
  24409. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  24410. }
  24411. if (this._rightStick) {
  24412. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  24413. }
  24414. };
  24415. return Gamepad;
  24416. })();
  24417. BABYLON.Gamepad = Gamepad;
  24418. var GenericPad = (function (_super) {
  24419. __extends(GenericPad, _super);
  24420. function GenericPad(id, index, gamepad) {
  24421. _super.call(this, id, index, gamepad);
  24422. this.id = id;
  24423. this.index = index;
  24424. this.gamepad = gamepad;
  24425. this._buttons = new Array(gamepad.buttons.length);
  24426. }
  24427. GenericPad.prototype.onbuttondown = function (callback) {
  24428. this._onbuttondown = callback;
  24429. };
  24430. GenericPad.prototype.onbuttonup = function (callback) {
  24431. this._onbuttonup = callback;
  24432. };
  24433. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  24434. if (newValue !== currentValue) {
  24435. if (this._onbuttondown && newValue === 1) {
  24436. this._onbuttondown(buttonIndex);
  24437. }
  24438. if (this._onbuttonup && newValue === 0) {
  24439. this._onbuttonup(buttonIndex);
  24440. }
  24441. }
  24442. return newValue;
  24443. };
  24444. GenericPad.prototype.update = function () {
  24445. _super.prototype.update.call(this);
  24446. for (var index = 0; index < this._buttons.length; index++) {
  24447. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  24448. }
  24449. };
  24450. return GenericPad;
  24451. })(Gamepad);
  24452. BABYLON.GenericPad = GenericPad;
  24453. (function (Xbox360Button) {
  24454. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  24455. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  24456. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  24457. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  24458. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  24459. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  24460. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  24461. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  24462. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  24463. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  24464. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  24465. var Xbox360Button = BABYLON.Xbox360Button;
  24466. (function (Xbox360Dpad) {
  24467. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  24468. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  24469. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  24470. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  24471. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  24472. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  24473. var Xbox360Pad = (function (_super) {
  24474. __extends(Xbox360Pad, _super);
  24475. function Xbox360Pad() {
  24476. _super.apply(this, arguments);
  24477. this._leftTrigger = 0;
  24478. this._rightTrigger = 0;
  24479. this._buttonA = 0;
  24480. this._buttonB = 0;
  24481. this._buttonX = 0;
  24482. this._buttonY = 0;
  24483. this._buttonBack = 0;
  24484. this._buttonStart = 0;
  24485. this._buttonLB = 0;
  24486. this._buttonRB = 0;
  24487. this._buttonLeftStick = 0;
  24488. this._buttonRightStick = 0;
  24489. this._dPadUp = 0;
  24490. this._dPadDown = 0;
  24491. this._dPadLeft = 0;
  24492. this._dPadRight = 0;
  24493. }
  24494. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  24495. this._onlefttriggerchanged = callback;
  24496. };
  24497. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  24498. this._onrighttriggerchanged = callback;
  24499. };
  24500. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  24501. get: function () {
  24502. return this._leftTrigger;
  24503. },
  24504. set: function (newValue) {
  24505. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  24506. this._onlefttriggerchanged(newValue);
  24507. }
  24508. this._leftTrigger = newValue;
  24509. },
  24510. enumerable: true,
  24511. configurable: true
  24512. });
  24513. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  24514. get: function () {
  24515. return this._rightTrigger;
  24516. },
  24517. set: function (newValue) {
  24518. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  24519. this._onrighttriggerchanged(newValue);
  24520. }
  24521. this._rightTrigger = newValue;
  24522. },
  24523. enumerable: true,
  24524. configurable: true
  24525. });
  24526. Xbox360Pad.prototype.onbuttondown = function (callback) {
  24527. this._onbuttondown = callback;
  24528. };
  24529. Xbox360Pad.prototype.onbuttonup = function (callback) {
  24530. this._onbuttonup = callback;
  24531. };
  24532. Xbox360Pad.prototype.ondpaddown = function (callback) {
  24533. this._ondpaddown = callback;
  24534. };
  24535. Xbox360Pad.prototype.ondpadup = function (callback) {
  24536. this._ondpadup = callback;
  24537. };
  24538. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  24539. if (newValue !== currentValue) {
  24540. if (this._onbuttondown && newValue === 1) {
  24541. this._onbuttondown(buttonType);
  24542. }
  24543. if (this._onbuttonup && newValue === 0) {
  24544. this._onbuttonup(buttonType);
  24545. }
  24546. }
  24547. return newValue;
  24548. };
  24549. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  24550. if (newValue !== currentValue) {
  24551. if (this._ondpaddown && newValue === 1) {
  24552. this._ondpaddown(buttonType);
  24553. }
  24554. if (this._ondpadup && newValue === 0) {
  24555. this._ondpadup(buttonType);
  24556. }
  24557. }
  24558. return newValue;
  24559. };
  24560. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  24561. get: function () {
  24562. return this._buttonA;
  24563. },
  24564. set: function (value) {
  24565. this._buttonA = this._setButtonValue(value, this._buttonA, 0 /* A */);
  24566. },
  24567. enumerable: true,
  24568. configurable: true
  24569. });
  24570. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  24571. get: function () {
  24572. return this._buttonB;
  24573. },
  24574. set: function (value) {
  24575. this._buttonB = this._setButtonValue(value, this._buttonB, 1 /* B */);
  24576. },
  24577. enumerable: true,
  24578. configurable: true
  24579. });
  24580. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  24581. get: function () {
  24582. return this._buttonX;
  24583. },
  24584. set: function (value) {
  24585. this._buttonX = this._setButtonValue(value, this._buttonX, 2 /* X */);
  24586. },
  24587. enumerable: true,
  24588. configurable: true
  24589. });
  24590. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  24591. get: function () {
  24592. return this._buttonY;
  24593. },
  24594. set: function (value) {
  24595. this._buttonY = this._setButtonValue(value, this._buttonY, 3 /* Y */);
  24596. },
  24597. enumerable: true,
  24598. configurable: true
  24599. });
  24600. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  24601. get: function () {
  24602. return this._buttonStart;
  24603. },
  24604. set: function (value) {
  24605. this._buttonStart = this._setButtonValue(value, this._buttonStart, 4 /* Start */);
  24606. },
  24607. enumerable: true,
  24608. configurable: true
  24609. });
  24610. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  24611. get: function () {
  24612. return this._buttonBack;
  24613. },
  24614. set: function (value) {
  24615. this._buttonBack = this._setButtonValue(value, this._buttonBack, 5 /* Back */);
  24616. },
  24617. enumerable: true,
  24618. configurable: true
  24619. });
  24620. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  24621. get: function () {
  24622. return this._buttonLB;
  24623. },
  24624. set: function (value) {
  24625. this._buttonLB = this._setButtonValue(value, this._buttonLB, 6 /* LB */);
  24626. },
  24627. enumerable: true,
  24628. configurable: true
  24629. });
  24630. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  24631. get: function () {
  24632. return this._buttonRB;
  24633. },
  24634. set: function (value) {
  24635. this._buttonRB = this._setButtonValue(value, this._buttonRB, 7 /* RB */);
  24636. },
  24637. enumerable: true,
  24638. configurable: true
  24639. });
  24640. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  24641. get: function () {
  24642. return this._buttonLeftStick;
  24643. },
  24644. set: function (value) {
  24645. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, 8 /* LeftStick */);
  24646. },
  24647. enumerable: true,
  24648. configurable: true
  24649. });
  24650. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  24651. get: function () {
  24652. return this._buttonRightStick;
  24653. },
  24654. set: function (value) {
  24655. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, 9 /* RightStick */);
  24656. },
  24657. enumerable: true,
  24658. configurable: true
  24659. });
  24660. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  24661. get: function () {
  24662. return this._dPadUp;
  24663. },
  24664. set: function (value) {
  24665. this._dPadUp = this._setDPadValue(value, this._dPadUp, 0 /* Up */);
  24666. },
  24667. enumerable: true,
  24668. configurable: true
  24669. });
  24670. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  24671. get: function () {
  24672. return this._dPadDown;
  24673. },
  24674. set: function (value) {
  24675. this._dPadDown = this._setDPadValue(value, this._dPadDown, 1 /* Down */);
  24676. },
  24677. enumerable: true,
  24678. configurable: true
  24679. });
  24680. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  24681. get: function () {
  24682. return this._dPadLeft;
  24683. },
  24684. set: function (value) {
  24685. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, 2 /* Left */);
  24686. },
  24687. enumerable: true,
  24688. configurable: true
  24689. });
  24690. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  24691. get: function () {
  24692. return this._dPadRight;
  24693. },
  24694. set: function (value) {
  24695. this._dPadRight = this._setDPadValue(value, this._dPadRight, 3 /* Right */);
  24696. },
  24697. enumerable: true,
  24698. configurable: true
  24699. });
  24700. Xbox360Pad.prototype.update = function () {
  24701. _super.prototype.update.call(this);
  24702. this.buttonA = this.browserGamepad.buttons[0].value;
  24703. this.buttonB = this.browserGamepad.buttons[1].value;
  24704. this.buttonX = this.browserGamepad.buttons[2].value;
  24705. this.buttonY = this.browserGamepad.buttons[3].value;
  24706. this.buttonLB = this.browserGamepad.buttons[4].value;
  24707. this.buttonRB = this.browserGamepad.buttons[5].value;
  24708. this.leftTrigger = this.browserGamepad.buttons[6].value;
  24709. this.rightTrigger = this.browserGamepad.buttons[7].value;
  24710. this.buttonBack = this.browserGamepad.buttons[8].value;
  24711. this.buttonStart = this.browserGamepad.buttons[9].value;
  24712. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  24713. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  24714. this.dPadUp = this.browserGamepad.buttons[12].value;
  24715. this.dPadDown = this.browserGamepad.buttons[13].value;
  24716. this.dPadLeft = this.browserGamepad.buttons[14].value;
  24717. this.dPadRight = this.browserGamepad.buttons[15].value;
  24718. };
  24719. return Xbox360Pad;
  24720. })(Gamepad);
  24721. BABYLON.Xbox360Pad = Xbox360Pad;
  24722. })(BABYLON || (BABYLON = {}));
  24723. //# sourceMappingURL=babylon.gamepads.js.map
  24724. var BABYLON;
  24725. (function (BABYLON) {
  24726. // We're mainly based on the logic defined into the FreeCamera code
  24727. var GamepadCamera = (function (_super) {
  24728. __extends(GamepadCamera, _super);
  24729. function GamepadCamera(name, position, scene) {
  24730. var _this = this;
  24731. _super.call(this, name, position, scene);
  24732. this.angularSensibility = 200;
  24733. this.moveSensibility = 75;
  24734. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  24735. _this._onNewGameConnected(gamepad);
  24736. });
  24737. }
  24738. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  24739. // Only the first gamepad can control the camera
  24740. if (gamepad.index === 0) {
  24741. this._gamepad = gamepad;
  24742. }
  24743. };
  24744. GamepadCamera.prototype._checkInputs = function () {
  24745. if (!this._gamepad) {
  24746. return;
  24747. }
  24748. var LSValues = this._gamepad.leftStick;
  24749. var normalizedLX = LSValues.x / this.moveSensibility;
  24750. var normalizedLY = LSValues.y / this.moveSensibility;
  24751. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  24752. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  24753. var RSValues = this._gamepad.rightStick;
  24754. var normalizedRX = RSValues.x / this.angularSensibility;
  24755. var normalizedRY = RSValues.y / this.angularSensibility;
  24756. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  24757. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  24758. ;
  24759. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  24760. var speed = this._computeLocalCameraSpeed() * 50.0;
  24761. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  24762. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  24763. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  24764. };
  24765. GamepadCamera.prototype.dispose = function () {
  24766. this._gamepads.dispose();
  24767. _super.prototype.dispose.call(this);
  24768. };
  24769. return GamepadCamera;
  24770. })(BABYLON.FreeCamera);
  24771. BABYLON.GamepadCamera = GamepadCamera;
  24772. })(BABYLON || (BABYLON = {}));
  24773. //# sourceMappingURL=babylon.gamepadCamera.js.map
  24774. var BABYLON;
  24775. (function (BABYLON) {
  24776. var LinesMesh = (function (_super) {
  24777. __extends(LinesMesh, _super);
  24778. function LinesMesh(name, scene, updatable) {
  24779. if (updatable === void 0) { updatable = false; }
  24780. _super.call(this, name, scene);
  24781. this.color = new BABYLON.Color3(1, 1, 1);
  24782. this.alpha = 1;
  24783. this._indices = new Array();
  24784. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  24785. attributes: ["position"],
  24786. uniforms: ["worldViewProjection", "color"],
  24787. needAlphaBlending: true
  24788. });
  24789. }
  24790. Object.defineProperty(LinesMesh.prototype, "material", {
  24791. get: function () {
  24792. return this._colorShader;
  24793. },
  24794. enumerable: true,
  24795. configurable: true
  24796. });
  24797. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  24798. get: function () {
  24799. return false;
  24800. },
  24801. enumerable: true,
  24802. configurable: true
  24803. });
  24804. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  24805. get: function () {
  24806. return false;
  24807. },
  24808. enumerable: true,
  24809. configurable: true
  24810. });
  24811. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  24812. var engine = this.getScene().getEngine();
  24813. var indexToBind = this._geometry.getIndexBuffer();
  24814. // VBOs
  24815. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  24816. // Color
  24817. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  24818. };
  24819. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  24820. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  24821. return;
  24822. }
  24823. var engine = this.getScene().getEngine();
  24824. // Draw order
  24825. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  24826. };
  24827. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  24828. return null;
  24829. };
  24830. LinesMesh.prototype.dispose = function (doNotRecurse) {
  24831. this._colorShader.dispose();
  24832. _super.prototype.dispose.call(this, doNotRecurse);
  24833. };
  24834. return LinesMesh;
  24835. })(BABYLON.Mesh);
  24836. BABYLON.LinesMesh = LinesMesh;
  24837. })(BABYLON || (BABYLON = {}));
  24838. //# sourceMappingURL=babylon.linesMesh.js.mapvar BABYLON;
  24839. (function (BABYLON) {
  24840. var OutlineRenderer = (function () {
  24841. function OutlineRenderer(scene) {
  24842. this._scene = scene;
  24843. }
  24844. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  24845. var _this = this;
  24846. if (useOverlay === void 0) { useOverlay = false; }
  24847. var scene = this._scene;
  24848. var engine = this._scene.getEngine();
  24849. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  24850. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  24851. return;
  24852. }
  24853. var mesh = subMesh.getRenderingMesh();
  24854. var material = subMesh.getMaterial();
  24855. engine.enableEffect(this._effect);
  24856. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  24857. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  24858. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  24859. // Bones
  24860. if (mesh.useBones) {
  24861. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  24862. }
  24863. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  24864. // Alpha test
  24865. if (material && material.needAlphaTesting()) {
  24866. var alphaTexture = material.getAlphaTestTexture();
  24867. this._effect.setTexture("diffuseSampler", alphaTexture);
  24868. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  24869. }
  24870. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  24871. _this._effect.setMatrix("world", world);
  24872. });
  24873. };
  24874. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  24875. var defines = [];
  24876. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  24877. var mesh = subMesh.getMesh();
  24878. var material = subMesh.getMaterial();
  24879. // Alpha test
  24880. if (material && material.needAlphaTesting()) {
  24881. defines.push("#define ALPHATEST");
  24882. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  24883. attribs.push(BABYLON.VertexBuffer.UVKind);
  24884. defines.push("#define UV1");
  24885. }
  24886. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  24887. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  24888. defines.push("#define UV2");
  24889. }
  24890. }
  24891. // Bones
  24892. if (mesh.useBones) {
  24893. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  24894. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  24895. defines.push("#define BONES");
  24896. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  24897. }
  24898. // Instances
  24899. if (useInstances) {
  24900. defines.push("#define INSTANCES");
  24901. attribs.push("world0");
  24902. attribs.push("world1");
  24903. attribs.push("world2");
  24904. attribs.push("world3");
  24905. }
  24906. // Get correct effect
  24907. var join = defines.join("\n");
  24908. if (this._cachedDefines !== join) {
  24909. this._cachedDefines = join;
  24910. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  24911. }
  24912. return this._effect.isReady();
  24913. };
  24914. return OutlineRenderer;
  24915. })();
  24916. BABYLON.OutlineRenderer = OutlineRenderer;
  24917. })(BABYLON || (BABYLON = {}));
  24918. //# sourceMappingURL=babylon.outlineRenderer.js.mapvar BABYLON;
  24919. (function (BABYLON) {
  24920. var MeshAssetTask = (function () {
  24921. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  24922. this.name = name;
  24923. this.meshesNames = meshesNames;
  24924. this.rootUrl = rootUrl;
  24925. this.sceneFilename = sceneFilename;
  24926. this.isCompleted = false;
  24927. }
  24928. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  24929. var _this = this;
  24930. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  24931. _this.loadedMeshes = meshes;
  24932. _this.loadedParticleSystems = particleSystems;
  24933. _this.loadedSkeletons = skeletons;
  24934. _this.isCompleted = true;
  24935. if (_this.onSuccess) {
  24936. _this.onSuccess(_this);
  24937. }
  24938. onSuccess();
  24939. }, null, function () {
  24940. if (_this.onError) {
  24941. _this.onError(_this);
  24942. }
  24943. onError();
  24944. });
  24945. };
  24946. return MeshAssetTask;
  24947. })();
  24948. BABYLON.MeshAssetTask = MeshAssetTask;
  24949. var TextFileAssetTask = (function () {
  24950. function TextFileAssetTask(name, url) {
  24951. this.name = name;
  24952. this.url = url;
  24953. this.isCompleted = false;
  24954. }
  24955. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  24956. var _this = this;
  24957. BABYLON.Tools.LoadFile(this.url, function (data) {
  24958. _this.text = data;
  24959. _this.isCompleted = true;
  24960. if (_this.onSuccess) {
  24961. _this.onSuccess(_this);
  24962. }
  24963. onSuccess();
  24964. }, null, scene.database, false, function () {
  24965. if (_this.onError) {
  24966. _this.onError(_this);
  24967. }
  24968. onError();
  24969. });
  24970. };
  24971. return TextFileAssetTask;
  24972. })();
  24973. BABYLON.TextFileAssetTask = TextFileAssetTask;
  24974. var BinaryFileAssetTask = (function () {
  24975. function BinaryFileAssetTask(name, url) {
  24976. this.name = name;
  24977. this.url = url;
  24978. this.isCompleted = false;
  24979. }
  24980. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  24981. var _this = this;
  24982. BABYLON.Tools.LoadFile(this.url, function (data) {
  24983. _this.data = data;
  24984. _this.isCompleted = true;
  24985. if (_this.onSuccess) {
  24986. _this.onSuccess(_this);
  24987. }
  24988. onSuccess();
  24989. }, null, scene.database, true, function () {
  24990. if (_this.onError) {
  24991. _this.onError(_this);
  24992. }
  24993. onError();
  24994. });
  24995. };
  24996. return BinaryFileAssetTask;
  24997. })();
  24998. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  24999. var ImageAssetTask = (function () {
  25000. function ImageAssetTask(name, url) {
  25001. this.name = name;
  25002. this.url = url;
  25003. this.isCompleted = false;
  25004. }
  25005. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  25006. var _this = this;
  25007. var img = new Image();
  25008. img.onload = function () {
  25009. _this.image = img;
  25010. _this.isCompleted = true;
  25011. if (_this.onSuccess) {
  25012. _this.onSuccess(_this);
  25013. }
  25014. onSuccess();
  25015. };
  25016. img.onerror = function () {
  25017. if (_this.onError) {
  25018. _this.onError(_this);
  25019. }
  25020. onError();
  25021. };
  25022. img.src = this.url;
  25023. };
  25024. return ImageAssetTask;
  25025. })();
  25026. BABYLON.ImageAssetTask = ImageAssetTask;
  25027. var TextureAssetTask = (function () {
  25028. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  25029. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  25030. this.name = name;
  25031. this.url = url;
  25032. this.noMipmap = noMipmap;
  25033. this.invertY = invertY;
  25034. this.samplingMode = samplingMode;
  25035. this.isCompleted = false;
  25036. }
  25037. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  25038. var _this = this;
  25039. var onload = function () {
  25040. _this.isCompleted = true;
  25041. if (_this.onSuccess) {
  25042. _this.onSuccess(_this);
  25043. }
  25044. onSuccess();
  25045. };
  25046. var onerror = function () {
  25047. if (_this.onError) {
  25048. _this.onError(_this);
  25049. }
  25050. onError();
  25051. };
  25052. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onError);
  25053. };
  25054. return TextureAssetTask;
  25055. })();
  25056. BABYLON.TextureAssetTask = TextureAssetTask;
  25057. var AssetsManager = (function () {
  25058. function AssetsManager(scene) {
  25059. this._tasks = new Array();
  25060. this._waitingTasksCount = 0;
  25061. this.useDefaultLoadingScreen = true;
  25062. this._scene = scene;
  25063. }
  25064. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  25065. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  25066. this._tasks.push(task);
  25067. return task;
  25068. };
  25069. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  25070. var task = new TextFileAssetTask(taskName, url);
  25071. this._tasks.push(task);
  25072. return task;
  25073. };
  25074. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  25075. var task = new BinaryFileAssetTask(taskName, url);
  25076. this._tasks.push(task);
  25077. return task;
  25078. };
  25079. AssetsManager.prototype.addImageTask = function (taskName, url) {
  25080. var task = new ImageAssetTask(taskName, url);
  25081. this._tasks.push(task);
  25082. return task;
  25083. };
  25084. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  25085. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  25086. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  25087. this._tasks.push(task);
  25088. return task;
  25089. };
  25090. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  25091. this._waitingTasksCount--;
  25092. if (this._waitingTasksCount === 0) {
  25093. if (this.onFinish) {
  25094. this.onFinish(this._tasks);
  25095. }
  25096. this._scene.getEngine().hideLoadingUI();
  25097. }
  25098. };
  25099. AssetsManager.prototype._runTask = function (task) {
  25100. var _this = this;
  25101. task.run(this._scene, function () {
  25102. if (_this.onTaskSuccess) {
  25103. _this.onTaskSuccess(task);
  25104. }
  25105. _this._decreaseWaitingTasksCount();
  25106. }, function () {
  25107. if (_this.onTaskError) {
  25108. _this.onTaskError(task);
  25109. }
  25110. _this._decreaseWaitingTasksCount();
  25111. });
  25112. };
  25113. AssetsManager.prototype.reset = function () {
  25114. this._tasks = new Array();
  25115. return this;
  25116. };
  25117. AssetsManager.prototype.load = function () {
  25118. this._waitingTasksCount = this._tasks.length;
  25119. if (this._waitingTasksCount === 0) {
  25120. if (this.onFinish) {
  25121. this.onFinish(this._tasks);
  25122. }
  25123. return this;
  25124. }
  25125. if (this.useDefaultLoadingScreen) {
  25126. this._scene.getEngine().displayLoadingUI();
  25127. }
  25128. for (var index = 0; index < this._tasks.length; index++) {
  25129. var task = this._tasks[index];
  25130. this._runTask(task);
  25131. }
  25132. return this;
  25133. };
  25134. return AssetsManager;
  25135. })();
  25136. BABYLON.AssetsManager = AssetsManager;
  25137. })(BABYLON || (BABYLON = {}));
  25138. //# sourceMappingURL=babylon.assetsManager.js.map
  25139. var BABYLON;
  25140. (function (BABYLON) {
  25141. var VRDeviceOrientationCamera = (function (_super) {
  25142. __extends(VRDeviceOrientationCamera, _super);
  25143. function VRDeviceOrientationCamera(name, position, scene) {
  25144. _super.call(this, name, position, scene);
  25145. this._alpha = 0;
  25146. this._beta = 0;
  25147. this._gamma = 0;
  25148. }
  25149. VRDeviceOrientationCamera.prototype._onOrientationEvent = function (evt) {
  25150. this._alpha = +evt.alpha | 0;
  25151. this._beta = +evt.beta | 0;
  25152. this._gamma = +evt.gamma | 0;
  25153. if (this._gamma < 0) {
  25154. this._gamma = 90 + this._gamma;
  25155. }
  25156. else {
  25157. // Incline it in the correct angle.
  25158. this._gamma = 270 - this._gamma;
  25159. }
  25160. this.rotation.x = this._gamma / 180.0 * Math.PI;
  25161. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  25162. this.rotation.z = this._beta / 180.0 * Math.PI;
  25163. };
  25164. return VRDeviceOrientationCamera;
  25165. })(BABYLON.OculusCamera);
  25166. BABYLON.VRDeviceOrientationCamera = VRDeviceOrientationCamera;
  25167. })(BABYLON || (BABYLON = {}));
  25168. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  25169. var BABYLON;
  25170. (function (BABYLON) {
  25171. var WebVRCamera = (function (_super) {
  25172. __extends(WebVRCamera, _super);
  25173. function WebVRCamera(name, position, scene) {
  25174. _super.call(this, name, position, scene);
  25175. this._hmdDevice = null;
  25176. this._sensorDevice = null;
  25177. this._cacheState = null;
  25178. this._cacheQuaternion = new BABYLON.Quaternion();
  25179. this._cacheRotation = BABYLON.Vector3.Zero();
  25180. this._vrEnabled = false;
  25181. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  25182. }
  25183. WebVRCamera.prototype._getWebVRDevices = function (devices) {
  25184. var size = devices.length;
  25185. var i = 0;
  25186. // Reset devices.
  25187. this._sensorDevice = null;
  25188. this._hmdDevice = null;
  25189. while (i < size && this._hmdDevice === null) {
  25190. if (devices[i] instanceof HMDVRDevice) {
  25191. this._hmdDevice = devices[i];
  25192. }
  25193. i++;
  25194. }
  25195. i = 0;
  25196. while (i < size && this._sensorDevice === null) {
  25197. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  25198. this._sensorDevice = devices[i];
  25199. }
  25200. i++;
  25201. }
  25202. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  25203. };
  25204. WebVRCamera.prototype._update = function () {
  25205. if (this._vrEnabled) {
  25206. this._cacheState = this._sensorDevice.getState();
  25207. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  25208. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  25209. this.rotation.x = -this._cacheRotation.z;
  25210. this.rotation.y = -this._cacheRotation.y;
  25211. this.rotation.z = this._cacheRotation.x;
  25212. }
  25213. _super.prototype._update.call(this);
  25214. };
  25215. WebVRCamera.prototype.attachControl = function (element, noPreventDefault) {
  25216. _super.prototype.attachControl.call(this, element, noPreventDefault);
  25217. if (navigator.getVRDevices) {
  25218. navigator.getVRDevices().then(this._getWebVRDevices);
  25219. }
  25220. else if (navigator.mozGetVRDevices) {
  25221. navigator.mozGetVRDevices(this._getWebVRDevices);
  25222. }
  25223. };
  25224. WebVRCamera.prototype.detachControl = function (element) {
  25225. _super.prototype.detachControl.call(this, element);
  25226. this._vrEnabled = false;
  25227. };
  25228. return WebVRCamera;
  25229. })(BABYLON.OculusCamera);
  25230. BABYLON.WebVRCamera = WebVRCamera;
  25231. })(BABYLON || (BABYLON = {}));
  25232. //# sourceMappingURL=babylon.webVRCamera.js.map
  25233. var BABYLON;
  25234. (function (BABYLON) {
  25235. // Standard optimizations
  25236. var SceneOptimization = (function () {
  25237. function SceneOptimization(priority) {
  25238. if (priority === void 0) { priority = 0; }
  25239. this.priority = priority;
  25240. this.apply = function (scene) {
  25241. return true; // Return true if everything that can be done was applied
  25242. };
  25243. }
  25244. return SceneOptimization;
  25245. })();
  25246. BABYLON.SceneOptimization = SceneOptimization;
  25247. var TextureOptimization = (function (_super) {
  25248. __extends(TextureOptimization, _super);
  25249. function TextureOptimization(priority, maximumSize) {
  25250. var _this = this;
  25251. if (priority === void 0) { priority = 0; }
  25252. if (maximumSize === void 0) { maximumSize = 1024; }
  25253. _super.call(this, priority);
  25254. this.priority = priority;
  25255. this.maximumSize = maximumSize;
  25256. this.apply = function (scene) {
  25257. var allDone = true;
  25258. for (var index = 0; index < scene.textures.length; index++) {
  25259. var texture = scene.textures[index];
  25260. if (!texture.canRescale) {
  25261. continue;
  25262. }
  25263. var currentSize = texture.getSize();
  25264. var maxDimension = Math.max(currentSize.width, currentSize.height);
  25265. if (maxDimension > _this.maximumSize) {
  25266. texture.scale(0.5);
  25267. allDone = false;
  25268. }
  25269. }
  25270. return allDone;
  25271. };
  25272. }
  25273. return TextureOptimization;
  25274. })(SceneOptimization);
  25275. BABYLON.TextureOptimization = TextureOptimization;
  25276. var HardwareScalingOptimization = (function (_super) {
  25277. __extends(HardwareScalingOptimization, _super);
  25278. function HardwareScalingOptimization(priority, maximumScale) {
  25279. var _this = this;
  25280. if (priority === void 0) { priority = 0; }
  25281. if (maximumScale === void 0) { maximumScale = 2; }
  25282. _super.call(this, priority);
  25283. this.priority = priority;
  25284. this.maximumScale = maximumScale;
  25285. this._currentScale = 1;
  25286. this.apply = function (scene) {
  25287. _this._currentScale++;
  25288. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  25289. return _this._currentScale >= _this.maximumScale;
  25290. };
  25291. }
  25292. return HardwareScalingOptimization;
  25293. })(SceneOptimization);
  25294. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  25295. var ShadowsOptimization = (function (_super) {
  25296. __extends(ShadowsOptimization, _super);
  25297. function ShadowsOptimization() {
  25298. _super.apply(this, arguments);
  25299. this.apply = function (scene) {
  25300. scene.shadowsEnabled = false;
  25301. return true;
  25302. };
  25303. }
  25304. return ShadowsOptimization;
  25305. })(SceneOptimization);
  25306. BABYLON.ShadowsOptimization = ShadowsOptimization;
  25307. var PostProcessesOptimization = (function (_super) {
  25308. __extends(PostProcessesOptimization, _super);
  25309. function PostProcessesOptimization() {
  25310. _super.apply(this, arguments);
  25311. this.apply = function (scene) {
  25312. scene.postProcessesEnabled = false;
  25313. return true;
  25314. };
  25315. }
  25316. return PostProcessesOptimization;
  25317. })(SceneOptimization);
  25318. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  25319. var LensFlaresOptimization = (function (_super) {
  25320. __extends(LensFlaresOptimization, _super);
  25321. function LensFlaresOptimization() {
  25322. _super.apply(this, arguments);
  25323. this.apply = function (scene) {
  25324. scene.lensFlaresEnabled = false;
  25325. return true;
  25326. };
  25327. }
  25328. return LensFlaresOptimization;
  25329. })(SceneOptimization);
  25330. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  25331. var ParticlesOptimization = (function (_super) {
  25332. __extends(ParticlesOptimization, _super);
  25333. function ParticlesOptimization() {
  25334. _super.apply(this, arguments);
  25335. this.apply = function (scene) {
  25336. scene.particlesEnabled = false;
  25337. return true;
  25338. };
  25339. }
  25340. return ParticlesOptimization;
  25341. })(SceneOptimization);
  25342. BABYLON.ParticlesOptimization = ParticlesOptimization;
  25343. var RenderTargetsOptimization = (function (_super) {
  25344. __extends(RenderTargetsOptimization, _super);
  25345. function RenderTargetsOptimization() {
  25346. _super.apply(this, arguments);
  25347. this.apply = function (scene) {
  25348. scene.renderTargetsEnabled = false;
  25349. return true;
  25350. };
  25351. }
  25352. return RenderTargetsOptimization;
  25353. })(SceneOptimization);
  25354. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  25355. var MergeMeshesOptimization = (function (_super) {
  25356. __extends(MergeMeshesOptimization, _super);
  25357. function MergeMeshesOptimization() {
  25358. var _this = this;
  25359. _super.apply(this, arguments);
  25360. this._canBeMerged = function (abstractMesh) {
  25361. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  25362. return false;
  25363. }
  25364. var mesh = abstractMesh;
  25365. if (!mesh.isVisible || !mesh.isEnabled()) {
  25366. return false;
  25367. }
  25368. if (mesh.instances.length > 0) {
  25369. return false;
  25370. }
  25371. if (mesh.skeleton || mesh.hasLODLevels) {
  25372. return false;
  25373. }
  25374. return true;
  25375. };
  25376. this.apply = function (scene) {
  25377. var globalPool = scene.meshes.slice(0);
  25378. var globalLength = globalPool.length;
  25379. for (var index = 0; index < globalLength; index++) {
  25380. var currentPool = new Array();
  25381. var current = globalPool[index];
  25382. // Checks
  25383. if (!_this._canBeMerged(current)) {
  25384. continue;
  25385. }
  25386. currentPool.push(current);
  25387. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  25388. var otherMesh = globalPool[subIndex];
  25389. if (!_this._canBeMerged(otherMesh)) {
  25390. continue;
  25391. }
  25392. if (otherMesh.material !== current.material) {
  25393. continue;
  25394. }
  25395. if (otherMesh.checkCollisions !== current.checkCollisions) {
  25396. continue;
  25397. }
  25398. currentPool.push(otherMesh);
  25399. globalLength--;
  25400. globalPool.splice(subIndex, 1);
  25401. subIndex--;
  25402. }
  25403. if (currentPool.length < 2) {
  25404. continue;
  25405. }
  25406. // Merge meshes
  25407. BABYLON.Mesh.MergeMeshes(currentPool);
  25408. }
  25409. return true;
  25410. };
  25411. }
  25412. return MergeMeshesOptimization;
  25413. })(SceneOptimization);
  25414. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  25415. // Options
  25416. var SceneOptimizerOptions = (function () {
  25417. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  25418. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  25419. if (trackerDuration === void 0) { trackerDuration = 2000; }
  25420. this.targetFrameRate = targetFrameRate;
  25421. this.trackerDuration = trackerDuration;
  25422. this.optimizations = new Array();
  25423. }
  25424. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  25425. var result = new SceneOptimizerOptions(targetFrameRate);
  25426. var priority = 0;
  25427. result.optimizations.push(new MergeMeshesOptimization(priority));
  25428. result.optimizations.push(new ShadowsOptimization(priority));
  25429. result.optimizations.push(new LensFlaresOptimization(priority));
  25430. // Next priority
  25431. priority++;
  25432. result.optimizations.push(new PostProcessesOptimization(priority));
  25433. result.optimizations.push(new ParticlesOptimization(priority));
  25434. // Next priority
  25435. priority++;
  25436. result.optimizations.push(new TextureOptimization(priority, 1024));
  25437. return result;
  25438. };
  25439. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  25440. var result = new SceneOptimizerOptions(targetFrameRate);
  25441. var priority = 0;
  25442. result.optimizations.push(new MergeMeshesOptimization(priority));
  25443. result.optimizations.push(new ShadowsOptimization(priority));
  25444. result.optimizations.push(new LensFlaresOptimization(priority));
  25445. // Next priority
  25446. priority++;
  25447. result.optimizations.push(new PostProcessesOptimization(priority));
  25448. result.optimizations.push(new ParticlesOptimization(priority));
  25449. // Next priority
  25450. priority++;
  25451. result.optimizations.push(new TextureOptimization(priority, 512));
  25452. // Next priority
  25453. priority++;
  25454. result.optimizations.push(new RenderTargetsOptimization(priority));
  25455. // Next priority
  25456. priority++;
  25457. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  25458. return result;
  25459. };
  25460. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  25461. var result = new SceneOptimizerOptions(targetFrameRate);
  25462. var priority = 0;
  25463. result.optimizations.push(new MergeMeshesOptimization(priority));
  25464. result.optimizations.push(new ShadowsOptimization(priority));
  25465. result.optimizations.push(new LensFlaresOptimization(priority));
  25466. // Next priority
  25467. priority++;
  25468. result.optimizations.push(new PostProcessesOptimization(priority));
  25469. result.optimizations.push(new ParticlesOptimization(priority));
  25470. // Next priority
  25471. priority++;
  25472. result.optimizations.push(new TextureOptimization(priority, 256));
  25473. // Next priority
  25474. priority++;
  25475. result.optimizations.push(new RenderTargetsOptimization(priority));
  25476. // Next priority
  25477. priority++;
  25478. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  25479. return result;
  25480. };
  25481. return SceneOptimizerOptions;
  25482. })();
  25483. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  25484. // Scene optimizer tool
  25485. var SceneOptimizer = (function () {
  25486. function SceneOptimizer() {
  25487. }
  25488. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  25489. // TODO: add an epsilon
  25490. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  25491. if (onSuccess) {
  25492. onSuccess();
  25493. }
  25494. return;
  25495. }
  25496. // Apply current level of optimizations
  25497. var allDone = true;
  25498. var noOptimizationApplied = true;
  25499. for (var index = 0; index < options.optimizations.length; index++) {
  25500. var optimization = options.optimizations[index];
  25501. if (optimization.priority === currentPriorityLevel) {
  25502. noOptimizationApplied = false;
  25503. allDone = allDone && optimization.apply(scene);
  25504. }
  25505. }
  25506. // If no optimization was applied, this is a failure :(
  25507. if (noOptimizationApplied) {
  25508. if (onFailure) {
  25509. onFailure();
  25510. }
  25511. return;
  25512. }
  25513. // If all optimizations were done, move to next level
  25514. if (allDone) {
  25515. currentPriorityLevel++;
  25516. }
  25517. // Let's the system running for a specific amount of time before checking FPS
  25518. scene.executeWhenReady(function () {
  25519. setTimeout(function () {
  25520. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  25521. }, options.trackerDuration);
  25522. });
  25523. };
  25524. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  25525. if (!options) {
  25526. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  25527. }
  25528. // Let's the system running for a specific amount of time before checking FPS
  25529. scene.executeWhenReady(function () {
  25530. setTimeout(function () {
  25531. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  25532. }, options.trackerDuration);
  25533. });
  25534. };
  25535. return SceneOptimizer;
  25536. })();
  25537. BABYLON.SceneOptimizer = SceneOptimizer;
  25538. })(BABYLON || (BABYLON = {}));
  25539. //# sourceMappingURL=babylon.sceneOptimizer.js.mapvar BABYLON;
  25540. (function (BABYLON) {
  25541. var Internals;
  25542. (function (Internals) {
  25543. var MeshLODLevel = (function () {
  25544. function MeshLODLevel(distance, mesh) {
  25545. this.distance = distance;
  25546. this.mesh = mesh;
  25547. }
  25548. return MeshLODLevel;
  25549. })();
  25550. Internals.MeshLODLevel = MeshLODLevel;
  25551. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  25552. })(BABYLON || (BABYLON = {}));
  25553. //# sourceMappingURL=babylon.meshLODLevel.js.mapvar BABYLON;
  25554. (function (BABYLON) {
  25555. var AudioEngine = (function () {
  25556. function AudioEngine() {
  25557. this.audioContext = null;
  25558. this.canUseWebAudio = false;
  25559. this.WarnedWebAudioUnsupported = false;
  25560. try {
  25561. if (typeof AudioContext !== 'undefined') {
  25562. this.audioContext = new AudioContext();
  25563. this.canUseWebAudio = true;
  25564. }
  25565. else if (typeof webkitAudioContext !== 'undefined') {
  25566. this.audioContext = new webkitAudioContext();
  25567. this.canUseWebAudio = true;
  25568. }
  25569. }
  25570. catch (e) {
  25571. this.canUseWebAudio = false;
  25572. BABYLON.Tools.Error("Web Audio: " + e.message);
  25573. }
  25574. // create a global volume gain node
  25575. if (this.canUseWebAudio) {
  25576. this.masterGain = this.audioContext.createGain();
  25577. this.masterGain.gain.value = 1;
  25578. this.masterGain.connect(this.audioContext.destination);
  25579. }
  25580. }
  25581. AudioEngine.prototype.dispose = function () {
  25582. if (this.canUseWebAudio) {
  25583. if (this._connectedAnalyser) {
  25584. this._connectedAnalyser.stopDebugCanvas();
  25585. this._connectedAnalyser.dispose();
  25586. this.masterGain.disconnect();
  25587. this.masterGain.connect(this.audioContext.destination);
  25588. this._connectedAnalyser = null;
  25589. }
  25590. this.masterGain.gain.value = 1;
  25591. }
  25592. this.WarnedWebAudioUnsupported = false;
  25593. };
  25594. AudioEngine.prototype.getGlobalVolume = function () {
  25595. if (this.canUseWebAudio) {
  25596. return this.masterGain.gain.value;
  25597. }
  25598. else {
  25599. return -1;
  25600. }
  25601. };
  25602. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  25603. if (this.canUseWebAudio) {
  25604. this.masterGain.gain.value = newVolume;
  25605. }
  25606. };
  25607. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  25608. if (this._connectedAnalyser) {
  25609. this._connectedAnalyser.stopDebugCanvas();
  25610. }
  25611. this._connectedAnalyser = analyser;
  25612. if (this.canUseWebAudio) {
  25613. this.masterGain.disconnect();
  25614. this._connectedAnalyser.connectAudioNodes(this.masterGain, this.audioContext.destination);
  25615. }
  25616. };
  25617. return AudioEngine;
  25618. })();
  25619. BABYLON.AudioEngine = AudioEngine;
  25620. })(BABYLON || (BABYLON = {}));
  25621. //# sourceMappingURL=babylon.audioengine.js.mapvar BABYLON;
  25622. (function (BABYLON) {
  25623. var Sound = (function () {
  25624. /**
  25625. * Create a sound and attach it to a scene
  25626. * @param name Name of your sound
  25627. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  25628. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  25629. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel
  25630. */
  25631. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  25632. var _this = this;
  25633. this.autoplay = false;
  25634. this.loop = false;
  25635. this.useCustomAttenuation = false;
  25636. this.spatialSound = false;
  25637. this.refDistance = 1;
  25638. this.rolloffFactor = 1;
  25639. this.maxDistance = 100;
  25640. this.distanceModel = "linear";
  25641. this.panningModel = "HRTF";
  25642. this._playbackRate = 1;
  25643. this._startTime = 0;
  25644. this._startOffset = 0;
  25645. this._position = BABYLON.Vector3.Zero();
  25646. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  25647. this._volume = 1;
  25648. this._isLoaded = false;
  25649. this._isReadyToPlay = false;
  25650. this._isPlaying = false;
  25651. this._isDirectional = false;
  25652. // Used if you'd like to create a directional sound.
  25653. // If not set, the sound will be omnidirectional
  25654. this._coneInnerAngle = 360;
  25655. this._coneOuterAngle = 360;
  25656. this._coneOuterGain = 0;
  25657. this.name = name;
  25658. this._scene = scene;
  25659. this._readyToPlayCallback = readyToPlayCallback;
  25660. // Default custom attenuation function is a linear attenuation
  25661. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  25662. if (currentDistance < maxDistance) {
  25663. return currentVolume * (1 - currentDistance / maxDistance);
  25664. }
  25665. else {
  25666. return 0;
  25667. }
  25668. };
  25669. if (options) {
  25670. this.autoplay = options.autoplay || false;
  25671. this.loop = options.loop || false;
  25672. // if volume === 0, we need another way to check this option
  25673. if (options.volume !== undefined) {
  25674. this._volume = options.volume;
  25675. }
  25676. this.spatialSound = options.spatialSound || false;
  25677. this.maxDistance = options.maxDistance || 100;
  25678. this.useCustomAttenuation = options.useCustomAttenuation || false;
  25679. this.rolloffFactor = options.rolloffFactor || 1;
  25680. this.refDistance = options.refDistance || 1;
  25681. this.distanceModel = options.distanceModel || "linear";
  25682. this.panningModel = options.panningModel || "HRTF";
  25683. this._playbackRate = options.playbackRate || 1;
  25684. }
  25685. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  25686. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  25687. this._soundGain.gain.value = this._volume;
  25688. this._inputAudioNode = this._soundGain;
  25689. this._ouputAudioNode = this._soundGain;
  25690. if (this.spatialSound) {
  25691. this._createSpatialParameters();
  25692. }
  25693. this._scene.mainSoundTrack.AddSound(this);
  25694. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  25695. if (urlOrArrayBuffer) {
  25696. // If it's an URL
  25697. if (typeof (urlOrArrayBuffer) === "string") {
  25698. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) {
  25699. _this._soundLoaded(data);
  25700. }, null, null, true);
  25701. }
  25702. else {
  25703. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  25704. this._soundLoaded(urlOrArrayBuffer);
  25705. }
  25706. else {
  25707. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  25708. }
  25709. }
  25710. }
  25711. }
  25712. else {
  25713. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  25714. this._scene.mainSoundTrack.AddSound(this);
  25715. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  25716. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  25717. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  25718. }
  25719. }
  25720. }
  25721. Sound.prototype.dispose = function () {
  25722. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  25723. if (this._isPlaying) {
  25724. this.stop();
  25725. }
  25726. this._isReadyToPlay = false;
  25727. if (this.soundTrackId === -1) {
  25728. this._scene.mainSoundTrack.RemoveSound(this);
  25729. }
  25730. else {
  25731. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  25732. }
  25733. this._soundGain.disconnect();
  25734. this._soundSource.disconnect();
  25735. if (this._soundPanner) {
  25736. this._soundPanner.disconnect();
  25737. this._soundPanner = null;
  25738. }
  25739. this._audioBuffer = null;
  25740. this._soundGain = null;
  25741. this._soundSource = null;
  25742. if (this._connectedMesh) {
  25743. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  25744. this._connectedMesh = null;
  25745. }
  25746. }
  25747. };
  25748. Sound.prototype._soundLoaded = function (audioData) {
  25749. var _this = this;
  25750. this._isLoaded = true;
  25751. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  25752. _this._audioBuffer = buffer;
  25753. _this._isReadyToPlay = true;
  25754. if (_this.autoplay) {
  25755. _this.play();
  25756. }
  25757. if (_this._readyToPlayCallback) {
  25758. _this._readyToPlayCallback();
  25759. }
  25760. }, function (error) {
  25761. BABYLON.Tools.Error("Error while decoding audio data: " + error.err);
  25762. });
  25763. };
  25764. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  25765. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  25766. this._audioBuffer = audioBuffer;
  25767. this._isReadyToPlay = true;
  25768. }
  25769. };
  25770. Sound.prototype.updateOptions = function (options) {
  25771. if (options) {
  25772. this.loop = options.loop || this.loop;
  25773. this.maxDistance = options.maxDistance || this.maxDistance;
  25774. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  25775. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  25776. this.refDistance = options.refDistance || this.refDistance;
  25777. this.distanceModel = options.distanceModel || this.distanceModel;
  25778. this.panningModel = options.panningModel || this.panningModel;
  25779. this._playbackRate = options.playbackRate || this._playbackRate;
  25780. }
  25781. };
  25782. Sound.prototype._createSpatialParameters = function () {
  25783. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  25784. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  25785. if (this.useCustomAttenuation) {
  25786. // Tricks to disable in a way embedded Web Audio attenuation
  25787. this._soundPanner.distanceModel = "linear";
  25788. this._soundPanner.maxDistance = Number.MAX_VALUE;
  25789. this._soundPanner.refDistance = 1;
  25790. this._soundPanner.rolloffFactor = 1;
  25791. this._soundPanner.panningModel = "HRTF";
  25792. }
  25793. else {
  25794. this._soundPanner.distanceModel = this.distanceModel;
  25795. this._soundPanner.maxDistance = this.maxDistance;
  25796. this._soundPanner.refDistance = this.refDistance;
  25797. this._soundPanner.rolloffFactor = this.rolloffFactor;
  25798. this._soundPanner.panningModel = this.panningModel;
  25799. }
  25800. this._soundPanner.connect(this._ouputAudioNode);
  25801. this._inputAudioNode = this._soundPanner;
  25802. }
  25803. };
  25804. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  25805. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  25806. this._ouputAudioNode.disconnect();
  25807. this._ouputAudioNode.connect(soundTrackAudioNode);
  25808. }
  25809. };
  25810. /**
  25811. * Transform this sound into a directional source
  25812. * @param coneInnerAngle Size of the inner cone in degree
  25813. * @param coneOuterAngle Size of the outer cone in degree
  25814. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  25815. */
  25816. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  25817. if (coneOuterAngle < coneInnerAngle) {
  25818. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  25819. return;
  25820. }
  25821. this._coneInnerAngle = coneInnerAngle;
  25822. this._coneOuterAngle = coneOuterAngle;
  25823. this._coneOuterGain = coneOuterGain;
  25824. this._isDirectional = true;
  25825. if (this._isPlaying && this.loop) {
  25826. this.stop();
  25827. this.play();
  25828. }
  25829. };
  25830. Sound.prototype.setPosition = function (newPosition) {
  25831. this._position = newPosition;
  25832. if (this._isPlaying && this.spatialSound) {
  25833. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  25834. }
  25835. };
  25836. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  25837. this._localDirection = newLocalDirection;
  25838. if (this._connectedMesh && this._isPlaying) {
  25839. this._updateDirection();
  25840. }
  25841. };
  25842. Sound.prototype._updateDirection = function () {
  25843. var mat = this._connectedMesh.getWorldMatrix();
  25844. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  25845. direction.normalize();
  25846. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  25847. };
  25848. Sound.prototype.updateDistanceFromListener = function () {
  25849. if (this._connectedMesh && this.useCustomAttenuation) {
  25850. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  25851. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  25852. }
  25853. };
  25854. Sound.prototype.setAttenuationFunction = function (callback) {
  25855. this._customAttenuationFunction = callback;
  25856. };
  25857. /**
  25858. * Play the sound
  25859. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  25860. */
  25861. Sound.prototype.play = function (time) {
  25862. if (this._isReadyToPlay) {
  25863. try {
  25864. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : 0;
  25865. if (!this._soundSource) {
  25866. if (this.spatialSound) {
  25867. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  25868. if (this._isDirectional) {
  25869. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  25870. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  25871. this._soundPanner.coneOuterGain = this._coneOuterGain;
  25872. if (this._connectedMesh) {
  25873. this._updateDirection();
  25874. }
  25875. else {
  25876. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  25877. }
  25878. }
  25879. }
  25880. }
  25881. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  25882. this._soundSource.buffer = this._audioBuffer;
  25883. this._soundSource.connect(this._inputAudioNode);
  25884. this._soundSource.loop = this.loop;
  25885. this._soundSource.playbackRate.value = this._playbackRate;
  25886. this._startTime = startTime;
  25887. if (this.onended) {
  25888. this._soundSource.onended = this.onended;
  25889. }
  25890. this._soundSource.start(startTime, this._startOffset % this._soundSource.buffer.duration);
  25891. this._isPlaying = true;
  25892. }
  25893. catch (ex) {
  25894. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  25895. }
  25896. }
  25897. };
  25898. /**
  25899. * Stop the sound
  25900. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  25901. */
  25902. Sound.prototype.stop = function (time) {
  25903. if (this._isPlaying) {
  25904. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : 0;
  25905. this._soundSource.stop(stopTime);
  25906. this._isPlaying = false;
  25907. }
  25908. };
  25909. Sound.prototype.pause = function () {
  25910. if (this._isPlaying) {
  25911. this._soundSource.stop(0);
  25912. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  25913. }
  25914. };
  25915. Sound.prototype.setVolume = function (newVolume, time) {
  25916. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  25917. if (time) {
  25918. this._soundGain.gain.linearRampToValueAtTime(this._volume, BABYLON.Engine.audioEngine.audioContext.currentTime);
  25919. this._soundGain.gain.linearRampToValueAtTime(newVolume, time);
  25920. }
  25921. else {
  25922. this._soundGain.gain.value = newVolume;
  25923. }
  25924. }
  25925. this._volume = newVolume;
  25926. };
  25927. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  25928. this._playbackRate = newPlaybackRate;
  25929. if (this._isPlaying) {
  25930. this._soundSource.playbackRate.value = this._playbackRate;
  25931. }
  25932. };
  25933. Sound.prototype.getVolume = function () {
  25934. return this._volume;
  25935. };
  25936. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  25937. var _this = this;
  25938. this._connectedMesh = meshToConnectTo;
  25939. if (!this.spatialSound) {
  25940. this._createSpatialParameters();
  25941. this.spatialSound = true;
  25942. if (this._isPlaying && this.loop) {
  25943. this.stop();
  25944. this.play();
  25945. }
  25946. }
  25947. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  25948. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  25949. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  25950. };
  25951. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  25952. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  25953. if (this._isDirectional && this._isPlaying) {
  25954. this._updateDirection();
  25955. }
  25956. };
  25957. return Sound;
  25958. })();
  25959. BABYLON.Sound = Sound;
  25960. })(BABYLON || (BABYLON = {}));
  25961. //# sourceMappingURL=babylon.sound.js.mapvar BABYLON;
  25962. (function (BABYLON) {
  25963. var SoundTrack = (function () {
  25964. function SoundTrack(scene, options) {
  25965. this.id = -1;
  25966. this._isMainTrack = false;
  25967. this._scene = scene;
  25968. this._audioEngine = BABYLON.Engine.audioEngine;
  25969. this.soundCollection = new Array();
  25970. if (this._audioEngine.canUseWebAudio) {
  25971. this._trackGain = this._audioEngine.audioContext.createGain();
  25972. this._trackGain.connect(this._audioEngine.masterGain);
  25973. if (options) {
  25974. if (options.volume) {
  25975. this._trackGain.gain.value = options.volume;
  25976. }
  25977. if (options.mainTrack) {
  25978. this._isMainTrack = options.mainTrack;
  25979. }
  25980. }
  25981. }
  25982. if (!this._isMainTrack) {
  25983. this._scene.soundTracks.push(this);
  25984. this.id = this._scene.soundTracks.length - 1;
  25985. }
  25986. }
  25987. SoundTrack.prototype.dispose = function () {
  25988. if (this._audioEngine.canUseWebAudio) {
  25989. if (this._connectedAnalyser) {
  25990. this._connectedAnalyser.stopDebugCanvas();
  25991. }
  25992. while (this.soundCollection.length) {
  25993. this.soundCollection[0].dispose();
  25994. }
  25995. this._trackGain.disconnect();
  25996. this._trackGain = null;
  25997. }
  25998. };
  25999. SoundTrack.prototype.AddSound = function (sound) {
  26000. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  26001. sound.connectToSoundTrackAudioNode(this._trackGain);
  26002. }
  26003. if (sound.soundTrackId) {
  26004. if (sound.soundTrackId === -1) {
  26005. this._scene.mainSoundTrack.RemoveSound(sound);
  26006. }
  26007. else {
  26008. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  26009. }
  26010. }
  26011. this.soundCollection.push(sound);
  26012. sound.soundTrackId = this.id;
  26013. };
  26014. SoundTrack.prototype.RemoveSound = function (sound) {
  26015. var index = this.soundCollection.indexOf(sound);
  26016. if (index !== -1) {
  26017. this.soundCollection.splice(index, 1);
  26018. }
  26019. };
  26020. SoundTrack.prototype.setVolume = function (newVolume) {
  26021. if (this._audioEngine.canUseWebAudio) {
  26022. this._trackGain.gain.value = newVolume;
  26023. }
  26024. };
  26025. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  26026. if (this._connectedAnalyser) {
  26027. this._connectedAnalyser.stopDebugCanvas();
  26028. }
  26029. this._connectedAnalyser = analyser;
  26030. if (this._audioEngine.canUseWebAudio) {
  26031. this._trackGain.disconnect();
  26032. this._connectedAnalyser.connectAudioNodes(this._trackGain, this._audioEngine.masterGain);
  26033. }
  26034. };
  26035. return SoundTrack;
  26036. })();
  26037. BABYLON.SoundTrack = SoundTrack;
  26038. })(BABYLON || (BABYLON = {}));
  26039. //# sourceMappingURL=babylon.soundtrack.js.mapvar BABYLON;
  26040. (function (BABYLON) {
  26041. var DebugLayer = (function () {
  26042. function DebugLayer(scene) {
  26043. var _this = this;
  26044. this._enabled = false;
  26045. this._labelsEnabled = false;
  26046. this._displayStatistics = true;
  26047. this._displayTree = false;
  26048. this._displayLogs = false;
  26049. this._identityMatrix = BABYLON.Matrix.Identity();
  26050. this.axisRatio = 0.02;
  26051. this.accentColor = "orange";
  26052. this._scene = scene;
  26053. this._syncPositions = function () {
  26054. var engine = _this._scene.getEngine();
  26055. var canvasRect = engine.getRenderingCanvasClientRect();
  26056. if (_this._showUI) {
  26057. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  26058. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  26059. _this._statsDiv.style.width = "400px";
  26060. _this._statsDiv.style.height = "auto";
  26061. _this._statsSubsetDiv.style.maxHeight = "240px";
  26062. _this._optionsDiv.style.left = "0px";
  26063. _this._optionsDiv.style.top = "10px";
  26064. _this._optionsDiv.style.width = "200px";
  26065. _this._optionsDiv.style.height = "auto";
  26066. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  26067. _this._logDiv.style.left = "0px";
  26068. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  26069. _this._logDiv.style.width = "600px";
  26070. _this._logDiv.style.height = "160px";
  26071. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  26072. _this._treeDiv.style.top = "10px";
  26073. _this._treeDiv.style.width = "300px";
  26074. _this._treeDiv.style.height = "auto";
  26075. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  26076. }
  26077. _this._globalDiv.style.left = canvasRect.left + "px";
  26078. _this._globalDiv.style.top = canvasRect.top + "px";
  26079. _this._drawingCanvas.style.left = "0px";
  26080. _this._drawingCanvas.style.top = "0px";
  26081. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  26082. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  26083. var devicePixelRatio = window.devicePixelRatio || 1;
  26084. var context = _this._drawingContext;
  26085. var backingStoreRatio = context.webkitBackingStorePixelRatio || context.mozBackingStorePixelRatio || context.msBackingStorePixelRatio || context.oBackingStorePixelRatio || context.backingStorePixelRatio || 1;
  26086. _this._ratio = devicePixelRatio / backingStoreRatio;
  26087. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  26088. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  26089. };
  26090. this._onCanvasClick = function (evt) {
  26091. _this._clickPosition = {
  26092. x: evt.clientX * _this._ratio,
  26093. y: evt.clientY * _this._ratio
  26094. };
  26095. };
  26096. this._syncData = function () {
  26097. if (_this._showUI) {
  26098. if (_this._displayStatistics) {
  26099. _this._displayStats();
  26100. _this._statsDiv.style.display = "";
  26101. }
  26102. else {
  26103. _this._statsDiv.style.display = "none";
  26104. }
  26105. if (_this._displayLogs) {
  26106. _this._logDiv.style.display = "";
  26107. }
  26108. else {
  26109. _this._logDiv.style.display = "none";
  26110. }
  26111. if (_this._displayTree) {
  26112. _this._treeDiv.style.display = "";
  26113. if (_this._needToRefreshMeshesTree) {
  26114. _this._needToRefreshMeshesTree = false;
  26115. _this._refreshMeshesTreeContent();
  26116. }
  26117. }
  26118. else {
  26119. _this._treeDiv.style.display = "none";
  26120. }
  26121. }
  26122. if (_this._labelsEnabled || !_this._showUI) {
  26123. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  26124. var engine = _this._scene.getEngine();
  26125. var viewport = _this._scene.activeCamera.viewport;
  26126. var globalViewport = viewport.toGlobal(engine);
  26127. // Meshes
  26128. var meshes = _this._scene.getActiveMeshes();
  26129. for (var index = 0; index < meshes.length; index++) {
  26130. var mesh = meshes.data[index];
  26131. var position = mesh.getBoundingInfo().boundingSphere.center;
  26132. var projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._scene.getTransformMatrix(), globalViewport);
  26133. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  26134. _this._renderAxis(projectedPosition, mesh, globalViewport);
  26135. }
  26136. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  26137. _this._renderLabel(mesh.name, projectedPosition, 12, function () {
  26138. mesh.renderOverlay = !mesh.renderOverlay;
  26139. }, function () {
  26140. return mesh.renderOverlay ? 'red' : 'black';
  26141. });
  26142. }
  26143. }
  26144. // Cameras
  26145. var cameras = _this._scene.cameras;
  26146. for (index = 0; index < cameras.length; index++) {
  26147. var camera = cameras[index];
  26148. if (camera === _this._scene.activeCamera) {
  26149. continue;
  26150. }
  26151. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._scene.getTransformMatrix(), globalViewport);
  26152. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  26153. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  26154. _this._scene.activeCamera.detachControl(engine.getRenderingCanvas());
  26155. _this._scene.activeCamera = camera;
  26156. _this._scene.activeCamera.attachControl(engine.getRenderingCanvas());
  26157. }, function () {
  26158. return "purple";
  26159. });
  26160. }
  26161. }
  26162. // Lights
  26163. var lights = _this._scene.lights;
  26164. for (index = 0; index < lights.length; index++) {
  26165. var light = lights[index];
  26166. if (light.position) {
  26167. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._scene.getTransformMatrix(), globalViewport);
  26168. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  26169. _this._renderLabel(light.name, projectedPosition, -20, function () {
  26170. light.setEnabled(!light.isEnabled());
  26171. }, function () {
  26172. return light.isEnabled() ? "orange" : "gray";
  26173. });
  26174. }
  26175. }
  26176. }
  26177. }
  26178. _this._clickPosition = undefined;
  26179. };
  26180. }
  26181. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  26182. while (this._treeSubsetDiv.hasChildNodes()) {
  26183. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  26184. }
  26185. // Add meshes
  26186. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  26187. sortedArray.sort(function (a, b) {
  26188. if (a.name === b.name) {
  26189. return 0;
  26190. }
  26191. return (a.name > b.name) ? 1 : -1;
  26192. });
  26193. for (var index = 0; index < sortedArray.length; index++) {
  26194. var mesh = sortedArray[index];
  26195. if (!mesh.isEnabled()) {
  26196. continue;
  26197. }
  26198. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  26199. m.isVisible = element.checked;
  26200. }, mesh);
  26201. }
  26202. };
  26203. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  26204. this._drawingContext.beginPath();
  26205. this._drawingContext.moveTo(zero.x, zero.y);
  26206. this._drawingContext.lineTo(unit.x, unit.y);
  26207. this._drawingContext.strokeStyle = color;
  26208. this._drawingContext.lineWidth = 4;
  26209. this._drawingContext.stroke();
  26210. this._drawingContext.font = "normal 14px Segoe UI";
  26211. this._drawingContext.fillStyle = color;
  26212. this._drawingContext.fillText(label, unitText.x, unitText.y);
  26213. };
  26214. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  26215. var position = mesh.getBoundingInfo().boundingSphere.center;
  26216. var worldMatrix = mesh.getWorldMatrix();
  26217. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._scene.getTransformMatrix());
  26218. var unit = (unprojectedVector.subtract(position)).length();
  26219. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  26220. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  26221. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  26222. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  26223. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  26224. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  26225. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  26226. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  26227. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  26228. };
  26229. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  26230. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  26231. this._drawingContext.font = "normal 12px Segoe UI";
  26232. var textMetrics = this._drawingContext.measureText(text);
  26233. var centerX = projectedPosition.x - textMetrics.width / 2;
  26234. var centerY = projectedPosition.y;
  26235. if (this._isClickInsideRect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  26236. onClick();
  26237. }
  26238. this._drawingContext.beginPath();
  26239. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  26240. this._drawingContext.fillStyle = getFillStyle();
  26241. this._drawingContext.globalAlpha = 0.5;
  26242. this._drawingContext.fill();
  26243. this._drawingContext.globalAlpha = 1.0;
  26244. this._drawingContext.strokeStyle = '#FFFFFF';
  26245. this._drawingContext.lineWidth = 1;
  26246. this._drawingContext.stroke();
  26247. this._drawingContext.fillStyle = "#FFFFFF";
  26248. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  26249. this._drawingContext.beginPath();
  26250. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  26251. this._drawingContext.fill();
  26252. }
  26253. };
  26254. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  26255. if (!this._clickPosition) {
  26256. return false;
  26257. }
  26258. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  26259. return false;
  26260. }
  26261. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  26262. return false;
  26263. }
  26264. return true;
  26265. };
  26266. DebugLayer.prototype.isVisible = function () {
  26267. return this._enabled;
  26268. };
  26269. DebugLayer.prototype.hide = function () {
  26270. if (!this._enabled) {
  26271. return;
  26272. }
  26273. this._enabled = false;
  26274. var engine = this._scene.getEngine();
  26275. this._scene.unregisterAfterRender(this._syncData);
  26276. document.body.removeChild(this._globalDiv);
  26277. window.removeEventListener("resize", this._syncPositions);
  26278. this._scene.forceShowBoundingBoxes = false;
  26279. this._scene.forceWireframe = false;
  26280. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  26281. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  26282. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  26283. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  26284. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  26285. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  26286. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  26287. this._scene.shadowsEnabled = true;
  26288. this._scene.particlesEnabled = true;
  26289. this._scene.postProcessesEnabled = true;
  26290. this._scene.collisionsEnabled = true;
  26291. this._scene.lightsEnabled = true;
  26292. this._scene.texturesEnabled = true;
  26293. this._scene.lensFlaresEnabled = true;
  26294. this._scene.proceduralTexturesEnabled = true;
  26295. this._scene.renderTargetsEnabled = true;
  26296. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  26297. };
  26298. DebugLayer.prototype.show = function (showUI) {
  26299. if (showUI === void 0) { showUI = true; }
  26300. if (this._enabled) {
  26301. return;
  26302. }
  26303. this._enabled = true;
  26304. this._showUI = showUI;
  26305. var engine = this._scene.getEngine();
  26306. this._globalDiv = document.createElement("div");
  26307. document.body.appendChild(this._globalDiv);
  26308. this._generateDOMelements();
  26309. window.addEventListener("resize", this._syncPositions);
  26310. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  26311. this._syncPositions();
  26312. this._scene.registerAfterRender(this._syncData);
  26313. };
  26314. DebugLayer.prototype._clearLabels = function () {
  26315. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  26316. for (var index = 0; index < this._scene.meshes.length; index++) {
  26317. var mesh = this._scene.meshes[index];
  26318. mesh.renderOverlay = false;
  26319. }
  26320. };
  26321. DebugLayer.prototype._generateheader = function (root, text) {
  26322. var header = document.createElement("div");
  26323. header.innerHTML = text + "&nbsp;";
  26324. header.style.textAlign = "right";
  26325. header.style.width = "100%";
  26326. header.style.color = "white";
  26327. header.style.backgroundColor = "Black";
  26328. header.style.padding = "5px 5px 4px 0px";
  26329. header.style.marginLeft = "-5px";
  26330. header.style.fontWeight = "bold";
  26331. root.appendChild(header);
  26332. };
  26333. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  26334. var label = document.createElement("label");
  26335. label.innerHTML = title;
  26336. label.style.color = color;
  26337. root.appendChild(label);
  26338. root.appendChild(document.createElement("br"));
  26339. };
  26340. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  26341. if (tag === void 0) { tag = null; }
  26342. var label = document.createElement("label");
  26343. var boundingBoxesCheckbox = document.createElement("input");
  26344. boundingBoxesCheckbox.type = "checkbox";
  26345. boundingBoxesCheckbox.checked = initialState;
  26346. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  26347. task(evt.target, tag);
  26348. });
  26349. label.appendChild(boundingBoxesCheckbox);
  26350. var container = document.createElement("span");
  26351. var leftPart = document.createElement("span");
  26352. var rightPart = document.createElement("span");
  26353. rightPart.style.cssFloat = "right";
  26354. leftPart.innerHTML = leftTitle;
  26355. rightPart.innerHTML = rightTitle;
  26356. rightPart.style.fontSize = "12px";
  26357. rightPart.style.maxWidth = "200px";
  26358. container.appendChild(leftPart);
  26359. container.appendChild(rightPart);
  26360. label.appendChild(container);
  26361. root.appendChild(label);
  26362. root.appendChild(document.createElement("br"));
  26363. };
  26364. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  26365. if (tag === void 0) { tag = null; }
  26366. var label = document.createElement("label");
  26367. var boundingBoxesCheckbox = document.createElement("input");
  26368. boundingBoxesCheckbox.type = "checkbox";
  26369. boundingBoxesCheckbox.checked = initialState;
  26370. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  26371. task(evt.target, tag);
  26372. });
  26373. label.appendChild(boundingBoxesCheckbox);
  26374. label.appendChild(document.createTextNode(title));
  26375. root.appendChild(label);
  26376. root.appendChild(document.createElement("br"));
  26377. };
  26378. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  26379. if (tag === void 0) { tag = null; }
  26380. var label = document.createElement("label");
  26381. var boundingBoxesRadio = document.createElement("input");
  26382. boundingBoxesRadio.type = "radio";
  26383. boundingBoxesRadio.name = name;
  26384. boundingBoxesRadio.checked = initialState;
  26385. boundingBoxesRadio.addEventListener("change", function (evt) {
  26386. task(evt.target, tag);
  26387. });
  26388. label.appendChild(boundingBoxesRadio);
  26389. label.appendChild(document.createTextNode(title));
  26390. root.appendChild(label);
  26391. root.appendChild(document.createElement("br"));
  26392. };
  26393. DebugLayer.prototype._generateDOMelements = function () {
  26394. var _this = this;
  26395. this._globalDiv.id = "DebugLayer";
  26396. this._globalDiv.style.position = "absolute";
  26397. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  26398. this._globalDiv.style.fontSize = "14px";
  26399. this._globalDiv.style.color = "white";
  26400. // Drawing canvas
  26401. this._drawingCanvas = document.createElement("canvas");
  26402. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  26403. this._drawingCanvas.style.position = "absolute";
  26404. this._drawingCanvas.style.pointerEvents = "none";
  26405. this._drawingContext = this._drawingCanvas.getContext("2d");
  26406. this._globalDiv.appendChild(this._drawingCanvas);
  26407. if (this._showUI) {
  26408. var background = "rgba(128, 128, 128, 0.4)";
  26409. var border = "rgb(180, 180, 180) solid 1px";
  26410. // Stats
  26411. this._statsDiv = document.createElement("div");
  26412. this._statsDiv.id = "DebugLayerStats";
  26413. this._statsDiv.style.border = border;
  26414. this._statsDiv.style.position = "absolute";
  26415. this._statsDiv.style.background = background;
  26416. this._statsDiv.style.padding = "0px 0px 0px 5px";
  26417. this._generateheader(this._statsDiv, "STATISTICS");
  26418. this._statsSubsetDiv = document.createElement("div");
  26419. this._statsSubsetDiv.style.paddingTop = "5px";
  26420. this._statsSubsetDiv.style.paddingBottom = "5px";
  26421. this._statsSubsetDiv.style.overflowY = "auto";
  26422. this._statsDiv.appendChild(this._statsSubsetDiv);
  26423. // Tree
  26424. this._treeDiv = document.createElement("div");
  26425. this._treeDiv.id = "DebugLayerTree";
  26426. this._treeDiv.style.border = border;
  26427. this._treeDiv.style.position = "absolute";
  26428. this._treeDiv.style.background = background;
  26429. this._treeDiv.style.padding = "0px 0px 0px 5px";
  26430. this._treeDiv.style.display = "none";
  26431. this._generateheader(this._treeDiv, "MESHES TREE");
  26432. this._treeSubsetDiv = document.createElement("div");
  26433. this._treeSubsetDiv.style.paddingTop = "5px";
  26434. this._treeSubsetDiv.style.paddingRight = "5px";
  26435. this._treeSubsetDiv.style.overflowY = "auto";
  26436. this._treeSubsetDiv.style.maxHeight = "300px";
  26437. this._treeDiv.appendChild(this._treeSubsetDiv);
  26438. this._needToRefreshMeshesTree = true;
  26439. // Logs
  26440. this._logDiv = document.createElement("div");
  26441. this._logDiv.style.border = border;
  26442. this._logDiv.id = "DebugLayerLogs";
  26443. this._logDiv.style.position = "absolute";
  26444. this._logDiv.style.background = background;
  26445. this._logDiv.style.padding = "0px 0px 0px 5px";
  26446. this._logDiv.style.display = "none";
  26447. this._generateheader(this._logDiv, "LOGS");
  26448. this._logSubsetDiv = document.createElement("div");
  26449. this._logSubsetDiv.style.height = "127px";
  26450. this._logSubsetDiv.style.paddingTop = "5px";
  26451. this._logSubsetDiv.style.overflowY = "auto";
  26452. this._logSubsetDiv.style.fontSize = "12px";
  26453. this._logSubsetDiv.style.fontFamily = "consolas";
  26454. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  26455. this._logDiv.appendChild(this._logSubsetDiv);
  26456. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  26457. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  26458. };
  26459. // Options
  26460. this._optionsDiv = document.createElement("div");
  26461. this._optionsDiv.id = "DebugLayerOptions";
  26462. this._optionsDiv.style.border = border;
  26463. this._optionsDiv.style.position = "absolute";
  26464. this._optionsDiv.style.background = background;
  26465. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  26466. this._optionsDiv.style.overflowY = "auto";
  26467. this._generateheader(this._optionsDiv, "OPTIONS");
  26468. this._optionsSubsetDiv = document.createElement("div");
  26469. this._optionsSubsetDiv.style.paddingTop = "5px";
  26470. this._optionsSubsetDiv.style.paddingBottom = "5px";
  26471. this._optionsSubsetDiv.style.overflowY = "auto";
  26472. this._optionsSubsetDiv.style.maxHeight = "200px";
  26473. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  26474. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  26475. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) {
  26476. _this._displayStatistics = element.checked;
  26477. });
  26478. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) {
  26479. _this._displayLogs = element.checked;
  26480. });
  26481. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  26482. _this._displayTree = element.checked;
  26483. _this._needToRefreshMeshesTree = true;
  26484. });
  26485. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  26486. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  26487. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) {
  26488. _this._scene.forceShowBoundingBoxes = element.checked;
  26489. });
  26490. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  26491. _this._labelsEnabled = element.checked;
  26492. if (!_this._labelsEnabled) {
  26493. _this._clearLabels();
  26494. }
  26495. });
  26496. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  26497. if (element.checked) {
  26498. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  26499. }
  26500. else {
  26501. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  26502. }
  26503. });
  26504. ;
  26505. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  26506. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  26507. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  26508. if (element.checked) {
  26509. _this._scene.forceWireframe = false;
  26510. _this._scene.forcePointsCloud = false;
  26511. }
  26512. });
  26513. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  26514. if (element.checked) {
  26515. _this._scene.forceWireframe = true;
  26516. _this._scene.forcePointsCloud = false;
  26517. }
  26518. });
  26519. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  26520. if (element.checked) {
  26521. _this._scene.forceWireframe = false;
  26522. _this._scene.forcePointsCloud = true;
  26523. }
  26524. });
  26525. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  26526. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  26527. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) {
  26528. BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked;
  26529. });
  26530. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) {
  26531. BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked;
  26532. });
  26533. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) {
  26534. BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked;
  26535. });
  26536. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) {
  26537. BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked;
  26538. });
  26539. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) {
  26540. BABYLON.StandardMaterial.BumpTextureEnabled = element.checked;
  26541. });
  26542. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) {
  26543. BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked;
  26544. });
  26545. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) {
  26546. BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked;
  26547. });
  26548. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) {
  26549. BABYLON.StandardMaterial.FresnelEnabled = element.checked;
  26550. });
  26551. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  26552. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  26553. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) {
  26554. _this._scene.animationsEnabled = element.checked;
  26555. });
  26556. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) {
  26557. _this._scene.collisionsEnabled = element.checked;
  26558. });
  26559. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) {
  26560. _this._scene.fogEnabled = element.checked;
  26561. });
  26562. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) {
  26563. _this._scene.lensFlaresEnabled = element.checked;
  26564. });
  26565. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) {
  26566. _this._scene.lightsEnabled = element.checked;
  26567. });
  26568. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) {
  26569. _this._scene.particlesEnabled = element.checked;
  26570. });
  26571. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) {
  26572. _this._scene.postProcessesEnabled = element.checked;
  26573. });
  26574. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) {
  26575. _this._scene.proceduralTexturesEnabled = element.checked;
  26576. });
  26577. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) {
  26578. _this._scene.renderTargetsEnabled = element.checked;
  26579. });
  26580. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) {
  26581. _this._scene.shadowsEnabled = element.checked;
  26582. });
  26583. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) {
  26584. _this._scene.skeletonsEnabled = element.checked;
  26585. });
  26586. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) {
  26587. _this._scene.texturesEnabled = element.checked;
  26588. });
  26589. this._globalDiv.appendChild(this._statsDiv);
  26590. this._globalDiv.appendChild(this._logDiv);
  26591. this._globalDiv.appendChild(this._optionsDiv);
  26592. this._globalDiv.appendChild(this._treeDiv);
  26593. }
  26594. };
  26595. DebugLayer.prototype._displayStats = function () {
  26596. var scene = this._scene;
  26597. var engine = scene.getEngine();
  26598. var glInfo = engine.getGlInfo();
  26599. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>" + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>" + "<b>Count</b><br>" + "Total meshes: " + scene.meshes.length + "<br>" + "Total vertices: " + scene.getTotalVertices() + "<br>" + "Total materials: " + scene.materials.length + "<br>" + "Total textures: " + scene.textures.length + "<br>" + "Active meshes: " + scene.getActiveMeshes().length + "<br>" + "Active vertices: " + scene.getActiveVertices() + "<br>" + "Active bones: " + scene.getActiveBones() + "<br>" + "Active particles: " + scene.getActiveParticles() + "<br>" + "<b>Draw calls: " + engine.drawCalls + "</b><br><br>" + "<b>Duration</b><br>" + "Meshes selection:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>" + "Render Targets: " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>" + "Particles: " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>" + "Sprites: " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br><br>" + "Render: <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b><br>" + "Frame: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>" + "Potential FPS: " + BABYLON.Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br><br>" + "</div>" + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>" + "<b>Extensions</b><br>" + "Std derivatives: " + (engine.getCaps().standardDerivatives ? "Yes" : "No") + "<br>" + "Compressed textures: " + (engine.getCaps().s3tc ? "Yes" : "No") + "<br>" + "Hardware instances: " + (engine.getCaps().instancedArrays ? "Yes" : "No") + "<br>" + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br>" + "32bits indices: " + (engine.getCaps().uintIndices ? "Yes" : "No") + "<br>" + "<b>Caps.</b><br>" + "Max textures units: " + engine.getCaps().maxTexturesImageUnits + "<br>" + "Max textures size: " + engine.getCaps().maxTextureSize + "<br>" + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br><br><br>" + "</div><br>" + "<b>Info</b><br>" + glInfo.version + "<br>" + glInfo.renderer + "<br>";
  26600. if (this.customStatsFunction) {
  26601. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  26602. }
  26603. };
  26604. return DebugLayer;
  26605. })();
  26606. BABYLON.DebugLayer = DebugLayer;
  26607. })(BABYLON || (BABYLON = {}));
  26608. //# sourceMappingURL=babylon.debugLayer.js.map
  26609. var BABYLON;
  26610. (function (BABYLON) {
  26611. var RawTexture = (function (_super) {
  26612. __extends(RawTexture, _super);
  26613. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  26614. if (generateMipMaps === void 0) { generateMipMaps = true; }
  26615. if (invertY === void 0) { invertY = false; }
  26616. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  26617. _super.call(this, null, scene, !generateMipMaps, invertY);
  26618. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  26619. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  26620. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  26621. }
  26622. // Statics
  26623. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  26624. if (generateMipMaps === void 0) { generateMipMaps = true; }
  26625. if (invertY === void 0) { invertY = false; }
  26626. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  26627. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  26628. };
  26629. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  26630. if (generateMipMaps === void 0) { generateMipMaps = true; }
  26631. if (invertY === void 0) { invertY = false; }
  26632. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  26633. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  26634. };
  26635. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  26636. if (generateMipMaps === void 0) { generateMipMaps = true; }
  26637. if (invertY === void 0) { invertY = false; }
  26638. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  26639. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  26640. };
  26641. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  26642. if (generateMipMaps === void 0) { generateMipMaps = true; }
  26643. if (invertY === void 0) { invertY = false; }
  26644. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  26645. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  26646. };
  26647. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  26648. if (generateMipMaps === void 0) { generateMipMaps = true; }
  26649. if (invertY === void 0) { invertY = false; }
  26650. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  26651. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  26652. };
  26653. return RawTexture;
  26654. })(BABYLON.Texture);
  26655. BABYLON.RawTexture = RawTexture;
  26656. })(BABYLON || (BABYLON = {}));
  26657. //# sourceMappingURL=babylon.rawTexture.js.map
  26658. var BABYLON;
  26659. (function (BABYLON) {
  26660. var IndexedVector2 = (function (_super) {
  26661. __extends(IndexedVector2, _super);
  26662. function IndexedVector2(original, index) {
  26663. _super.call(this, original.x, original.y);
  26664. this.index = index;
  26665. }
  26666. return IndexedVector2;
  26667. })(BABYLON.Vector2);
  26668. var PolygonPoints = (function () {
  26669. function PolygonPoints() {
  26670. this.elements = new Array();
  26671. }
  26672. PolygonPoints.prototype.add = function (originalPoints) {
  26673. var _this = this;
  26674. var result = new Array();
  26675. originalPoints.forEach(function (point) {
  26676. if (result.length === 0 || !(BABYLON.Tools.WithinEpsilon(point.x, result[0].x, 0.00001) && BABYLON.Tools.WithinEpsilon(point.y, result[0].y, 0.00001))) {
  26677. var newPoint = new IndexedVector2(point, _this.elements.length);
  26678. result.push(newPoint);
  26679. _this.elements.push(newPoint);
  26680. }
  26681. });
  26682. return result;
  26683. };
  26684. PolygonPoints.prototype.computeBounds = function () {
  26685. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  26686. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  26687. this.elements.forEach(function (point) {
  26688. // x
  26689. if (point.x < lmin.x) {
  26690. lmin.x = point.x;
  26691. }
  26692. else if (point.x > lmax.x) {
  26693. lmax.x = point.x;
  26694. }
  26695. // y
  26696. if (point.y < lmin.y) {
  26697. lmin.y = point.y;
  26698. }
  26699. else if (point.y > lmax.y) {
  26700. lmax.y = point.y;
  26701. }
  26702. });
  26703. return {
  26704. min: lmin,
  26705. max: lmax,
  26706. width: lmax.x - lmin.x,
  26707. height: lmax.y - lmin.y
  26708. };
  26709. };
  26710. return PolygonPoints;
  26711. })();
  26712. var Polygon = (function () {
  26713. function Polygon() {
  26714. }
  26715. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  26716. return [
  26717. new BABYLON.Vector2(xmin, ymin),
  26718. new BABYLON.Vector2(xmax, ymin),
  26719. new BABYLON.Vector2(xmax, ymax),
  26720. new BABYLON.Vector2(xmin, ymax)
  26721. ];
  26722. };
  26723. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  26724. if (cx === void 0) { cx = 0; }
  26725. if (cy === void 0) { cy = 0; }
  26726. if (numberOfSides === void 0) { numberOfSides = 32; }
  26727. var result = new Array();
  26728. var angle = 0;
  26729. var increment = (Math.PI * 2) / numberOfSides;
  26730. for (var i = 0; i < numberOfSides; i++) {
  26731. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  26732. angle -= increment;
  26733. }
  26734. return result;
  26735. };
  26736. Polygon.Parse = function (input) {
  26737. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  26738. var i, result = [];
  26739. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  26740. result.push(new poly2tri.Point(floats[i], floats[i + 1]));
  26741. }
  26742. return result;
  26743. };
  26744. Polygon.StartingAt = function (x, y) {
  26745. return BABYLON.Path2.StartingAt(x, y);
  26746. };
  26747. return Polygon;
  26748. })();
  26749. BABYLON.Polygon = Polygon;
  26750. var PolygonMeshBuilder = (function () {
  26751. function PolygonMeshBuilder(name, contours, scene) {
  26752. this._points = new PolygonPoints();
  26753. if (!("poly2tri" in window)) {
  26754. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  26755. }
  26756. this._name = name;
  26757. this._scene = scene;
  26758. var points;
  26759. if (contours instanceof BABYLON.Path2) {
  26760. points = contours.getPoints();
  26761. }
  26762. else {
  26763. points = contours;
  26764. }
  26765. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  26766. }
  26767. PolygonMeshBuilder.prototype.addHole = function (hole) {
  26768. this._swctx.addHole(this._points.add(hole));
  26769. return this;
  26770. };
  26771. PolygonMeshBuilder.prototype.build = function (updatable) {
  26772. if (updatable === void 0) { updatable = false; }
  26773. var result = new BABYLON.Mesh(this._name, this._scene);
  26774. var normals = [];
  26775. var positions = [];
  26776. var uvs = [];
  26777. var bounds = this._points.computeBounds();
  26778. this._points.elements.forEach(function (p) {
  26779. normals.push(0, 1.0, 0);
  26780. positions.push(p.x, 0, p.y);
  26781. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  26782. });
  26783. var indices = [];
  26784. this._swctx.triangulate();
  26785. this._swctx.getTriangles().forEach(function (triangle) {
  26786. triangle.getPoints().forEach(function (point) {
  26787. indices.push(point.index);
  26788. });
  26789. });
  26790. result.setVerticesData(positions, BABYLON.VertexBuffer.PositionKind, updatable);
  26791. result.setVerticesData(normals, BABYLON.VertexBuffer.NormalKind, updatable);
  26792. result.setVerticesData(uvs, BABYLON.VertexBuffer.UVKind, updatable);
  26793. result.setIndices(indices);
  26794. return result;
  26795. };
  26796. return PolygonMeshBuilder;
  26797. })();
  26798. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  26799. })(BABYLON || (BABYLON = {}));
  26800. //# sourceMappingURL=babylon.polygonMesh.js.mapvar BABYLON;
  26801. (function (BABYLON) {
  26802. var SimplificationSettings = (function () {
  26803. function SimplificationSettings(quality, distance) {
  26804. this.quality = quality;
  26805. this.distance = distance;
  26806. }
  26807. return SimplificationSettings;
  26808. })();
  26809. BABYLON.SimplificationSettings = SimplificationSettings;
  26810. /**
  26811. * The implemented types of simplification.
  26812. * At the moment only Quadratic Error Decimation is implemented.
  26813. */
  26814. (function (SimplificationType) {
  26815. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  26816. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  26817. var SimplificationType = BABYLON.SimplificationType;
  26818. var DecimationTriangle = (function () {
  26819. function DecimationTriangle(vertices) {
  26820. this.vertices = vertices;
  26821. this.error = new Array(4);
  26822. this.deleted = false;
  26823. this.isDirty = false;
  26824. this.borderFactor = 0;
  26825. }
  26826. return DecimationTriangle;
  26827. })();
  26828. BABYLON.DecimationTriangle = DecimationTriangle;
  26829. var DecimationVertex = (function () {
  26830. function DecimationVertex(position, normal, uv, id) {
  26831. this.position = position;
  26832. this.normal = normal;
  26833. this.uv = uv;
  26834. this.id = id;
  26835. this.isBorder = true;
  26836. this.q = new QuadraticMatrix();
  26837. this.triangleCount = 0;
  26838. this.triangleStart = 0;
  26839. }
  26840. return DecimationVertex;
  26841. })();
  26842. BABYLON.DecimationVertex = DecimationVertex;
  26843. var QuadraticMatrix = (function () {
  26844. function QuadraticMatrix(data) {
  26845. this.data = new Array(10);
  26846. for (var i = 0; i < 10; ++i) {
  26847. if (data && data[i]) {
  26848. this.data[i] = data[i];
  26849. }
  26850. else {
  26851. this.data[i] = 0;
  26852. }
  26853. }
  26854. }
  26855. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  26856. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] + this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] - this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  26857. return det;
  26858. };
  26859. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  26860. for (var i = 0; i < 10; ++i) {
  26861. this.data[i] += matrix.data[i];
  26862. }
  26863. };
  26864. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  26865. for (var i = 0; i < 10; ++i) {
  26866. this.data[i] += data[i];
  26867. }
  26868. };
  26869. QuadraticMatrix.prototype.add = function (matrix) {
  26870. var m = new QuadraticMatrix();
  26871. for (var i = 0; i < 10; ++i) {
  26872. m.data[i] = this.data[i] + matrix.data[i];
  26873. }
  26874. return m;
  26875. };
  26876. QuadraticMatrix.FromData = function (a, b, c, d) {
  26877. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  26878. };
  26879. //returning an array to avoid garbage collection
  26880. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  26881. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  26882. };
  26883. return QuadraticMatrix;
  26884. })();
  26885. BABYLON.QuadraticMatrix = QuadraticMatrix;
  26886. var Reference = (function () {
  26887. function Reference(vertexId, triangleId) {
  26888. this.vertexId = vertexId;
  26889. this.triangleId = triangleId;
  26890. }
  26891. return Reference;
  26892. })();
  26893. BABYLON.Reference = Reference;
  26894. /**
  26895. * An implementation of the Quadratic Error simplification algorithm.
  26896. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  26897. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  26898. * @author RaananW
  26899. */
  26900. var QuadraticErrorSimplification = (function () {
  26901. function QuadraticErrorSimplification(_mesh) {
  26902. this._mesh = _mesh;
  26903. this.initialised = false;
  26904. this.syncIterations = 5000;
  26905. this.aggressiveness = 7;
  26906. this.decimationIterations = 100;
  26907. }
  26908. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  26909. var _this = this;
  26910. this.initWithMesh(this._mesh, function () {
  26911. _this.runDecimation(settings, successCallback);
  26912. });
  26913. };
  26914. QuadraticErrorSimplification.prototype.runDecimation = function (settings, successCallback) {
  26915. var _this = this;
  26916. var targetCount = ~~(this.triangles.length * settings.quality);
  26917. var deletedTriangles = 0;
  26918. var triangleCount = this.triangles.length;
  26919. var iterationFunction = function (iteration, callback) {
  26920. setTimeout(function () {
  26921. if (iteration % 5 === 0) {
  26922. _this.updateMesh(iteration === 0);
  26923. }
  26924. for (var i = 0; i < _this.triangles.length; ++i) {
  26925. _this.triangles[i].isDirty = false;
  26926. }
  26927. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  26928. var trianglesIterator = function (i) {
  26929. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  26930. var t = _this.triangles[tIdx];
  26931. if (!t)
  26932. return;
  26933. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  26934. return;
  26935. }
  26936. for (var j = 0; j < 3; ++j) {
  26937. if (t.error[j] < threshold) {
  26938. var deleted0 = [];
  26939. var deleted1 = [];
  26940. var i0 = t.vertices[j];
  26941. var i1 = t.vertices[(j + 1) % 3];
  26942. var v0 = _this.vertices[i0];
  26943. var v1 = _this.vertices[i1];
  26944. if (v0.isBorder !== v1.isBorder)
  26945. continue;
  26946. var p = BABYLON.Vector3.Zero();
  26947. var n = BABYLON.Vector3.Zero();
  26948. var uv = BABYLON.Vector2.Zero();
  26949. var color = new BABYLON.Color4(0, 0, 0, 1);
  26950. _this.calculateError(v0, v1, p, n, uv, color);
  26951. var delTr = [];
  26952. if (_this.isFlipped(v0, i1, p, deleted0, t.borderFactor, delTr))
  26953. continue;
  26954. if (_this.isFlipped(v1, i0, p, deleted1, t.borderFactor, delTr))
  26955. continue;
  26956. if (delTr.length == 2 || delTr[0] === delTr[1]) {
  26957. continue;
  26958. }
  26959. v0.normal = n;
  26960. if (v0.uv)
  26961. v0.uv = uv;
  26962. else if (v0.color)
  26963. v0.color = color;
  26964. v0.q = v1.q.add(v0.q);
  26965. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  26966. continue;
  26967. if (p.equals(v0.position))
  26968. continue;
  26969. v0.position = p;
  26970. var tStart = _this.references.length;
  26971. deletedTriangles = _this.updateTriangles(v0.id, v0, deleted0, deletedTriangles);
  26972. deletedTriangles = _this.updateTriangles(v0.id, v1, deleted1, deletedTriangles);
  26973. var tCount = _this.references.length - tStart;
  26974. if (tCount <= v0.triangleCount) {
  26975. if (tCount) {
  26976. for (var c = 0; c < tCount; c++) {
  26977. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  26978. }
  26979. }
  26980. }
  26981. else {
  26982. v0.triangleStart = tStart;
  26983. }
  26984. v0.triangleCount = tCount;
  26985. break;
  26986. }
  26987. }
  26988. };
  26989. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () {
  26990. return (triangleCount - deletedTriangles <= targetCount);
  26991. });
  26992. }, 0);
  26993. };
  26994. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  26995. if (triangleCount - deletedTriangles <= targetCount)
  26996. loop.breakLoop();
  26997. else {
  26998. iterationFunction(loop.index, function () {
  26999. loop.executeNext();
  27000. });
  27001. }
  27002. }, function () {
  27003. setTimeout(function () {
  27004. successCallback(_this.reconstructMesh());
  27005. }, 0);
  27006. });
  27007. };
  27008. QuadraticErrorSimplification.prototype.initWithMesh = function (mesh, callback) {
  27009. var _this = this;
  27010. if (!mesh)
  27011. return;
  27012. this.vertices = [];
  27013. this.triangles = [];
  27014. this._mesh = mesh;
  27015. //It is assumed that a mesh has positions, normals and either uvs or colors.
  27016. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27017. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  27018. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  27019. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  27020. var indices = mesh.getIndices();
  27021. var vertexInit = function (i) {
  27022. var vertex = new DecimationVertex(BABYLON.Vector3.FromArray(positionData, i * 3), BABYLON.Vector3.FromArray(normalData, i * 3), null, i);
  27023. if (_this._mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  27024. vertex.uv = BABYLON.Vector2.FromArray(uvs, i * 2);
  27025. }
  27026. else if (_this._mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  27027. vertex.color = BABYLON.Color4.FromArray(colorsData, i * 4);
  27028. }
  27029. _this.vertices.push(vertex);
  27030. };
  27031. var totalVertices = mesh.getTotalVertices();
  27032. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, this.syncIterations, vertexInit, function () {
  27033. var indicesInit = function (i) {
  27034. var pos = i * 3;
  27035. var i0 = indices[pos + 0];
  27036. var i1 = indices[pos + 1];
  27037. var i2 = indices[pos + 2];
  27038. var triangle = new DecimationTriangle([_this.vertices[i0].id, _this.vertices[i1].id, _this.vertices[i2].id]);
  27039. _this.triangles.push(triangle);
  27040. };
  27041. BABYLON.AsyncLoop.SyncAsyncForLoop(indices.length / 3, _this.syncIterations, indicesInit, function () {
  27042. _this.init(callback);
  27043. });
  27044. });
  27045. };
  27046. QuadraticErrorSimplification.prototype.init = function (callback) {
  27047. var _this = this;
  27048. var triangleInit1 = function (i) {
  27049. var t = _this.triangles[i];
  27050. t.normal = BABYLON.Vector3.Cross(_this.vertices[t.vertices[1]].position.subtract(_this.vertices[t.vertices[0]].position), _this.vertices[t.vertices[2]].position.subtract(_this.vertices[t.vertices[0]].position)).normalize();
  27051. for (var j = 0; j < 3; j++) {
  27052. _this.vertices[t.vertices[j]].q.addArrayInPlace(QuadraticMatrix.DataFromNumbers(t.normal.x, t.normal.y, t.normal.z, -(BABYLON.Vector3.Dot(t.normal, _this.vertices[t.vertices[0]].position))));
  27053. }
  27054. };
  27055. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  27056. var triangleInit2 = function (i) {
  27057. var t = _this.triangles[i];
  27058. for (var j = 0; j < 3; ++j) {
  27059. t.error[j] = _this.calculateError(_this.vertices[t.vertices[j]], _this.vertices[t.vertices[(j + 1) % 3]]);
  27060. }
  27061. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  27062. };
  27063. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  27064. _this.initialised = true;
  27065. callback();
  27066. });
  27067. });
  27068. };
  27069. QuadraticErrorSimplification.prototype.reconstructMesh = function () {
  27070. var newTriangles = [];
  27071. var i;
  27072. for (i = 0; i < this.vertices.length; ++i) {
  27073. this.vertices[i].triangleCount = 0;
  27074. }
  27075. var t;
  27076. var j;
  27077. for (i = 0; i < this.triangles.length; ++i) {
  27078. if (!this.triangles[i].deleted) {
  27079. t = this.triangles[i];
  27080. for (j = 0; j < 3; ++j) {
  27081. this.vertices[t.vertices[j]].triangleCount = 1;
  27082. }
  27083. newTriangles.push(t);
  27084. }
  27085. }
  27086. var newVerticesOrder = [];
  27087. //compact vertices, get the IDs of the vertices used.
  27088. var dst = 0;
  27089. for (i = 0; i < this.vertices.length; ++i) {
  27090. if (this.vertices[i].triangleCount) {
  27091. this.vertices[i].triangleStart = dst;
  27092. this.vertices[dst].position = this.vertices[i].position;
  27093. this.vertices[dst].normal = this.vertices[i].normal;
  27094. this.vertices[dst].uv = this.vertices[i].uv;
  27095. this.vertices[dst].color = this.vertices[i].color;
  27096. newVerticesOrder.push(i);
  27097. dst++;
  27098. }
  27099. }
  27100. for (i = 0; i < newTriangles.length; ++i) {
  27101. t = newTriangles[i];
  27102. for (j = 0; j < 3; ++j) {
  27103. t.vertices[j] = this.vertices[t.vertices[j]].triangleStart;
  27104. }
  27105. }
  27106. this.vertices = this.vertices.slice(0, dst);
  27107. var newPositionData = [];
  27108. var newNormalData = [];
  27109. var newUVsData = [];
  27110. var newColorsData = [];
  27111. for (i = 0; i < newVerticesOrder.length; ++i) {
  27112. newPositionData.push(this.vertices[i].position.x);
  27113. newPositionData.push(this.vertices[i].position.y);
  27114. newPositionData.push(this.vertices[i].position.z);
  27115. newNormalData.push(this.vertices[i].normal.x);
  27116. newNormalData.push(this.vertices[i].normal.y);
  27117. newNormalData.push(this.vertices[i].normal.z);
  27118. if (this.vertices[i].uv) {
  27119. newUVsData.push(this.vertices[i].uv.x);
  27120. newUVsData.push(this.vertices[i].uv.y);
  27121. }
  27122. else if (this.vertices[i].color) {
  27123. newColorsData.push(this.vertices[i].color.r);
  27124. newColorsData.push(this.vertices[i].color.g);
  27125. newColorsData.push(this.vertices[i].color.b);
  27126. newColorsData.push(this.vertices[i].color.a);
  27127. }
  27128. }
  27129. var newIndicesArray = [];
  27130. for (i = 0; i < newTriangles.length; ++i) {
  27131. newIndicesArray.push(newTriangles[i].vertices[0]);
  27132. newIndicesArray.push(newTriangles[i].vertices[1]);
  27133. newIndicesArray.push(newTriangles[i].vertices[2]);
  27134. }
  27135. //not cloning, to avoid geometry problems. Creating a whole new mesh.
  27136. var newMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  27137. newMesh.material = this._mesh.material;
  27138. newMesh.parent = this._mesh.parent;
  27139. newMesh.setIndices(newIndicesArray);
  27140. newMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  27141. newMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  27142. if (newUVsData.length > 0)
  27143. newMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  27144. if (newColorsData.length > 0)
  27145. newMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  27146. //preparing the skeleton support
  27147. if (this._mesh.skeleton) {
  27148. }
  27149. return newMesh;
  27150. };
  27151. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, index2, point, deletedArray, borderFactor, delTr) {
  27152. for (var i = 0; i < vertex1.triangleCount; ++i) {
  27153. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  27154. if (t.deleted)
  27155. continue;
  27156. var s = this.references[vertex1.triangleStart + i].vertexId;
  27157. var id1 = t.vertices[(s + 1) % 3];
  27158. var id2 = t.vertices[(s + 2) % 3];
  27159. if ((id1 === index2 || id2 === index2) && borderFactor < 2) {
  27160. deletedArray[i] = true;
  27161. delTr.push(t);
  27162. continue;
  27163. }
  27164. var d1 = this.vertices[id1].position.subtract(point);
  27165. d1 = d1.normalize();
  27166. var d2 = this.vertices[id2].position.subtract(point);
  27167. d2 = d2.normalize();
  27168. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  27169. return true;
  27170. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  27171. deletedArray[i] = false;
  27172. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  27173. return true;
  27174. }
  27175. return false;
  27176. };
  27177. QuadraticErrorSimplification.prototype.updateTriangles = function (vertexId, vertex, deletedArray, deletedTriangles) {
  27178. var newDeleted = deletedTriangles;
  27179. for (var i = 0; i < vertex.triangleCount; ++i) {
  27180. var ref = this.references[vertex.triangleStart + i];
  27181. var t = this.triangles[ref.triangleId];
  27182. if (t.deleted)
  27183. continue;
  27184. if (deletedArray[i]) {
  27185. t.deleted = true;
  27186. newDeleted++;
  27187. continue;
  27188. }
  27189. t.vertices[ref.vertexId] = vertexId;
  27190. t.isDirty = true;
  27191. t.error[0] = this.calculateError(this.vertices[t.vertices[0]], this.vertices[t.vertices[1]]) + (t.borderFactor / 2);
  27192. t.error[1] = this.calculateError(this.vertices[t.vertices[1]], this.vertices[t.vertices[2]]) + (t.borderFactor / 2);
  27193. t.error[2] = this.calculateError(this.vertices[t.vertices[2]], this.vertices[t.vertices[0]]) + (t.borderFactor / 2);
  27194. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  27195. this.references.push(ref);
  27196. }
  27197. return newDeleted;
  27198. };
  27199. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  27200. for (var i = 0; i < this.vertices.length; ++i) {
  27201. var vCount = [];
  27202. var vId = [];
  27203. var v = this.vertices[i];
  27204. var j;
  27205. for (j = 0; j < v.triangleCount; ++j) {
  27206. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  27207. for (var ii = 0; ii < 3; ii++) {
  27208. var ofs = 0;
  27209. var id = triangle.vertices[ii];
  27210. while (ofs < vCount.length) {
  27211. if (vId[ofs] === id)
  27212. break;
  27213. ++ofs;
  27214. }
  27215. if (ofs === vCount.length) {
  27216. vCount.push(1);
  27217. vId.push(id);
  27218. }
  27219. else {
  27220. vCount[ofs]++;
  27221. }
  27222. }
  27223. }
  27224. for (j = 0; j < vCount.length; ++j) {
  27225. if (vCount[j] === 1) {
  27226. this.vertices[vId[j]].isBorder = true;
  27227. }
  27228. else {
  27229. this.vertices[vId[j]].isBorder = false;
  27230. }
  27231. }
  27232. }
  27233. };
  27234. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  27235. if (identifyBorders === void 0) { identifyBorders = false; }
  27236. var i;
  27237. if (!identifyBorders) {
  27238. var newTrianglesVector = [];
  27239. for (i = 0; i < this.triangles.length; ++i) {
  27240. if (!this.triangles[i].deleted) {
  27241. newTrianglesVector.push(this.triangles[i]);
  27242. }
  27243. }
  27244. this.triangles = newTrianglesVector;
  27245. }
  27246. for (i = 0; i < this.vertices.length; ++i) {
  27247. this.vertices[i].triangleCount = 0;
  27248. this.vertices[i].triangleStart = 0;
  27249. }
  27250. var t;
  27251. var j;
  27252. var v;
  27253. for (i = 0; i < this.triangles.length; ++i) {
  27254. t = this.triangles[i];
  27255. for (j = 0; j < 3; ++j) {
  27256. v = this.vertices[t.vertices[j]];
  27257. v.triangleCount++;
  27258. }
  27259. }
  27260. var tStart = 0;
  27261. for (i = 0; i < this.vertices.length; ++i) {
  27262. this.vertices[i].triangleStart = tStart;
  27263. tStart += this.vertices[i].triangleCount;
  27264. this.vertices[i].triangleCount = 0;
  27265. }
  27266. var newReferences = new Array(this.triangles.length * 3);
  27267. for (i = 0; i < this.triangles.length; ++i) {
  27268. t = this.triangles[i];
  27269. for (j = 0; j < 3; ++j) {
  27270. v = this.vertices[t.vertices[j]];
  27271. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  27272. v.triangleCount++;
  27273. }
  27274. }
  27275. this.references = newReferences;
  27276. if (identifyBorders) {
  27277. this.identifyBorder();
  27278. }
  27279. };
  27280. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  27281. var x = point.x;
  27282. var y = point.y;
  27283. var z = point.z;
  27284. return q.data[0] * x * x + 2 * q.data[1] * x * y + 2 * q.data[2] * x * z + 2 * q.data[3] * x + q.data[4] * y * y + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  27285. };
  27286. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  27287. var q = vertex1.q.add(vertex2.q);
  27288. var border = vertex1.isBorder && vertex2.isBorder;
  27289. var error = 0;
  27290. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  27291. if (qDet !== 0 && !border) {
  27292. if (!pointResult) {
  27293. pointResult = BABYLON.Vector3.Zero();
  27294. }
  27295. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  27296. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  27297. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  27298. error = this.vertexError(q, pointResult);
  27299. //TODO this should be correctly calculated
  27300. if (normalResult) {
  27301. normalResult.copyFrom(vertex1.normal);
  27302. if (vertex1.uv)
  27303. uvResult.copyFrom(vertex1.uv);
  27304. else if (vertex1.color)
  27305. colorResult.copyFrom(vertex1.color);
  27306. }
  27307. }
  27308. else {
  27309. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  27310. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  27311. var error1 = this.vertexError(q, vertex1.position);
  27312. var error2 = this.vertexError(q, vertex2.position);
  27313. var error3 = this.vertexError(q, p3);
  27314. error = Math.min(error1, error2, error3);
  27315. if (error === error1) {
  27316. if (pointResult) {
  27317. pointResult.copyFrom(vertex1.position);
  27318. normalResult.copyFrom(vertex1.normal);
  27319. if (vertex1.uv)
  27320. uvResult.copyFrom(vertex1.uv);
  27321. else if (vertex1.color)
  27322. colorResult.copyFrom(vertex1.color);
  27323. }
  27324. }
  27325. else if (error === error2) {
  27326. if (pointResult) {
  27327. pointResult.copyFrom(vertex2.position);
  27328. normalResult.copyFrom(vertex2.normal);
  27329. if (vertex2.uv)
  27330. uvResult.copyFrom(vertex2.uv);
  27331. else if (vertex2.color)
  27332. colorResult.copyFrom(vertex2.color);
  27333. }
  27334. }
  27335. else {
  27336. if (pointResult) {
  27337. pointResult.copyFrom(p3);
  27338. normalResult.copyFrom(vertex1.normal);
  27339. if (vertex1.uv)
  27340. uvResult.copyFrom(vertex1.uv);
  27341. else if (vertex1.color)
  27342. colorResult.copyFrom(vertex1.color);
  27343. }
  27344. }
  27345. }
  27346. return error;
  27347. };
  27348. return QuadraticErrorSimplification;
  27349. })();
  27350. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  27351. })(BABYLON || (BABYLON = {}));
  27352. //# sourceMappingURL=babylon.meshSimplification.js.mapvar BABYLON;
  27353. (function (BABYLON) {
  27354. var Analyser = (function () {
  27355. function Analyser(scene) {
  27356. this.SMOOTHING = 0.75;
  27357. this.FFT_SIZE = 512;
  27358. this.BARGRAPHAMPLITUDE = 256;
  27359. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  27360. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  27361. this._scene = scene;
  27362. this._audioEngine = BABYLON.Engine.audioEngine;
  27363. if (this._audioEngine.canUseWebAudio) {
  27364. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  27365. this._webAudioAnalyser.minDecibels = -140;
  27366. this._webAudioAnalyser.maxDecibels = 0;
  27367. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  27368. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  27369. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  27370. }
  27371. }
  27372. Analyser.prototype.getFrequencyBinCount = function () {
  27373. if (this._audioEngine.canUseWebAudio) {
  27374. return this._webAudioAnalyser.frequencyBinCount;
  27375. }
  27376. else {
  27377. return 0;
  27378. }
  27379. };
  27380. Analyser.prototype.getByteFrequencyData = function () {
  27381. if (this._audioEngine.canUseWebAudio) {
  27382. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  27383. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  27384. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  27385. }
  27386. return this._byteFreqs;
  27387. };
  27388. Analyser.prototype.getByteTimeDomainData = function () {
  27389. if (this._audioEngine.canUseWebAudio) {
  27390. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  27391. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  27392. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  27393. }
  27394. return this._byteTime;
  27395. };
  27396. Analyser.prototype.getFloatFrequencyData = function () {
  27397. if (this._audioEngine.canUseWebAudio) {
  27398. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  27399. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  27400. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  27401. }
  27402. return this._floatFreqs;
  27403. };
  27404. Analyser.prototype.drawDebugCanvas = function () {
  27405. var _this = this;
  27406. if (this._audioEngine.canUseWebAudio) {
  27407. if (!this._debugCanvas) {
  27408. this._debugCanvas = document.createElement("canvas");
  27409. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  27410. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  27411. this._debugCanvas.style.position = "absolute";
  27412. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  27413. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  27414. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  27415. document.body.appendChild(this._debugCanvas);
  27416. this._registerFunc = function () {
  27417. _this.drawDebugCanvas();
  27418. };
  27419. this._scene.registerBeforeRender(this._registerFunc);
  27420. }
  27421. if (this._registerFunc) {
  27422. var workingArray = this.getByteFrequencyData();
  27423. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  27424. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  27425. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  27426. var value = workingArray[i];
  27427. var percent = value / this.BARGRAPHAMPLITUDE;
  27428. var height = this.DEBUGCANVASSIZE.height * percent;
  27429. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  27430. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  27431. var hue = i / this.getFrequencyBinCount() * 360;
  27432. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  27433. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  27434. }
  27435. }
  27436. }
  27437. };
  27438. Analyser.prototype.stopDebugCanvas = function () {
  27439. if (this._debugCanvas) {
  27440. this._scene.unregisterBeforeRender(this._registerFunc);
  27441. this._registerFunc = null;
  27442. document.body.removeChild(this._debugCanvas);
  27443. this._debugCanvas = null;
  27444. this._debugCanvasContext = null;
  27445. }
  27446. };
  27447. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  27448. if (this._audioEngine.canUseWebAudio) {
  27449. inputAudioNode.connect(this._webAudioAnalyser);
  27450. this._webAudioAnalyser.connect(outputAudioNode);
  27451. }
  27452. };
  27453. Analyser.prototype.dispose = function () {
  27454. if (this._audioEngine.canUseWebAudio) {
  27455. this._webAudioAnalyser.disconnect();
  27456. }
  27457. };
  27458. return Analyser;
  27459. })();
  27460. BABYLON.Analyser = Analyser;
  27461. })(BABYLON || (BABYLON = {}));
  27462. //# sourceMappingURL=babylon.analyser.js.mapvar BABYLON;
  27463. (function (BABYLON) {
  27464. var DepthRenderer = (function () {
  27465. function DepthRenderer(scene, type) {
  27466. var _this = this;
  27467. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  27468. this._viewMatrix = BABYLON.Matrix.Zero();
  27469. this._projectionMatrix = BABYLON.Matrix.Zero();
  27470. this._transformMatrix = BABYLON.Matrix.Zero();
  27471. this._worldViewProjection = BABYLON.Matrix.Zero();
  27472. this._scene = scene;
  27473. var engine = scene.getEngine();
  27474. // Render target
  27475. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  27476. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  27477. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  27478. this._depthMap.refreshRate = 1;
  27479. this._depthMap.renderParticles = false;
  27480. this._depthMap.renderList = null;
  27481. // Custom render function
  27482. var renderSubMesh = function (subMesh) {
  27483. var mesh = subMesh.getRenderingMesh();
  27484. var scene = _this._scene;
  27485. var engine = scene.getEngine();
  27486. // Culling
  27487. engine.setState(subMesh.getMaterial().backFaceCulling);
  27488. // Managing instances
  27489. var batch = mesh._getInstancesRenderList(subMesh._id);
  27490. if (batch.mustReturn) {
  27491. return;
  27492. }
  27493. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  27494. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  27495. engine.enableEffect(_this._effect);
  27496. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  27497. var material = subMesh.getMaterial();
  27498. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  27499. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  27500. // Alpha test
  27501. if (material && material.needAlphaTesting()) {
  27502. var alphaTexture = material.getAlphaTestTexture();
  27503. _this._effect.setTexture("diffuseSampler", alphaTexture);
  27504. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  27505. }
  27506. // Bones
  27507. if (mesh.useBones) {
  27508. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  27509. }
  27510. // Draw
  27511. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  27512. }
  27513. };
  27514. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  27515. var index;
  27516. for (index = 0; index < opaqueSubMeshes.length; index++) {
  27517. renderSubMesh(opaqueSubMeshes.data[index]);
  27518. }
  27519. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  27520. renderSubMesh(alphaTestSubMeshes.data[index]);
  27521. }
  27522. };
  27523. }
  27524. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  27525. var defines = [];
  27526. var attribs = [BABYLON.VertexBuffer.PositionKind];
  27527. var mesh = subMesh.getMesh();
  27528. var scene = mesh.getScene();
  27529. var material = subMesh.getMaterial();
  27530. // Alpha test
  27531. if (material && material.needAlphaTesting()) {
  27532. defines.push("#define ALPHATEST");
  27533. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  27534. attribs.push(BABYLON.VertexBuffer.UVKind);
  27535. defines.push("#define UV1");
  27536. }
  27537. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  27538. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  27539. defines.push("#define UV2");
  27540. }
  27541. }
  27542. // Bones
  27543. if (mesh.useBones) {
  27544. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  27545. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  27546. defines.push("#define BONES");
  27547. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  27548. }
  27549. // Instances
  27550. if (useInstances) {
  27551. defines.push("#define INSTANCES");
  27552. attribs.push("world0");
  27553. attribs.push("world1");
  27554. attribs.push("world2");
  27555. attribs.push("world3");
  27556. }
  27557. // Get correct effect
  27558. var join = defines.join("\n");
  27559. if (this._cachedDefines !== join) {
  27560. this._cachedDefines = join;
  27561. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  27562. }
  27563. return this._effect.isReady();
  27564. };
  27565. DepthRenderer.prototype.getDepthMap = function () {
  27566. return this._depthMap;
  27567. };
  27568. // Methods
  27569. DepthRenderer.prototype.dispose = function () {
  27570. this._depthMap.dispose();
  27571. };
  27572. return DepthRenderer;
  27573. })();
  27574. BABYLON.DepthRenderer = DepthRenderer;
  27575. })(BABYLON || (BABYLON = {}));
  27576. //# sourceMappingURL=babylon.depthRenderer.js.map
  27577. var BABYLON;
  27578. (function (BABYLON) {
  27579. var SSAORenderingPipeline = (function (_super) {
  27580. __extends(SSAORenderingPipeline, _super);
  27581. /**
  27582. * @constructor
  27583. * @param {string} name - The rendering pipeline name
  27584. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  27585. * @param {number} ratio - The size of the postprocesses (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)
  27586. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  27587. */
  27588. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  27589. var _this = this;
  27590. if (ratio === void 0) { ratio = 1.0; }
  27591. _super.call(this, scene.getEngine(), name);
  27592. // Members
  27593. /**
  27594. * The PassPostProcess id in the pipeline that contains the original scene color
  27595. * @type {string}
  27596. */
  27597. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  27598. /**
  27599. * The SSAO PostProcess id in the pipeline
  27600. * @type {string}
  27601. */
  27602. this.SSAORenderEffect = "SSAORenderEffect";
  27603. /**
  27604. * The horizontal blur PostProcess id in the pipeline
  27605. * @type {string}
  27606. */
  27607. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  27608. /**
  27609. * The vertical blur PostProcess id in the pipeline
  27610. * @type {string}
  27611. */
  27612. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  27613. /**
  27614. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  27615. * @type {string}
  27616. */
  27617. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  27618. this._firstUpdate = true;
  27619. this._scene = scene;
  27620. // Set up assets
  27621. this._createRandomTexture();
  27622. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  27623. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  27624. this._createSSAOPostProcess(ratio);
  27625. this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlurH", new BABYLON.Vector2(2.0, 0.0), 1.3, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  27626. this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlurV", new BABYLON.Vector2(0.0, 2.0), 1.3, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  27627. this._createSSAOCombinePostProcess();
  27628. // Set up pipeline
  27629. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () {
  27630. return _this._originalColorPostProcess;
  27631. }, true));
  27632. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () {
  27633. return _this._ssaoPostProcess;
  27634. }, true));
  27635. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () {
  27636. return _this._blurHPostProcess;
  27637. }, true));
  27638. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () {
  27639. return _this._blurVPostProcess;
  27640. }, true));
  27641. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () {
  27642. return _this._ssaoCombinePostProcess;
  27643. }, true));
  27644. // Finish
  27645. scene.postProcessRenderPipelineManager.addPipeline(this);
  27646. if (cameras)
  27647. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  27648. }
  27649. // Public Methods
  27650. /**
  27651. * Returns the horizontal blur PostProcess
  27652. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  27653. */
  27654. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  27655. return this._blurHPostProcess;
  27656. };
  27657. /**
  27658. * Returns the vertical blur PostProcess
  27659. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  27660. */
  27661. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  27662. return this._blurVPostProcess;
  27663. };
  27664. /**
  27665. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  27666. */
  27667. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  27668. if (disableDepthRender === void 0) { disableDepthRender = false; }
  27669. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  27670. this._originalColorPostProcess = undefined;
  27671. this._ssaoPostProcess = undefined;
  27672. this._blurHPostProcess = undefined;
  27673. this._blurVPostProcess = undefined;
  27674. this._ssaoCombinePostProcess = undefined;
  27675. this._randomTexture.dispose();
  27676. if (disableDepthRender)
  27677. this._scene.disableDepthRenderer();
  27678. };
  27679. // Private Methods
  27680. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  27681. var _this = this;
  27682. var sampleSphere = [
  27683. 0.5381,
  27684. 0.1856,
  27685. -0.4319,
  27686. 0.1379,
  27687. 0.2486,
  27688. 0.4430,
  27689. 0.3371,
  27690. 0.5679,
  27691. -0.0057,
  27692. -0.6999,
  27693. -0.0451,
  27694. -0.0019,
  27695. 0.0689,
  27696. -0.1598,
  27697. -0.8547,
  27698. 0.0560,
  27699. 0.0069,
  27700. -0.1843,
  27701. -0.0146,
  27702. 0.1402,
  27703. 0.0762,
  27704. 0.0100,
  27705. -0.1924,
  27706. -0.0344,
  27707. -0.3577,
  27708. -0.5301,
  27709. -0.4358,
  27710. -0.3169,
  27711. 0.1063,
  27712. 0.0158,
  27713. 0.0103,
  27714. -0.5869,
  27715. 0.0046,
  27716. -0.0897,
  27717. -0.4940,
  27718. 0.3287,
  27719. 0.7119,
  27720. -0.0154,
  27721. -0.0918,
  27722. -0.0533,
  27723. 0.0596,
  27724. -0.5411,
  27725. 0.0352,
  27726. -0.0631,
  27727. 0.5460,
  27728. -0.4776,
  27729. 0.2847,
  27730. -0.0271
  27731. ];
  27732. var samplesFactor = 1.0 / 16.0;
  27733. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", ["sampleSphere", "samplesFactor", "randTextureTiles"], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  27734. this._ssaoPostProcess.onApply = function (effect) {
  27735. if (_this._firstUpdate) {
  27736. effect.setArray3("sampleSphere", sampleSphere);
  27737. effect.setFloat("samplesFactor", samplesFactor);
  27738. effect.setFloat("randTextureTiles", 4.0 / ratio);
  27739. _this._firstUpdate = false;
  27740. }
  27741. effect.setTexture("textureSampler", _this._depthTexture);
  27742. effect.setTexture("randomSampler", _this._randomTexture);
  27743. };
  27744. };
  27745. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function () {
  27746. var _this = this;
  27747. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  27748. this._ssaoCombinePostProcess.onApply = function (effect) {
  27749. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  27750. };
  27751. };
  27752. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  27753. var size = 512;
  27754. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  27755. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  27756. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  27757. var context = this._randomTexture.getContext();
  27758. var rand = function (min, max) {
  27759. return Math.random() * (max - min) + min;
  27760. };
  27761. for (var x = 0; x < size; x++) {
  27762. for (var y = 0; y < size; y++) {
  27763. var randVector = BABYLON.Vector3.Zero();
  27764. randVector.x = Math.floor(rand(0.0, 1.0) * 255);
  27765. randVector.y = Math.floor(rand(0.0, 1.0) * 255);
  27766. randVector.z = Math.floor(rand(0.0, 1.0) * 255);
  27767. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  27768. context.fillRect(x, y, 1, 1);
  27769. }
  27770. }
  27771. this._randomTexture.update(false);
  27772. };
  27773. return SSAORenderingPipeline;
  27774. })(BABYLON.PostProcessRenderPipeline);
  27775. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  27776. })(BABYLON || (BABYLON = {}));
  27777. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  27778. var BABYLON;
  27779. (function (BABYLON) {
  27780. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  27781. var VolumetricLightScatteringPostProcess = (function (_super) {
  27782. __extends(VolumetricLightScatteringPostProcess, _super);
  27783. /**
  27784. * @constructor
  27785. * @param {string} name - The post-process name
  27786. * @param {number} ratio - The size of the postprocesses (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)
  27787. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  27788. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  27789. * @param {number} samplingMode - The post-process filtering mode
  27790. * @param {BABYLON.Engine} engine - The babylon engine
  27791. * @param {boolean} reusable - If the post-process is reusable
  27792. */
  27793. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable) {
  27794. var _this = this;
  27795. if (samples === void 0) { samples = 100; }
  27796. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  27797. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  27798. this._screenCoordinates = BABYLON.Vector2.Zero();
  27799. /**
  27800. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  27801. * @type {boolean}
  27802. */
  27803. this.useCustomMeshPosition = false;
  27804. /**
  27805. * If the post-process should inverse the light scattering direction
  27806. * @type {boolean}
  27807. */
  27808. this.invert = true;
  27809. /**
  27810. * Array containing the excluded meshes not rendered in the internal pass
  27811. */
  27812. this.excludedMeshes = new Array();
  27813. this.exposure = 0.3;
  27814. this.decay = 0.96815;
  27815. this.weight = 0.58767;
  27816. this.density = 0.926;
  27817. var scene = camera.getScene();
  27818. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(scene.getEngine());
  27819. // Configure mesh
  27820. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  27821. // Configure
  27822. this._createPass(scene, 0.5);
  27823. this.onApply = function (effect) {
  27824. _this._updateMeshScreenCoordinates(scene);
  27825. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  27826. effect.setFloat("exposure", _this.exposure);
  27827. effect.setFloat("decay", _this.decay);
  27828. effect.setFloat("weight", _this.weight);
  27829. effect.setFloat("density", _this.density);
  27830. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  27831. };
  27832. }
  27833. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  27834. var mesh = subMesh.getMesh();
  27835. var defines = [];
  27836. var attribs = [BABYLON.VertexBuffer.PositionKind];
  27837. var material = subMesh.getMaterial();
  27838. // Render this.mesh as default
  27839. if (mesh === this.mesh) {
  27840. defines.push("#define BASIC_RENDER");
  27841. }
  27842. // Alpha test
  27843. if (material) {
  27844. if (material.needAlphaTesting() || mesh === this.mesh)
  27845. defines.push("#define ALPHATEST");
  27846. if (material.opacityTexture !== undefined)
  27847. defines.push("#define OPACITY");
  27848. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  27849. attribs.push(BABYLON.VertexBuffer.UVKind);
  27850. defines.push("#define UV1");
  27851. }
  27852. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  27853. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  27854. defines.push("#define UV2");
  27855. }
  27856. }
  27857. // Bones
  27858. if (mesh.useBones) {
  27859. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  27860. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  27861. defines.push("#define BONES");
  27862. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  27863. }
  27864. // Instances
  27865. if (useInstances) {
  27866. defines.push("#define INSTANCES");
  27867. attribs.push("world0");
  27868. attribs.push("world1");
  27869. attribs.push("world2");
  27870. attribs.push("world3");
  27871. }
  27872. // Get correct effect
  27873. var join = defines.join("\n");
  27874. if (this._cachedDefines !== join) {
  27875. this._cachedDefines = join;
  27876. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler", "opacitySampler"], join);
  27877. }
  27878. return this._volumetricLightScatteringPass.isReady();
  27879. };
  27880. /**
  27881. * Sets the new light position for light scattering effect
  27882. * @param {BABYLON.Vector3} The new custom light position
  27883. */
  27884. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  27885. this._customMeshPosition = position;
  27886. };
  27887. /**
  27888. * Returns the light position for light scattering effect
  27889. * @return {BABYLON.Vector3} The custom light position
  27890. */
  27891. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  27892. return this._customMeshPosition;
  27893. };
  27894. /**
  27895. * Disposes the internal assets and detaches the post-process from the camera
  27896. */
  27897. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  27898. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  27899. if (rttIndex !== -1) {
  27900. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  27901. }
  27902. this._volumetricLightScatteringRTT.dispose();
  27903. _super.prototype.dispose.call(this, camera);
  27904. };
  27905. /**
  27906. * Returns the render target texture used by the post-process
  27907. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  27908. */
  27909. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  27910. return this._volumetricLightScatteringRTT;
  27911. };
  27912. // Private methods
  27913. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  27914. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  27915. return true;
  27916. }
  27917. return false;
  27918. };
  27919. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  27920. var _this = this;
  27921. var engine = scene.getEngine();
  27922. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  27923. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  27924. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  27925. this._volumetricLightScatteringRTT.renderList = null;
  27926. this._volumetricLightScatteringRTT.renderParticles = false;
  27927. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  27928. // Custom render function for submeshes
  27929. var renderSubMesh = function (subMesh) {
  27930. var mesh = subMesh.getRenderingMesh();
  27931. if (_this._meshExcluded(mesh)) {
  27932. return;
  27933. }
  27934. var scene = mesh.getScene();
  27935. var engine = scene.getEngine();
  27936. // Culling
  27937. engine.setState(subMesh.getMaterial().backFaceCulling);
  27938. // Managing instances
  27939. var batch = mesh._getInstancesRenderList(subMesh._id);
  27940. if (batch.mustReturn) {
  27941. return;
  27942. }
  27943. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  27944. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  27945. engine.enableEffect(_this._volumetricLightScatteringPass);
  27946. mesh._bind(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode);
  27947. var material = subMesh.getMaterial();
  27948. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  27949. // Alpha test
  27950. if (material && (mesh === _this.mesh || material.needAlphaTesting() || material.opacityTexture !== undefined)) {
  27951. var alphaTexture = material.getAlphaTestTexture();
  27952. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  27953. if (_this.mesh.material && alphaTexture)
  27954. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  27955. if (material.opacityTexture !== undefined)
  27956. _this._volumetricLightScatteringPass.setTexture("opacitySampler", material.opacityTexture);
  27957. }
  27958. // Bones
  27959. if (mesh.useBones) {
  27960. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  27961. }
  27962. // Draw
  27963. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._volumetricLightScatteringPass.setMatrix("world", world); });
  27964. }
  27965. };
  27966. // Render target texture callbacks
  27967. var savedSceneClearColor;
  27968. var sceneClearColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  27969. this._volumetricLightScatteringRTT.onBeforeRender = function () {
  27970. savedSceneClearColor = scene.clearColor;
  27971. scene.clearColor = sceneClearColor;
  27972. };
  27973. this._volumetricLightScatteringRTT.onAfterRender = function () {
  27974. scene.clearColor = savedSceneClearColor;
  27975. };
  27976. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  27977. var index;
  27978. for (index = 0; index < opaqueSubMeshes.length; index++) {
  27979. renderSubMesh(opaqueSubMeshes.data[index]);
  27980. }
  27981. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  27982. renderSubMesh(alphaTestSubMeshes.data[index]);
  27983. }
  27984. for (index = 0; index < transparentSubMeshes.length; index++) {
  27985. renderSubMesh(transparentSubMeshes.data[index]);
  27986. }
  27987. };
  27988. };
  27989. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  27990. var transform = scene.getTransformMatrix();
  27991. var pos = BABYLON.Vector3.Project(this.useCustomMeshPosition ? this._customMeshPosition : this.mesh.position, BABYLON.Matrix.Identity(), transform, this._viewPort);
  27992. this._screenCoordinates.x = pos.x / this._viewPort.width;
  27993. this._screenCoordinates.y = pos.y / this._viewPort.height;
  27994. if (this.invert)
  27995. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  27996. };
  27997. // Static methods
  27998. /**
  27999. * Creates a default mesh for the Volumeric Light Scattering post-process
  28000. * @param {string} The mesh name
  28001. * @param {BABYLON.Scene} The scene where to create the mesh
  28002. * @return {BABYLON.Mesh} the default mesh
  28003. */
  28004. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  28005. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  28006. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  28007. mesh.material = new BABYLON.StandardMaterial(name + "Material", scene);
  28008. return mesh;
  28009. };
  28010. return VolumetricLightScatteringPostProcess;
  28011. })(BABYLON.PostProcess);
  28012. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  28013. })(BABYLON || (BABYLON = {}));
  28014. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map