babylon.2.0-alpha.debug.js 1.2 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331
  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 (typeof r === "undefined") { r = 0; }
  11. if (typeof g === "undefined") { g = 0; }
  12. if (typeof b === "undefined") { 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. };
  29. Color3.prototype.toColor4 = function (alpha) {
  30. if (typeof alpha === "undefined") { alpha = 1; }
  31. return new Color4(this.r, this.g, this.b, alpha);
  32. };
  33. Color3.prototype.asArray = function () {
  34. var result = [];
  35. this.toArray(result, 0);
  36. return result;
  37. };
  38. Color3.prototype.toLuminance = function () {
  39. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  40. };
  41. Color3.prototype.multiply = function (otherColor) {
  42. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  43. };
  44. Color3.prototype.multiplyToRef = function (otherColor, result) {
  45. result.r = this.r * otherColor.r;
  46. result.g = this.g * otherColor.g;
  47. result.b = this.b * otherColor.b;
  48. };
  49. Color3.prototype.equals = function (otherColor) {
  50. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  51. };
  52. Color3.prototype.scale = function (scale) {
  53. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  54. };
  55. Color3.prototype.scaleToRef = function (scale, result) {
  56. result.r = this.r * scale;
  57. result.g = this.g * scale;
  58. result.b = this.b * scale;
  59. };
  60. Color3.prototype.add = function (otherColor) {
  61. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  62. };
  63. Color3.prototype.addToRef = function (otherColor, result) {
  64. result.r = this.r + otherColor.r;
  65. result.g = this.g + otherColor.g;
  66. result.b = this.b + otherColor.b;
  67. };
  68. Color3.prototype.subtract = function (otherColor) {
  69. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  70. };
  71. Color3.prototype.subtractToRef = function (otherColor, result) {
  72. result.r = this.r - otherColor.r;
  73. result.g = this.g - otherColor.g;
  74. result.b = this.b - otherColor.b;
  75. };
  76. Color3.prototype.clone = function () {
  77. return new Color3(this.r, this.g, this.b);
  78. };
  79. Color3.prototype.copyFrom = function (source) {
  80. this.r = source.r;
  81. this.g = source.g;
  82. this.b = source.b;
  83. };
  84. Color3.prototype.copyFromFloats = function (r, g, b) {
  85. this.r = r;
  86. this.g = g;
  87. this.b = b;
  88. };
  89. // Statics
  90. Color3.FromArray = function (array) {
  91. return new Color3(array[0], array[1], array[2]);
  92. };
  93. Color3.FromInts = function (r, g, b) {
  94. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  95. };
  96. Color3.Lerp = function (start, end, amount) {
  97. var r = start.r + ((end.r - start.r) * amount);
  98. var g = start.g + ((end.g - start.g) * amount);
  99. var b = start.b + ((end.b - start.b) * amount);
  100. return new Color3(r, g, b);
  101. };
  102. Color3.Red = function () {
  103. return new Color3(1, 0, 0);
  104. };
  105. Color3.Green = function () {
  106. return new Color3(0, 1, 0);
  107. };
  108. Color3.Blue = function () {
  109. return new Color3(0, 0, 1);
  110. };
  111. Color3.Black = function () {
  112. return new Color3(0, 0, 0);
  113. };
  114. Color3.White = function () {
  115. return new Color3(1, 1, 1);
  116. };
  117. Color3.Purple = function () {
  118. return new Color3(0.5, 0, 0.5);
  119. };
  120. Color3.Magenta = function () {
  121. return new Color3(1, 0, 1);
  122. };
  123. Color3.Yellow = function () {
  124. return new Color3(1, 1, 0);
  125. };
  126. Color3.Gray = function () {
  127. return new Color3(0.5, 0.5, 0.5);
  128. };
  129. return Color3;
  130. })();
  131. BABYLON.Color3 = Color3;
  132. var Color4 = (function () {
  133. function Color4(r, g, b, a) {
  134. this.r = r;
  135. this.g = g;
  136. this.b = b;
  137. this.a = a;
  138. }
  139. // Operators
  140. Color4.prototype.addInPlace = function (right) {
  141. this.r += right.r;
  142. this.g += right.g;
  143. this.b += right.b;
  144. this.a += right.a;
  145. };
  146. Color4.prototype.asArray = function () {
  147. var result = [];
  148. this.toArray(result, 0);
  149. return result;
  150. };
  151. Color4.prototype.toArray = function (array, index) {
  152. if (index === undefined) {
  153. index = 0;
  154. }
  155. array[index] = this.r;
  156. array[index + 1] = this.g;
  157. array[index + 2] = this.b;
  158. array[index + 3] = this.a;
  159. };
  160. Color4.prototype.add = function (right) {
  161. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  162. };
  163. Color4.prototype.subtract = function (right) {
  164. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  165. };
  166. Color4.prototype.subtractToRef = function (right, result) {
  167. result.r = this.r - right.r;
  168. result.g = this.g - right.g;
  169. result.b = this.b - right.b;
  170. result.a = this.a - right.a;
  171. };
  172. Color4.prototype.scale = function (scale) {
  173. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  174. };
  175. Color4.prototype.scaleToRef = function (scale, result) {
  176. result.r = this.r * scale;
  177. result.g = this.g * scale;
  178. result.b = this.b * scale;
  179. result.a = this.a * scale;
  180. };
  181. Color4.prototype.toString = function () {
  182. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  183. };
  184. Color4.prototype.clone = function () {
  185. return new Color4(this.r, this.g, this.b, this.a);
  186. };
  187. // Statics
  188. Color4.Lerp = function (left, right, amount) {
  189. var result = new Color4(0, 0, 0, 0);
  190. BABYLON.Color4.LerpToRef(left, right, amount, result);
  191. return result;
  192. };
  193. Color4.LerpToRef = function (left, right, amount, result) {
  194. result.r = left.r + (right.r - left.r) * amount;
  195. result.g = left.g + (right.g - left.g) * amount;
  196. result.b = left.b + (right.b - left.b) * amount;
  197. result.a = left.a + (right.a - left.a) * amount;
  198. };
  199. Color4.FromArray = function (array, offset) {
  200. if (typeof offset === "undefined") { offset = 0; }
  201. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  202. };
  203. Color4.FromInts = function (r, g, b, a) {
  204. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  205. };
  206. return Color4;
  207. })();
  208. BABYLON.Color4 = Color4;
  209. var Vector2 = (function () {
  210. function Vector2(x, y) {
  211. this.x = x;
  212. this.y = y;
  213. }
  214. Vector2.prototype.toString = function () {
  215. return "{X: " + this.x + " Y:" + this.y + "}";
  216. };
  217. // Operators
  218. Vector2.prototype.toArray = function (array, index) {
  219. if (index === undefined) {
  220. index = 0;
  221. }
  222. array[index] = this.x;
  223. array[index + 1] = this.y;
  224. };
  225. Vector2.prototype.asArray = function () {
  226. var result = [];
  227. this.toArray(result, 0);
  228. return result;
  229. };
  230. Vector2.prototype.copyFrom = function (source) {
  231. this.x = source.x;
  232. this.y = source.y;
  233. };
  234. Vector2.prototype.copyFromFloats = function (x, y) {
  235. this.x = x;
  236. this.y = y;
  237. };
  238. Vector2.prototype.add = function (otherVector) {
  239. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  240. };
  241. Vector2.prototype.addVector3 = function (otherVector) {
  242. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  243. };
  244. Vector2.prototype.subtract = function (otherVector) {
  245. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  246. };
  247. Vector2.prototype.subtractInPlace = function (otherVector) {
  248. this.x -= otherVector.x;
  249. this.y -= otherVector.y;
  250. };
  251. Vector2.prototype.multiplyInPlace = function (otherVector) {
  252. this.x *= otherVector.x;
  253. this.y *= otherVector.y;
  254. };
  255. Vector2.prototype.multiply = function (otherVector) {
  256. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  257. };
  258. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  259. result.x = this.x * otherVector.x;
  260. result.y = this.y * otherVector.y;
  261. };
  262. Vector2.prototype.multiplyByFloats = function (x, y) {
  263. return new Vector2(this.x * x, this.y * y);
  264. };
  265. Vector2.prototype.divide = function (otherVector) {
  266. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  267. };
  268. Vector2.prototype.divideToRef = function (otherVector, result) {
  269. result.x = this.x / otherVector.x;
  270. result.y = this.y / otherVector.y;
  271. };
  272. Vector2.prototype.negate = function () {
  273. return new Vector2(-this.x, -this.y);
  274. };
  275. Vector2.prototype.scaleInPlace = function (scale) {
  276. this.x *= scale;
  277. this.y *= scale;
  278. return this;
  279. };
  280. Vector2.prototype.scale = function (scale) {
  281. return new Vector2(this.x * scale, this.y * scale);
  282. };
  283. Vector2.prototype.equals = function (otherVector) {
  284. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  285. };
  286. // Properties
  287. Vector2.prototype.length = function () {
  288. return Math.sqrt(this.x * this.x + this.y * this.y);
  289. };
  290. Vector2.prototype.lengthSquared = function () {
  291. return (this.x * this.x + this.y * this.y);
  292. };
  293. // Methods
  294. Vector2.prototype.normalize = function () {
  295. var len = this.length();
  296. if (len === 0)
  297. return this;
  298. var num = 1.0 / len;
  299. this.x *= num;
  300. this.y *= num;
  301. return this;
  302. };
  303. Vector2.prototype.clone = function () {
  304. return new Vector2(this.x, this.y);
  305. };
  306. // Statics
  307. Vector2.Zero = function () {
  308. return new Vector2(0, 0);
  309. };
  310. Vector2.FromArray = function (array, offset) {
  311. if (!offset) {
  312. offset = 0;
  313. }
  314. return new Vector2(array[offset], array[offset + 1]);
  315. };
  316. Vector2.FromArrayToRef = function (array, offset, result) {
  317. result.x = array[offset];
  318. result.y = array[offset + 1];
  319. };
  320. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  321. var squared = amount * amount;
  322. var cubed = amount * squared;
  323. 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));
  324. 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));
  325. return new Vector2(x, y);
  326. };
  327. Vector2.Clamp = function (value, min, max) {
  328. var x = value.x;
  329. x = (x > max.x) ? max.x : x;
  330. x = (x < min.x) ? min.x : x;
  331. var y = value.y;
  332. y = (y > max.y) ? max.y : y;
  333. y = (y < min.y) ? min.y : y;
  334. return new Vector2(x, y);
  335. };
  336. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  337. var squared = amount * amount;
  338. var cubed = amount * squared;
  339. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  340. var part2 = (-2.0 * cubed) + (3.0 * squared);
  341. var part3 = (cubed - (2.0 * squared)) + amount;
  342. var part4 = cubed - squared;
  343. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  344. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  345. return new Vector2(x, y);
  346. };
  347. Vector2.Lerp = function (start, end, amount) {
  348. var x = start.x + ((end.x - start.x) * amount);
  349. var y = start.y + ((end.y - start.y) * amount);
  350. return new Vector2(x, y);
  351. };
  352. Vector2.Dot = function (left, right) {
  353. return left.x * right.x + left.y * right.y;
  354. };
  355. Vector2.Normalize = function (vector) {
  356. var newVector = vector.clone();
  357. newVector.normalize();
  358. return newVector;
  359. };
  360. Vector2.Minimize = function (left, right) {
  361. var x = (left.x < right.x) ? left.x : right.x;
  362. var y = (left.y < right.y) ? left.y : right.y;
  363. return new Vector2(x, y);
  364. };
  365. Vector2.Maximize = function (left, right) {
  366. var x = (left.x > right.x) ? left.x : right.x;
  367. var y = (left.y > right.y) ? left.y : right.y;
  368. return new Vector2(x, y);
  369. };
  370. Vector2.Transform = function (vector, transformation) {
  371. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]);
  372. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]);
  373. return new Vector2(x, y);
  374. };
  375. Vector2.Distance = function (value1, value2) {
  376. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  377. };
  378. Vector2.DistanceSquared = function (value1, value2) {
  379. var x = value1.x - value2.x;
  380. var y = value1.y - value2.y;
  381. return (x * x) + (y * y);
  382. };
  383. return Vector2;
  384. })();
  385. BABYLON.Vector2 = Vector2;
  386. var Vector3 = (function () {
  387. function Vector3(x, y, z) {
  388. this.x = x;
  389. this.y = y;
  390. this.z = z;
  391. }
  392. Vector3.prototype.toString = function () {
  393. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  394. };
  395. // Operators
  396. Vector3.prototype.asArray = function () {
  397. var result = [];
  398. this.toArray(result, 0);
  399. return result;
  400. };
  401. Vector3.prototype.toArray = function (array, index) {
  402. if (index === undefined) {
  403. index = 0;
  404. }
  405. array[index] = this.x;
  406. array[index + 1] = this.y;
  407. array[index + 2] = this.z;
  408. };
  409. Vector3.prototype.addInPlace = function (otherVector) {
  410. this.x += otherVector.x;
  411. this.y += otherVector.y;
  412. this.z += otherVector.z;
  413. };
  414. Vector3.prototype.add = function (otherVector) {
  415. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  416. };
  417. Vector3.prototype.addToRef = function (otherVector, result) {
  418. result.x = this.x + otherVector.x;
  419. result.y = this.y + otherVector.y;
  420. result.z = this.z + otherVector.z;
  421. };
  422. Vector3.prototype.subtractInPlace = function (otherVector) {
  423. this.x -= otherVector.x;
  424. this.y -= otherVector.y;
  425. this.z -= otherVector.z;
  426. };
  427. Vector3.prototype.subtract = function (otherVector) {
  428. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  429. };
  430. Vector3.prototype.subtractToRef = function (otherVector, result) {
  431. result.x = this.x - otherVector.x;
  432. result.y = this.y - otherVector.y;
  433. result.z = this.z - otherVector.z;
  434. };
  435. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  436. return new Vector3(this.x - x, this.y - y, this.z - z);
  437. };
  438. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  439. result.x = this.x - x;
  440. result.y = this.y - y;
  441. result.z = this.z - z;
  442. };
  443. Vector3.prototype.negate = function () {
  444. return new Vector3(-this.x, -this.y, -this.z);
  445. };
  446. Vector3.prototype.scaleInPlace = function (scale) {
  447. this.x *= scale;
  448. this.y *= scale;
  449. this.z *= scale;
  450. return this;
  451. };
  452. Vector3.prototype.scale = function (scale) {
  453. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  454. };
  455. Vector3.prototype.scaleToRef = function (scale, result) {
  456. result.x = this.x * scale;
  457. result.y = this.y * scale;
  458. result.z = this.z * scale;
  459. };
  460. Vector3.prototype.equals = function (otherVector) {
  461. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  462. };
  463. Vector3.prototype.equalsWithEpsilon = function (otherVector) {
  464. 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;
  465. };
  466. Vector3.prototype.equalsToFloats = function (x, y, z) {
  467. return this.x === x && this.y === y && this.z === z;
  468. };
  469. Vector3.prototype.multiplyInPlace = function (otherVector) {
  470. this.x *= otherVector.x;
  471. this.y *= otherVector.y;
  472. this.z *= otherVector.z;
  473. };
  474. Vector3.prototype.multiply = function (otherVector) {
  475. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  476. };
  477. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  478. result.x = this.x * otherVector.x;
  479. result.y = this.y * otherVector.y;
  480. result.z = this.z * otherVector.z;
  481. };
  482. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  483. return new Vector3(this.x * x, this.y * y, this.z * z);
  484. };
  485. Vector3.prototype.divide = function (otherVector) {
  486. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  487. };
  488. Vector3.prototype.divideToRef = function (otherVector, result) {
  489. result.x = this.x / otherVector.x;
  490. result.y = this.y / otherVector.y;
  491. result.z = this.z / otherVector.z;
  492. };
  493. Vector3.prototype.MinimizeInPlace = function (other) {
  494. if (other.x < this.x)
  495. this.x = other.x;
  496. if (other.y < this.y)
  497. this.y = other.y;
  498. if (other.z < this.z)
  499. this.z = other.z;
  500. };
  501. Vector3.prototype.MaximizeInPlace = function (other) {
  502. if (other.x > this.x)
  503. this.x = other.x;
  504. if (other.y > this.y)
  505. this.y = other.y;
  506. if (other.z > this.z)
  507. this.z = other.z;
  508. };
  509. // Properties
  510. Vector3.prototype.length = function () {
  511. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  512. };
  513. Vector3.prototype.lengthSquared = function () {
  514. return (this.x * this.x + this.y * this.y + this.z * this.z);
  515. };
  516. // Methods
  517. Vector3.prototype.normalize = function () {
  518. var len = this.length();
  519. if (len === 0)
  520. return this;
  521. var num = 1.0 / len;
  522. this.x *= num;
  523. this.y *= num;
  524. this.z *= num;
  525. return this;
  526. };
  527. Vector3.prototype.clone = function () {
  528. return new Vector3(this.x, this.y, this.z);
  529. };
  530. Vector3.prototype.copyFrom = function (source) {
  531. this.x = source.x;
  532. this.y = source.y;
  533. this.z = source.z;
  534. };
  535. Vector3.prototype.copyFromFloats = function (x, y, z) {
  536. this.x = x;
  537. this.y = y;
  538. this.z = z;
  539. };
  540. // Statics
  541. Vector3.FromArray = function (array, offset) {
  542. if (!offset) {
  543. offset = 0;
  544. }
  545. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  546. };
  547. Vector3.FromArrayToRef = function (array, offset, result) {
  548. result.x = array[offset];
  549. result.y = array[offset + 1];
  550. result.z = array[offset + 2];
  551. };
  552. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  553. result.x = array[offset];
  554. result.y = array[offset + 1];
  555. result.z = array[offset + 2];
  556. };
  557. Vector3.FromFloatsToRef = function (x, y, z, result) {
  558. result.x = x;
  559. result.y = y;
  560. result.z = z;
  561. };
  562. Vector3.Zero = function () {
  563. return new Vector3(0, 0, 0);
  564. };
  565. Vector3.Up = function () {
  566. return new Vector3(0, 1.0, 0);
  567. };
  568. Vector3.TransformCoordinates = function (vector, transformation) {
  569. var result = Vector3.Zero();
  570. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  571. return result;
  572. };
  573. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  574. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  575. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  576. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  577. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  578. result.x = x / w;
  579. result.y = y / w;
  580. result.z = z / w;
  581. };
  582. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  583. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  584. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  585. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  586. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  587. result.x = rx / rw;
  588. result.y = ry / rw;
  589. result.z = rz / rw;
  590. };
  591. Vector3.TransformNormal = function (vector, transformation) {
  592. var result = Vector3.Zero();
  593. Vector3.TransformNormalToRef(vector, transformation, result);
  594. return result;
  595. };
  596. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  597. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  598. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  599. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  600. };
  601. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  602. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  603. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  604. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  605. };
  606. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  607. var squared = amount * amount;
  608. var cubed = amount * squared;
  609. 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));
  610. 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));
  611. 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));
  612. return new Vector3(x, y, z);
  613. };
  614. Vector3.Clamp = function (value, min, max) {
  615. var x = value.x;
  616. x = (x > max.x) ? max.x : x;
  617. x = (x < min.x) ? min.x : x;
  618. var y = value.y;
  619. y = (y > max.y) ? max.y : y;
  620. y = (y < min.y) ? min.y : y;
  621. var z = value.z;
  622. z = (z > max.z) ? max.z : z;
  623. z = (z < min.z) ? min.z : z;
  624. return new Vector3(x, y, z);
  625. };
  626. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  627. var squared = amount * amount;
  628. var cubed = amount * squared;
  629. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  630. var part2 = (-2.0 * cubed) + (3.0 * squared);
  631. var part3 = (cubed - (2.0 * squared)) + amount;
  632. var part4 = cubed - squared;
  633. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  634. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  635. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  636. return new Vector3(x, y, z);
  637. };
  638. Vector3.Lerp = function (start, end, amount) {
  639. var x = start.x + ((end.x - start.x) * amount);
  640. var y = start.y + ((end.y - start.y) * amount);
  641. var z = start.z + ((end.z - start.z) * amount);
  642. return new Vector3(x, y, z);
  643. };
  644. Vector3.Dot = function (left, right) {
  645. return (left.x * right.x + left.y * right.y + left.z * right.z);
  646. };
  647. Vector3.Cross = function (left, right) {
  648. var result = Vector3.Zero();
  649. Vector3.CrossToRef(left, right, result);
  650. return result;
  651. };
  652. Vector3.CrossToRef = function (left, right, result) {
  653. result.x = left.y * right.z - left.z * right.y;
  654. result.y = left.z * right.x - left.x * right.z;
  655. result.z = left.x * right.y - left.y * right.x;
  656. };
  657. Vector3.Normalize = function (vector) {
  658. var result = Vector3.Zero();
  659. Vector3.NormalizeToRef(vector, result);
  660. return result;
  661. };
  662. Vector3.NormalizeToRef = function (vector, result) {
  663. result.copyFrom(vector);
  664. result.normalize();
  665. };
  666. Vector3.Project = function (vector, world, transform, viewport) {
  667. var cw = viewport.width;
  668. var ch = viewport.height;
  669. var cx = viewport.x;
  670. var cy = viewport.y;
  671. var viewportMatrix = BABYLON.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);
  672. var finalMatrix = world.multiply(transform).multiply(viewportMatrix);
  673. return Vector3.TransformCoordinates(vector, finalMatrix);
  674. };
  675. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  676. var matrix = world.multiply(transform);
  677. matrix.invert();
  678. source.x = source.x / viewportWidth * 2 - 1;
  679. source.y = -(source.y / viewportHeight * 2 - 1);
  680. var vector = BABYLON.Vector3.TransformCoordinates(source, matrix);
  681. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  682. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  683. vector = vector.scale(1.0 / num);
  684. }
  685. return vector;
  686. };
  687. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  688. var matrix = world.multiply(view).multiply(projection);
  689. matrix.invert();
  690. source.x = source.x / viewportWidth * 2 - 1;
  691. source.y = -(source.y / viewportHeight * 2 - 1);
  692. var vector = BABYLON.Vector3.TransformCoordinates(source, matrix);
  693. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  694. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  695. vector = vector.scale(1.0 / num);
  696. }
  697. return vector;
  698. };
  699. Vector3.Minimize = function (left, right) {
  700. var min = left.clone();
  701. min.MinimizeInPlace(right);
  702. return min;
  703. };
  704. Vector3.Maximize = function (left, right) {
  705. var max = left.clone();
  706. max.MaximizeInPlace(right);
  707. return max;
  708. };
  709. Vector3.Distance = function (value1, value2) {
  710. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  711. };
  712. Vector3.DistanceSquared = function (value1, value2) {
  713. var x = value1.x - value2.x;
  714. var y = value1.y - value2.y;
  715. var z = value1.z - value2.z;
  716. return (x * x) + (y * y) + (z * z);
  717. };
  718. Vector3.Center = function (value1, value2) {
  719. var center = value1.add(value2);
  720. center.scaleInPlace(0.5);
  721. return center;
  722. };
  723. return Vector3;
  724. })();
  725. BABYLON.Vector3 = Vector3;
  726. //Vector4 class created for EulerAngle class conversion to Quaternion
  727. var Vector4 = (function () {
  728. function Vector4(x, y, z, w) {
  729. this.x = x;
  730. this.y = y;
  731. this.z = z;
  732. this.w = w;
  733. }
  734. Vector4.prototype.toString = function () {
  735. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  736. };
  737. // Operators
  738. Vector4.prototype.asArray = function () {
  739. var result = [];
  740. this.toArray(result, 0);
  741. return result;
  742. };
  743. Vector4.prototype.toArray = function (array, index) {
  744. if (index === undefined) {
  745. index = 0;
  746. }
  747. array[index] = this.x;
  748. array[index + 1] = this.y;
  749. array[index + 2] = this.z;
  750. array[index + 3] = this.w;
  751. };
  752. Vector4.prototype.addInPlace = function (otherVector) {
  753. this.x += otherVector.x;
  754. this.y += otherVector.y;
  755. this.z += otherVector.z;
  756. this.w += otherVector.w;
  757. };
  758. Vector4.prototype.add = function (otherVector) {
  759. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  760. };
  761. Vector4.prototype.addToRef = function (otherVector, result) {
  762. result.x = this.x + otherVector.x;
  763. result.y = this.y + otherVector.y;
  764. result.z = this.z + otherVector.z;
  765. result.w = this.w + otherVector.w;
  766. };
  767. Vector4.prototype.subtractInPlace = function (otherVector) {
  768. this.x -= otherVector.x;
  769. this.y -= otherVector.y;
  770. this.z -= otherVector.z;
  771. this.w -= otherVector.w;
  772. };
  773. Vector4.prototype.subtract = function (otherVector) {
  774. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  775. };
  776. Vector4.prototype.subtractToRef = function (otherVector, result) {
  777. result.x = this.x - otherVector.x;
  778. result.y = this.y - otherVector.y;
  779. result.z = this.z - otherVector.z;
  780. result.w = this.w - otherVector.w;
  781. };
  782. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  783. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  784. };
  785. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  786. result.x = this.x - x;
  787. result.y = this.y - y;
  788. result.z = this.z - z;
  789. result.w = this.w - w;
  790. };
  791. Vector4.prototype.negate = function () {
  792. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  793. };
  794. Vector4.prototype.scaleInPlace = function (scale) {
  795. this.x *= scale;
  796. this.y *= scale;
  797. this.z *= scale;
  798. this.w *= scale;
  799. return this;
  800. };
  801. Vector4.prototype.scale = function (scale) {
  802. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  803. };
  804. Vector4.prototype.scaleToRef = function (scale, result) {
  805. result.x = this.x * scale;
  806. result.y = this.y * scale;
  807. result.z = this.z * scale;
  808. result.w = this.w * scale;
  809. };
  810. Vector4.prototype.equals = function (otherVector) {
  811. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  812. };
  813. Vector4.prototype.equalsWithEpsilon = function (otherVector) {
  814. 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;
  815. };
  816. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  817. return this.x === x && this.y === y && this.z === z && this.w === w;
  818. };
  819. Vector4.prototype.multiplyInPlace = function (otherVector) {
  820. this.x *= otherVector.x;
  821. this.y *= otherVector.y;
  822. this.z *= otherVector.z;
  823. this.w *= otherVector.w;
  824. };
  825. Vector4.prototype.multiply = function (otherVector) {
  826. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  827. };
  828. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  829. result.x = this.x * otherVector.x;
  830. result.y = this.y * otherVector.y;
  831. result.z = this.z * otherVector.z;
  832. result.w = this.w * otherVector.w;
  833. };
  834. Vector4.prototype.multiplyByFloats = 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.divide = function (otherVector) {
  838. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  839. };
  840. Vector4.prototype.divideToRef = function (otherVector, result) {
  841. result.x = this.x / otherVector.x;
  842. result.y = this.y / otherVector.y;
  843. result.z = this.z / otherVector.z;
  844. result.w = this.w / otherVector.w;
  845. };
  846. Vector4.prototype.MinimizeInPlace = function (other) {
  847. if (other.x < this.x)
  848. this.x = other.x;
  849. if (other.y < this.y)
  850. this.y = other.y;
  851. if (other.z < this.z)
  852. this.z = other.z;
  853. if (other.w < this.w)
  854. this.w = other.w;
  855. };
  856. Vector4.prototype.MaximizeInPlace = function (other) {
  857. if (other.x > this.x)
  858. this.x = other.x;
  859. if (other.y > this.y)
  860. this.y = other.y;
  861. if (other.z > this.z)
  862. this.z = other.z;
  863. if (other.w > this.w)
  864. this.w = other.w;
  865. };
  866. // Properties
  867. Vector4.prototype.length = function () {
  868. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  869. };
  870. Vector4.prototype.lengthSquared = function () {
  871. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  872. };
  873. // Methods
  874. Vector4.prototype.normalize = function () {
  875. var len = this.length();
  876. if (len === 0)
  877. return this;
  878. var num = 1.0 / len;
  879. this.x *= num;
  880. this.y *= num;
  881. this.z *= num;
  882. this.w *= num;
  883. return this;
  884. };
  885. Vector4.prototype.clone = function () {
  886. return new Vector4(this.x, this.y, this.z, this.w);
  887. };
  888. Vector4.prototype.copyFrom = function (source) {
  889. this.x = source.x;
  890. this.y = source.y;
  891. this.z = source.z;
  892. this.w = source.w;
  893. };
  894. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  895. this.x = x;
  896. this.y = y;
  897. this.z = z;
  898. this.w = w;
  899. };
  900. // Statics
  901. Vector4.FromArray = function (array, offset) {
  902. if (!offset) {
  903. offset = 0;
  904. }
  905. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  906. };
  907. Vector4.FromArrayToRef = function (array, offset, result) {
  908. result.x = array[offset];
  909. result.y = array[offset + 1];
  910. result.z = array[offset + 2];
  911. result.w = array[offset + 3];
  912. };
  913. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  914. result.x = array[offset];
  915. result.y = array[offset + 1];
  916. result.z = array[offset + 2];
  917. result.w = array[offset + 3];
  918. };
  919. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  920. result.x = x;
  921. result.y = y;
  922. result.z = z;
  923. result.w = w;
  924. };
  925. Vector4.Zero = function () {
  926. return new Vector4(0, 0, 0, 0);
  927. };
  928. Vector4.Normalize = function (vector) {
  929. var result = Vector4.Zero();
  930. Vector4.NormalizeToRef(vector, result);
  931. return result;
  932. };
  933. Vector4.NormalizeToRef = function (vector, result) {
  934. result.copyFrom(vector);
  935. result.normalize();
  936. };
  937. Vector4.Minimize = function (left, right) {
  938. var min = left.clone();
  939. min.MinimizeInPlace(right);
  940. return min;
  941. };
  942. Vector4.Maximize = function (left, right) {
  943. var max = left.clone();
  944. max.MaximizeInPlace(right);
  945. return max;
  946. };
  947. Vector4.Distance = function (value1, value2) {
  948. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  949. };
  950. Vector4.DistanceSquared = function (value1, value2) {
  951. var x = value1.x - value2.x;
  952. var y = value1.y - value2.y;
  953. var z = value1.z - value2.z;
  954. var w = value1.w - value2.w;
  955. return (x * x) + (y * y) + (z * z) + (w * w);
  956. };
  957. Vector4.Center = function (value1, value2) {
  958. var center = value1.add(value2);
  959. center.scaleInPlace(0.5);
  960. return center;
  961. };
  962. return Vector4;
  963. })();
  964. BABYLON.Vector4 = Vector4;
  965. var Quaternion = (function () {
  966. function Quaternion(x, y, z, w) {
  967. if (typeof x === "undefined") { x = 0; }
  968. if (typeof y === "undefined") { y = 0; }
  969. if (typeof z === "undefined") { z = 0; }
  970. if (typeof w === "undefined") { w = 1; }
  971. this.x = x;
  972. this.y = y;
  973. this.z = z;
  974. this.w = w;
  975. }
  976. Quaternion.prototype.toString = function () {
  977. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  978. };
  979. Quaternion.prototype.asArray = function () {
  980. return [this.x, this.y, this.z, this.w];
  981. };
  982. Quaternion.prototype.equals = function (otherQuaternion) {
  983. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  984. };
  985. Quaternion.prototype.clone = function () {
  986. return new Quaternion(this.x, this.y, this.z, this.w);
  987. };
  988. Quaternion.prototype.copyFrom = function (other) {
  989. this.x = other.x;
  990. this.y = other.y;
  991. this.z = other.z;
  992. this.w = other.w;
  993. };
  994. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  995. this.x = x;
  996. this.y = y;
  997. this.z = z;
  998. this.w = w;
  999. };
  1000. Quaternion.prototype.add = function (other) {
  1001. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1002. };
  1003. Quaternion.prototype.subtract = function (other) {
  1004. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1005. };
  1006. Quaternion.prototype.scale = function (value) {
  1007. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1008. };
  1009. Quaternion.prototype.multiply = function (q1) {
  1010. var result = new Quaternion(0, 0, 0, 1.0);
  1011. this.multiplyToRef(q1, result);
  1012. return result;
  1013. };
  1014. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1015. result.x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1016. result.y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1017. result.z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1018. result.w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1019. };
  1020. Quaternion.prototype.length = function () {
  1021. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1022. };
  1023. Quaternion.prototype.normalize = function () {
  1024. var length = 1.0 / this.length();
  1025. this.x *= length;
  1026. this.y *= length;
  1027. this.z *= length;
  1028. this.w *= length;
  1029. };
  1030. Quaternion.prototype.toEulerAngles = function () {
  1031. var result = Vector3.Zero();
  1032. this.toEulerAnglesToRef(result);
  1033. return result;
  1034. };
  1035. Quaternion.prototype.toEulerAnglesToRef = function (result) {
  1036. //result is an EulerAngles in the in the z-x-z convention
  1037. var qx = this.x;
  1038. var qy = this.y;
  1039. var qz = this.z;
  1040. var qw = this.w;
  1041. var qxy = qx * qy;
  1042. var qxz = qx * qz;
  1043. var qwy = qw * qy;
  1044. var qwz = qw * qz;
  1045. var qwx = qw * qx;
  1046. var qyz = qy * qz;
  1047. var sqx = qx * qx;
  1048. var sqy = qy * qy;
  1049. var determinant = sqx + sqy;
  1050. if (determinant != 0.000 && determinant != 1.000) {
  1051. result.x = Math.atan2(qxz + qwy, qwx - qyz);
  1052. result.y = Math.acos(1 - 2 * determinant);
  1053. result.z = Math.atan2(qxz - qwy, qwx + qyz);
  1054. } else {
  1055. if (determinant == 0.000) {
  1056. result.x = 0.0;
  1057. result.y = 0.0;
  1058. 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)
  1059. } else {
  1060. 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)
  1061. result.y = Math.PI;
  1062. result.z = 0.0;
  1063. }
  1064. }
  1065. };
  1066. Quaternion.prototype.toRotationMatrix = function (result) {
  1067. var xx = this.x * this.x;
  1068. var yy = this.y * this.y;
  1069. var zz = this.z * this.z;
  1070. var xy = this.x * this.y;
  1071. var zw = this.z * this.w;
  1072. var zx = this.z * this.x;
  1073. var yw = this.y * this.w;
  1074. var yz = this.y * this.z;
  1075. var xw = this.x * this.w;
  1076. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1077. result.m[1] = 2.0 * (xy + zw);
  1078. result.m[2] = 2.0 * (zx - yw);
  1079. result.m[3] = 0;
  1080. result.m[4] = 2.0 * (xy - zw);
  1081. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1082. result.m[6] = 2.0 * (yz + xw);
  1083. result.m[7] = 0;
  1084. result.m[8] = 2.0 * (zx + yw);
  1085. result.m[9] = 2.0 * (yz - xw);
  1086. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1087. result.m[11] = 0;
  1088. result.m[12] = 0;
  1089. result.m[13] = 0;
  1090. result.m[14] = 0;
  1091. result.m[15] = 1.0;
  1092. };
  1093. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1094. var data = matrix.m;
  1095. var m11 = data[0], m12 = data[4], m13 = data[8];
  1096. var m21 = data[1], m22 = data[5], m23 = data[9];
  1097. var m31 = data[2], m32 = data[6], m33 = data[10];
  1098. var trace = m11 + m22 + m33;
  1099. var s;
  1100. if (trace > 0) {
  1101. s = 0.5 / Math.sqrt(trace + 1.0);
  1102. this.w = 0.25 / s;
  1103. this.x = (m32 - m23) * s;
  1104. this.y = (m13 - m31) * s;
  1105. this.z = (m21 - m12) * s;
  1106. return;
  1107. }
  1108. if (m11 > m22 && m11 > m33) {
  1109. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1110. this.w = (m32 - m23) / s;
  1111. this.x = 0.25 * s;
  1112. this.y = (m12 + m21) / s;
  1113. this.z = (m13 + m31) / s;
  1114. return;
  1115. }
  1116. if (m22 > m33) {
  1117. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1118. this.w = (m13 - m31) / s;
  1119. this.x = (m12 + m21) / s;
  1120. this.y = 0.25 * s;
  1121. this.z = (m23 + m32) / s;
  1122. return;
  1123. }
  1124. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1125. this.w = (m21 - m12) / s;
  1126. this.x = (m13 + m31) / s;
  1127. this.y = (m23 + m32) / s;
  1128. this.z = 0.25 * s;
  1129. };
  1130. // Statics
  1131. Quaternion.Inverse = function (q) {
  1132. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1133. };
  1134. Quaternion.RotationAxis = function (axis, angle) {
  1135. var result = new Quaternion();
  1136. var sin = Math.sin(angle / 2);
  1137. result.w = Math.cos(angle / 2);
  1138. result.x = axis.x * sin;
  1139. result.y = axis.y * sin;
  1140. result.z = axis.z * sin;
  1141. return result;
  1142. };
  1143. Quaternion.FromArray = function (array, offset) {
  1144. if (!offset) {
  1145. offset = 0;
  1146. }
  1147. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1148. };
  1149. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1150. var result = new Quaternion();
  1151. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1152. return result;
  1153. };
  1154. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1155. var halfRoll = roll * 0.5;
  1156. var halfPitch = pitch * 0.5;
  1157. var halfYaw = yaw * 0.5;
  1158. var sinRoll = Math.sin(halfRoll);
  1159. var cosRoll = Math.cos(halfRoll);
  1160. var sinPitch = Math.sin(halfPitch);
  1161. var cosPitch = Math.cos(halfPitch);
  1162. var sinYaw = Math.sin(halfYaw);
  1163. var cosYaw = Math.cos(halfYaw);
  1164. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1165. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1166. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1167. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1168. };
  1169. Quaternion.Slerp = function (left, right, amount) {
  1170. var num2;
  1171. var num3;
  1172. var num = amount;
  1173. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1174. var flag = false;
  1175. if (num4 < 0) {
  1176. flag = true;
  1177. num4 = -num4;
  1178. }
  1179. if (num4 > 0.999999) {
  1180. num3 = 1 - num;
  1181. num2 = flag ? -num : num;
  1182. } else {
  1183. var num5 = Math.acos(num4);
  1184. var num6 = (1.0 / Math.sin(num5));
  1185. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1186. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1187. }
  1188. 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));
  1189. };
  1190. return Quaternion;
  1191. })();
  1192. BABYLON.Quaternion = Quaternion;
  1193. var Matrix = (function () {
  1194. function Matrix() {
  1195. this.m = new Float32Array(16);
  1196. }
  1197. // Properties
  1198. Matrix.prototype.isIdentity = function () {
  1199. if (this.m[0] != 1.0 || this.m[5] != 1.0 || this.m[10] != 1.0 || this.m[15] != 1.0)
  1200. return false;
  1201. 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)
  1202. return false;
  1203. return true;
  1204. };
  1205. Matrix.prototype.determinant = function () {
  1206. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1207. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1208. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1209. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1210. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1211. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1212. 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))));
  1213. };
  1214. // Methods
  1215. Matrix.prototype.toArray = function () {
  1216. return this.m;
  1217. };
  1218. Matrix.prototype.asArray = function () {
  1219. return this.toArray();
  1220. };
  1221. Matrix.prototype.invert = function () {
  1222. this.invertToRef(this);
  1223. };
  1224. Matrix.prototype.invertToRef = function (other) {
  1225. var l1 = this.m[0];
  1226. var l2 = this.m[1];
  1227. var l3 = this.m[2];
  1228. var l4 = this.m[3];
  1229. var l5 = this.m[4];
  1230. var l6 = this.m[5];
  1231. var l7 = this.m[6];
  1232. var l8 = this.m[7];
  1233. var l9 = this.m[8];
  1234. var l10 = this.m[9];
  1235. var l11 = this.m[10];
  1236. var l12 = this.m[11];
  1237. var l13 = this.m[12];
  1238. var l14 = this.m[13];
  1239. var l15 = this.m[14];
  1240. var l16 = this.m[15];
  1241. var l17 = (l11 * l16) - (l12 * l15);
  1242. var l18 = (l10 * l16) - (l12 * l14);
  1243. var l19 = (l10 * l15) - (l11 * l14);
  1244. var l20 = (l9 * l16) - (l12 * l13);
  1245. var l21 = (l9 * l15) - (l11 * l13);
  1246. var l22 = (l9 * l14) - (l10 * l13);
  1247. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1248. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1249. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1250. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1251. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1252. var l28 = (l7 * l16) - (l8 * l15);
  1253. var l29 = (l6 * l16) - (l8 * l14);
  1254. var l30 = (l6 * l15) - (l7 * l14);
  1255. var l31 = (l5 * l16) - (l8 * l13);
  1256. var l32 = (l5 * l15) - (l7 * l13);
  1257. var l33 = (l5 * l14) - (l6 * l13);
  1258. var l34 = (l7 * l12) - (l8 * l11);
  1259. var l35 = (l6 * l12) - (l8 * l10);
  1260. var l36 = (l6 * l11) - (l7 * l10);
  1261. var l37 = (l5 * l12) - (l8 * l9);
  1262. var l38 = (l5 * l11) - (l7 * l9);
  1263. var l39 = (l5 * l10) - (l6 * l9);
  1264. other.m[0] = l23 * l27;
  1265. other.m[4] = l24 * l27;
  1266. other.m[8] = l25 * l27;
  1267. other.m[12] = l26 * l27;
  1268. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1269. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1270. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1271. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1272. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1273. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1274. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1275. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1276. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1277. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1278. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1279. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1280. };
  1281. Matrix.prototype.setTranslation = function (vector3) {
  1282. this.m[12] = vector3.x;
  1283. this.m[13] = vector3.y;
  1284. this.m[14] = vector3.z;
  1285. };
  1286. Matrix.prototype.multiply = function (other) {
  1287. var result = new Matrix();
  1288. this.multiplyToRef(other, result);
  1289. return result;
  1290. };
  1291. Matrix.prototype.copyFrom = function (other) {
  1292. for (var index = 0; index < 16; index++) {
  1293. this.m[index] = other.m[index];
  1294. }
  1295. };
  1296. Matrix.prototype.copyToArray = function (array, offset) {
  1297. if (typeof offset === "undefined") { offset = 0; }
  1298. for (var index = 0; index < 16; index++) {
  1299. array[offset + index] = this.m[index];
  1300. }
  1301. };
  1302. Matrix.prototype.multiplyToRef = function (other, result) {
  1303. this.multiplyToArray(other, result.m, 0);
  1304. };
  1305. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1306. var tm0 = this.m[0];
  1307. var tm1 = this.m[1];
  1308. var tm2 = this.m[2];
  1309. var tm3 = this.m[3];
  1310. var tm4 = this.m[4];
  1311. var tm5 = this.m[5];
  1312. var tm6 = this.m[6];
  1313. var tm7 = this.m[7];
  1314. var tm8 = this.m[8];
  1315. var tm9 = this.m[9];
  1316. var tm10 = this.m[10];
  1317. var tm11 = this.m[11];
  1318. var tm12 = this.m[12];
  1319. var tm13 = this.m[13];
  1320. var tm14 = this.m[14];
  1321. var tm15 = this.m[15];
  1322. var om0 = other.m[0];
  1323. var om1 = other.m[1];
  1324. var om2 = other.m[2];
  1325. var om3 = other.m[3];
  1326. var om4 = other.m[4];
  1327. var om5 = other.m[5];
  1328. var om6 = other.m[6];
  1329. var om7 = other.m[7];
  1330. var om8 = other.m[8];
  1331. var om9 = other.m[9];
  1332. var om10 = other.m[10];
  1333. var om11 = other.m[11];
  1334. var om12 = other.m[12];
  1335. var om13 = other.m[13];
  1336. var om14 = other.m[14];
  1337. var om15 = other.m[15];
  1338. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1339. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1340. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1341. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1342. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1343. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1344. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1345. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1346. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1347. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1348. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1349. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1350. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1351. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1352. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1353. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1354. };
  1355. Matrix.prototype.equals = function (value) {
  1356. 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]);
  1357. };
  1358. Matrix.prototype.clone = function () {
  1359. 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]);
  1360. };
  1361. // Statics
  1362. Matrix.FromArray = function (array, offset) {
  1363. var result = new Matrix();
  1364. if (!offset) {
  1365. offset = 0;
  1366. }
  1367. Matrix.FromArrayToRef(array, offset, result);
  1368. return result;
  1369. };
  1370. Matrix.FromArrayToRef = function (array, offset, result) {
  1371. for (var index = 0; index < 16; index++) {
  1372. result.m[index] = array[index + offset];
  1373. }
  1374. };
  1375. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1376. result.m[0] = initialM11;
  1377. result.m[1] = initialM12;
  1378. result.m[2] = initialM13;
  1379. result.m[3] = initialM14;
  1380. result.m[4] = initialM21;
  1381. result.m[5] = initialM22;
  1382. result.m[6] = initialM23;
  1383. result.m[7] = initialM24;
  1384. result.m[8] = initialM31;
  1385. result.m[9] = initialM32;
  1386. result.m[10] = initialM33;
  1387. result.m[11] = initialM34;
  1388. result.m[12] = initialM41;
  1389. result.m[13] = initialM42;
  1390. result.m[14] = initialM43;
  1391. result.m[15] = initialM44;
  1392. };
  1393. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1394. var result = new Matrix();
  1395. result.m[0] = initialM11;
  1396. result.m[1] = initialM12;
  1397. result.m[2] = initialM13;
  1398. result.m[3] = initialM14;
  1399. result.m[4] = initialM21;
  1400. result.m[5] = initialM22;
  1401. result.m[6] = initialM23;
  1402. result.m[7] = initialM24;
  1403. result.m[8] = initialM31;
  1404. result.m[9] = initialM32;
  1405. result.m[10] = initialM33;
  1406. result.m[11] = initialM34;
  1407. result.m[12] = initialM41;
  1408. result.m[13] = initialM42;
  1409. result.m[14] = initialM43;
  1410. result.m[15] = initialM44;
  1411. return result;
  1412. };
  1413. Matrix.Identity = function () {
  1414. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1415. };
  1416. Matrix.IdentityToRef = function (result) {
  1417. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1418. };
  1419. Matrix.Zero = function () {
  1420. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1421. };
  1422. Matrix.RotationX = function (angle) {
  1423. var result = new Matrix();
  1424. Matrix.RotationXToRef(angle, result);
  1425. return result;
  1426. };
  1427. Matrix.Invert = function (source) {
  1428. var result = new Matrix();
  1429. source.invertToRef(result);
  1430. return result;
  1431. };
  1432. Matrix.RotationXToRef = function (angle, result) {
  1433. var s = Math.sin(angle);
  1434. var c = Math.cos(angle);
  1435. result.m[0] = 1.0;
  1436. result.m[15] = 1.0;
  1437. result.m[5] = c;
  1438. result.m[10] = c;
  1439. result.m[9] = -s;
  1440. result.m[6] = s;
  1441. result.m[1] = 0;
  1442. result.m[2] = 0;
  1443. result.m[3] = 0;
  1444. result.m[4] = 0;
  1445. result.m[7] = 0;
  1446. result.m[8] = 0;
  1447. result.m[11] = 0;
  1448. result.m[12] = 0;
  1449. result.m[13] = 0;
  1450. result.m[14] = 0;
  1451. };
  1452. Matrix.RotationY = function (angle) {
  1453. var result = new Matrix();
  1454. Matrix.RotationYToRef(angle, result);
  1455. return result;
  1456. };
  1457. Matrix.RotationYToRef = function (angle, result) {
  1458. var s = Math.sin(angle);
  1459. var c = Math.cos(angle);
  1460. result.m[5] = 1.0;
  1461. result.m[15] = 1.0;
  1462. result.m[0] = c;
  1463. result.m[2] = -s;
  1464. result.m[8] = s;
  1465. result.m[10] = c;
  1466. result.m[1] = 0;
  1467. result.m[3] = 0;
  1468. result.m[4] = 0;
  1469. result.m[6] = 0;
  1470. result.m[7] = 0;
  1471. result.m[9] = 0;
  1472. result.m[11] = 0;
  1473. result.m[12] = 0;
  1474. result.m[13] = 0;
  1475. result.m[14] = 0;
  1476. };
  1477. Matrix.RotationZ = function (angle) {
  1478. var result = new Matrix();
  1479. Matrix.RotationZToRef(angle, result);
  1480. return result;
  1481. };
  1482. Matrix.RotationZToRef = function (angle, result) {
  1483. var s = Math.sin(angle);
  1484. var c = Math.cos(angle);
  1485. result.m[10] = 1.0;
  1486. result.m[15] = 1.0;
  1487. result.m[0] = c;
  1488. result.m[1] = s;
  1489. result.m[4] = -s;
  1490. result.m[5] = c;
  1491. result.m[2] = 0;
  1492. result.m[3] = 0;
  1493. result.m[6] = 0;
  1494. result.m[7] = 0;
  1495. result.m[8] = 0;
  1496. result.m[9] = 0;
  1497. result.m[11] = 0;
  1498. result.m[12] = 0;
  1499. result.m[13] = 0;
  1500. result.m[14] = 0;
  1501. };
  1502. Matrix.RotationAxis = function (axis, angle) {
  1503. var s = Math.sin(-angle);
  1504. var c = Math.cos(-angle);
  1505. var c1 = 1 - c;
  1506. axis.normalize();
  1507. var result = Matrix.Zero();
  1508. result.m[0] = (axis.x * axis.x) * c1 + c;
  1509. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1510. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1511. result.m[3] = 0.0;
  1512. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1513. result.m[5] = (axis.y * axis.y) * c1 + c;
  1514. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  1515. result.m[7] = 0.0;
  1516. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  1517. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  1518. result.m[10] = (axis.z * axis.z) * c1 + c;
  1519. result.m[11] = 0.0;
  1520. result.m[15] = 1.0;
  1521. return result;
  1522. };
  1523. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1524. var result = new Matrix();
  1525. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1526. return result;
  1527. };
  1528. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1529. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  1530. this._tempQuaternion.toRotationMatrix(result);
  1531. };
  1532. Matrix.Scaling = function (x, y, z) {
  1533. var result = Matrix.Zero();
  1534. Matrix.ScalingToRef(x, y, z, result);
  1535. return result;
  1536. };
  1537. Matrix.ScalingToRef = function (x, y, z, result) {
  1538. result.m[0] = x;
  1539. result.m[1] = 0;
  1540. result.m[2] = 0;
  1541. result.m[3] = 0;
  1542. result.m[4] = 0;
  1543. result.m[5] = y;
  1544. result.m[6] = 0;
  1545. result.m[7] = 0;
  1546. result.m[8] = 0;
  1547. result.m[9] = 0;
  1548. result.m[10] = z;
  1549. result.m[11] = 0;
  1550. result.m[12] = 0;
  1551. result.m[13] = 0;
  1552. result.m[14] = 0;
  1553. result.m[15] = 1.0;
  1554. };
  1555. Matrix.Translation = function (x, y, z) {
  1556. var result = Matrix.Identity();
  1557. Matrix.TranslationToRef(x, y, z, result);
  1558. return result;
  1559. };
  1560. Matrix.TranslationToRef = function (x, y, z, result) {
  1561. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  1562. };
  1563. Matrix.LookAtLH = function (eye, target, up) {
  1564. var result = Matrix.Zero();
  1565. Matrix.LookAtLHToRef(eye, target, up, result);
  1566. return result;
  1567. };
  1568. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  1569. // Z axis
  1570. target.subtractToRef(eye, this._zAxis);
  1571. this._zAxis.normalize();
  1572. // X axis
  1573. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  1574. this._xAxis.normalize();
  1575. // Y axis
  1576. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  1577. this._yAxis.normalize();
  1578. // Eye angles
  1579. var ex = -Vector3.Dot(this._xAxis, eye);
  1580. var ey = -Vector3.Dot(this._yAxis, eye);
  1581. var ez = -Vector3.Dot(this._zAxis, eye);
  1582. 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);
  1583. };
  1584. Matrix.OrthoLH = function (width, height, znear, zfar) {
  1585. var hw = 2.0 / width;
  1586. var hh = 2.0 / height;
  1587. var id = 1.0 / (zfar - znear);
  1588. var nid = znear / (znear - zfar);
  1589. return Matrix.FromValues(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1);
  1590. };
  1591. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  1592. var matrix = Matrix.Zero();
  1593. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  1594. return matrix;
  1595. };
  1596. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  1597. result.m[0] = 2.0 / (right - left);
  1598. result.m[1] = result.m[2] = result.m[3] = 0;
  1599. result.m[5] = 2.0 / (top - bottom);
  1600. result.m[4] = result.m[6] = result.m[7] = 0;
  1601. result.m[10] = -1.0 / (znear - zfar);
  1602. result.m[8] = result.m[9] = result.m[11] = 0;
  1603. result.m[12] = (left + right) / (left - right);
  1604. result.m[13] = (top + bottom) / (bottom - top);
  1605. result.m[14] = znear / (znear - zfar);
  1606. result.m[15] = 1.0;
  1607. };
  1608. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  1609. var matrix = Matrix.Zero();
  1610. matrix.m[0] = (2.0 * znear) / width;
  1611. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  1612. matrix.m[5] = (2.0 * znear) / height;
  1613. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  1614. matrix.m[10] = -zfar / (znear - zfar);
  1615. matrix.m[8] = matrix.m[9] = 0.0;
  1616. matrix.m[11] = 1.0;
  1617. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  1618. matrix.m[14] = (znear * zfar) / (znear - zfar);
  1619. return matrix;
  1620. };
  1621. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  1622. var matrix = Matrix.Zero();
  1623. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  1624. return matrix;
  1625. };
  1626. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result) {
  1627. var tan = 1.0 / (Math.tan(fov * 0.5));
  1628. result.m[0] = tan / aspect;
  1629. result.m[1] = result.m[2] = result.m[3] = 0.0;
  1630. result.m[5] = tan;
  1631. result.m[4] = result.m[6] = result.m[7] = 0.0;
  1632. result.m[8] = result.m[9] = 0.0;
  1633. result.m[10] = -zfar / (znear - zfar);
  1634. result.m[11] = 1.0;
  1635. result.m[12] = result.m[13] = result.m[15] = 0.0;
  1636. result.m[14] = (znear * zfar) / (znear - zfar);
  1637. };
  1638. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  1639. var cw = viewport.width;
  1640. var ch = viewport.height;
  1641. var cx = viewport.x;
  1642. var cy = viewport.y;
  1643. 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);
  1644. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  1645. };
  1646. Matrix.Transpose = function (matrix) {
  1647. var result = new Matrix();
  1648. result.m[0] = matrix.m[0];
  1649. result.m[1] = matrix.m[4];
  1650. result.m[2] = matrix.m[8];
  1651. result.m[3] = matrix.m[12];
  1652. result.m[4] = matrix.m[1];
  1653. result.m[5] = matrix.m[5];
  1654. result.m[6] = matrix.m[9];
  1655. result.m[7] = matrix.m[13];
  1656. result.m[8] = matrix.m[2];
  1657. result.m[9] = matrix.m[6];
  1658. result.m[10] = matrix.m[10];
  1659. result.m[11] = matrix.m[14];
  1660. result.m[12] = matrix.m[3];
  1661. result.m[13] = matrix.m[7];
  1662. result.m[14] = matrix.m[11];
  1663. result.m[15] = matrix.m[15];
  1664. return result;
  1665. };
  1666. Matrix.Reflection = function (plane) {
  1667. var matrix = new Matrix();
  1668. Matrix.ReflectionToRef(plane, matrix);
  1669. return matrix;
  1670. };
  1671. Matrix.ReflectionToRef = function (plane, result) {
  1672. plane.normalize();
  1673. var x = plane.normal.x;
  1674. var y = plane.normal.y;
  1675. var z = plane.normal.z;
  1676. var temp = -2 * x;
  1677. var temp2 = -2 * y;
  1678. var temp3 = -2 * z;
  1679. result.m[0] = (temp * x) + 1;
  1680. result.m[1] = temp2 * x;
  1681. result.m[2] = temp3 * x;
  1682. result.m[3] = 0.0;
  1683. result.m[4] = temp * y;
  1684. result.m[5] = (temp2 * y) + 1;
  1685. result.m[6] = temp3 * y;
  1686. result.m[7] = 0.0;
  1687. result.m[8] = temp * z;
  1688. result.m[9] = temp2 * z;
  1689. result.m[10] = (temp3 * z) + 1;
  1690. result.m[11] = 0.0;
  1691. result.m[12] = temp * plane.d;
  1692. result.m[13] = temp2 * plane.d;
  1693. result.m[14] = temp3 * plane.d;
  1694. result.m[15] = 1.0;
  1695. };
  1696. Matrix._tempQuaternion = new Quaternion();
  1697. Matrix._xAxis = Vector3.Zero();
  1698. Matrix._yAxis = Vector3.Zero();
  1699. Matrix._zAxis = Vector3.Zero();
  1700. return Matrix;
  1701. })();
  1702. BABYLON.Matrix = Matrix;
  1703. var Plane = (function () {
  1704. function Plane(a, b, c, d) {
  1705. this.normal = new Vector3(a, b, c);
  1706. this.d = d;
  1707. }
  1708. Plane.prototype.asArray = function () {
  1709. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  1710. };
  1711. // Methods
  1712. Plane.prototype.clone = function () {
  1713. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  1714. };
  1715. Plane.prototype.normalize = function () {
  1716. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  1717. var magnitude = 0;
  1718. if (norm != 0) {
  1719. magnitude = 1.0 / norm;
  1720. }
  1721. this.normal.x *= magnitude;
  1722. this.normal.y *= magnitude;
  1723. this.normal.z *= magnitude;
  1724. this.d *= magnitude;
  1725. };
  1726. Plane.prototype.transform = function (transformation) {
  1727. var transposedMatrix = BABYLON.Matrix.Transpose(transformation);
  1728. var x = this.normal.x;
  1729. var y = this.normal.y;
  1730. var z = this.normal.z;
  1731. var d = this.d;
  1732. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  1733. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  1734. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  1735. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  1736. return new BABYLON.Plane(normalX, normalY, normalZ, finalD);
  1737. };
  1738. Plane.prototype.dotCoordinate = function (point) {
  1739. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  1740. };
  1741. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  1742. var x1 = point2.x - point1.x;
  1743. var y1 = point2.y - point1.y;
  1744. var z1 = point2.z - point1.z;
  1745. var x2 = point3.x - point1.x;
  1746. var y2 = point3.y - point1.y;
  1747. var z2 = point3.z - point1.z;
  1748. var yz = (y1 * z2) - (z1 * y2);
  1749. var xz = (z1 * x2) - (x1 * z2);
  1750. var xy = (x1 * y2) - (y1 * x2);
  1751. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  1752. var invPyth;
  1753. if (pyth != 0) {
  1754. invPyth = 1.0 / pyth;
  1755. } else {
  1756. invPyth = 0;
  1757. }
  1758. this.normal.x = yz * invPyth;
  1759. this.normal.y = xz * invPyth;
  1760. this.normal.z = xy * invPyth;
  1761. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  1762. };
  1763. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  1764. var dot = Vector3.Dot(this.normal, direction);
  1765. return (dot <= epsilon);
  1766. };
  1767. Plane.prototype.signedDistanceTo = function (point) {
  1768. return Vector3.Dot(point, this.normal) + this.d;
  1769. };
  1770. // Statics
  1771. Plane.FromArray = function (array) {
  1772. return new BABYLON.Plane(array[0], array[1], array[2], array[3]);
  1773. };
  1774. Plane.FromPoints = function (point1, point2, point3) {
  1775. var result = new BABYLON.Plane(0, 0, 0, 0);
  1776. result.copyFromPoints(point1, point2, point3);
  1777. return result;
  1778. };
  1779. Plane.FromPositionAndNormal = function (origin, normal) {
  1780. var result = new BABYLON.Plane(0, 0, 0, 0);
  1781. normal.normalize();
  1782. result.normal = normal;
  1783. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  1784. return result;
  1785. };
  1786. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  1787. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  1788. return Vector3.Dot(point, normal) + d;
  1789. };
  1790. return Plane;
  1791. })();
  1792. BABYLON.Plane = Plane;
  1793. var Viewport = (function () {
  1794. function Viewport(x, y, width, height) {
  1795. this.x = x;
  1796. this.y = y;
  1797. this.width = width;
  1798. this.height = height;
  1799. }
  1800. Viewport.prototype.toGlobal = function (engine) {
  1801. var width = engine.getRenderWidth();
  1802. var height = engine.getRenderHeight();
  1803. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  1804. };
  1805. return Viewport;
  1806. })();
  1807. BABYLON.Viewport = Viewport;
  1808. var Frustum = (function () {
  1809. function Frustum() {
  1810. }
  1811. Frustum.GetPlanes = function (transform) {
  1812. var frustumPlanes = [];
  1813. for (var index = 0; index < 6; index++) {
  1814. frustumPlanes.push(new Plane(0, 0, 0, 0));
  1815. }
  1816. Frustum.GetPlanesToRef(transform, frustumPlanes);
  1817. return frustumPlanes;
  1818. };
  1819. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  1820. // Near
  1821. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  1822. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  1823. frustumPlanes[0].normal.z = transform.m[10] + transform.m[10];
  1824. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  1825. frustumPlanes[0].normalize();
  1826. // Far
  1827. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  1828. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  1829. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  1830. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  1831. frustumPlanes[1].normalize();
  1832. // Left
  1833. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  1834. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  1835. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  1836. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  1837. frustumPlanes[2].normalize();
  1838. // Right
  1839. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  1840. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  1841. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  1842. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  1843. frustumPlanes[3].normalize();
  1844. // Top
  1845. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  1846. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  1847. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  1848. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  1849. frustumPlanes[4].normalize();
  1850. // Bottom
  1851. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  1852. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  1853. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  1854. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  1855. frustumPlanes[5].normalize();
  1856. };
  1857. return Frustum;
  1858. })();
  1859. BABYLON.Frustum = Frustum;
  1860. var Ray = (function () {
  1861. function Ray(origin, direction, length) {
  1862. if (typeof length === "undefined") { length = Number.MAX_VALUE; }
  1863. this.origin = origin;
  1864. this.direction = direction;
  1865. this.length = length;
  1866. }
  1867. // Methods
  1868. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  1869. var d = 0.0;
  1870. var maxValue = Number.MAX_VALUE;
  1871. if (Math.abs(this.direction.x) < 0.0000001) {
  1872. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  1873. return false;
  1874. }
  1875. } else {
  1876. var inv = 1.0 / this.direction.x;
  1877. var min = (minimum.x - this.origin.x) * inv;
  1878. var max = (maximum.x - this.origin.x) * inv;
  1879. if (max == -Infinity) {
  1880. max = Infinity;
  1881. }
  1882. if (min > max) {
  1883. var temp = min;
  1884. min = max;
  1885. max = temp;
  1886. }
  1887. d = Math.max(min, d);
  1888. maxValue = Math.min(max, maxValue);
  1889. if (d > maxValue) {
  1890. return false;
  1891. }
  1892. }
  1893. if (Math.abs(this.direction.y) < 0.0000001) {
  1894. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  1895. return false;
  1896. }
  1897. } else {
  1898. inv = 1.0 / this.direction.y;
  1899. min = (minimum.y - this.origin.y) * inv;
  1900. max = (maximum.y - this.origin.y) * inv;
  1901. if (max == -Infinity) {
  1902. max = Infinity;
  1903. }
  1904. if (min > max) {
  1905. temp = min;
  1906. min = max;
  1907. max = temp;
  1908. }
  1909. d = Math.max(min, d);
  1910. maxValue = Math.min(max, maxValue);
  1911. if (d > maxValue) {
  1912. return false;
  1913. }
  1914. }
  1915. if (Math.abs(this.direction.z) < 0.0000001) {
  1916. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  1917. return false;
  1918. }
  1919. } else {
  1920. inv = 1.0 / this.direction.z;
  1921. min = (minimum.z - this.origin.z) * inv;
  1922. max = (maximum.z - this.origin.z) * inv;
  1923. if (max == -Infinity) {
  1924. max = Infinity;
  1925. }
  1926. if (min > max) {
  1927. temp = min;
  1928. min = max;
  1929. max = temp;
  1930. }
  1931. d = Math.max(min, d);
  1932. maxValue = Math.min(max, maxValue);
  1933. if (d > maxValue) {
  1934. return false;
  1935. }
  1936. }
  1937. return true;
  1938. };
  1939. Ray.prototype.intersectsBox = function (box) {
  1940. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  1941. };
  1942. Ray.prototype.intersectsSphere = function (sphere) {
  1943. var x = sphere.center.x - this.origin.x;
  1944. var y = sphere.center.y - this.origin.y;
  1945. var z = sphere.center.z - this.origin.z;
  1946. var pyth = (x * x) + (y * y) + (z * z);
  1947. var rr = sphere.radius * sphere.radius;
  1948. if (pyth <= rr) {
  1949. return true;
  1950. }
  1951. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  1952. if (dot < 0.0) {
  1953. return false;
  1954. }
  1955. var temp = pyth - (dot * dot);
  1956. return temp <= rr;
  1957. };
  1958. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  1959. if (!this._edge1) {
  1960. this._edge1 = BABYLON.Vector3.Zero();
  1961. this._edge2 = BABYLON.Vector3.Zero();
  1962. this._pvec = BABYLON.Vector3.Zero();
  1963. this._tvec = BABYLON.Vector3.Zero();
  1964. this._qvec = BABYLON.Vector3.Zero();
  1965. }
  1966. vertex1.subtractToRef(vertex0, this._edge1);
  1967. vertex2.subtractToRef(vertex0, this._edge2);
  1968. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  1969. var det = Vector3.Dot(this._edge1, this._pvec);
  1970. if (det === 0) {
  1971. return null;
  1972. }
  1973. var invdet = 1 / det;
  1974. this.origin.subtractToRef(vertex0, this._tvec);
  1975. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  1976. if (bu < 0 || bu > 1.0) {
  1977. return null;
  1978. }
  1979. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  1980. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  1981. if (bv < 0 || bu + bv > 1.0) {
  1982. return null;
  1983. }
  1984. //check if the distance is longer than the predefined length.
  1985. var distance = Vector3.Dot(this._edge2, this._qvec) * invdet;
  1986. if (distance > this.length) {
  1987. return null;
  1988. }
  1989. return new BABYLON.IntersectionInfo(bu, bv, distance);
  1990. };
  1991. // Statics
  1992. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  1993. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  1994. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  1995. var direction = end.subtract(start);
  1996. direction.normalize();
  1997. return new Ray(start, direction);
  1998. };
  1999. /**
  2000. * 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
  2001. * transformed to the given world matrix.
  2002. * @param origin The origin point
  2003. * @param end The end point
  2004. * @param world a matrix to transform the ray to. Default is the identity matrix.
  2005. */
  2006. Ray.CreateNewFromTo = function (origin, end, world) {
  2007. if (typeof world === "undefined") { world = BABYLON.Matrix.Identity(); }
  2008. var direction = end.subtract(origin);
  2009. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  2010. direction.normalize();
  2011. return Ray.Transform(new Ray(origin, direction, length), world);
  2012. };
  2013. Ray.Transform = function (ray, matrix) {
  2014. var newOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, matrix);
  2015. var newDirection = BABYLON.Vector3.TransformNormal(ray.direction, matrix);
  2016. return new Ray(newOrigin, newDirection, ray.length);
  2017. };
  2018. return Ray;
  2019. })();
  2020. BABYLON.Ray = Ray;
  2021. (function (Space) {
  2022. Space[Space["LOCAL"] = 0] = "LOCAL";
  2023. Space[Space["WORLD"] = 1] = "WORLD";
  2024. })(BABYLON.Space || (BABYLON.Space = {}));
  2025. var Space = BABYLON.Space;
  2026. var Axis = (function () {
  2027. function Axis() {
  2028. }
  2029. Axis.X = new BABYLON.Vector3(1, 0, 0);
  2030. Axis.Y = new BABYLON.Vector3(0, 1, 0);
  2031. Axis.Z = new BABYLON.Vector3(0, 0, 1);
  2032. return Axis;
  2033. })();
  2034. BABYLON.Axis = Axis;
  2035. ;
  2036. var BezierCurve = (function () {
  2037. function BezierCurve() {
  2038. }
  2039. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2040. // Extract X (which is equal to time here)
  2041. var f0 = 1 - 3 * x2 + 3 * x1;
  2042. var f1 = 3 * x2 - 6 * x1;
  2043. var f2 = 3 * x1;
  2044. var refinedT = t;
  2045. for (var i = 0; i < 5; i++) {
  2046. var refinedT2 = refinedT * refinedT;
  2047. var refinedT3 = refinedT2 * refinedT;
  2048. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2049. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2050. refinedT -= (x - t) * slope;
  2051. refinedT = Math.min(1, Math.max(0, refinedT));
  2052. }
  2053. // Resolve cubic bezier for the given x
  2054. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 + 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 + Math.pow(refinedT, 3);
  2055. };
  2056. return BezierCurve;
  2057. })();
  2058. BABYLON.BezierCurve = BezierCurve;
  2059. })(BABYLON || (BABYLON = {}));
  2060. //# sourceMappingURL=babylon.math.js.map
  2061. var BABYLON;
  2062. (function (BABYLON) {
  2063. // Screenshots
  2064. var screenshotCanvas;
  2065. var cloneValue = function (source, destinationObject) {
  2066. if (!source)
  2067. return null;
  2068. if (source instanceof BABYLON.Mesh) {
  2069. return null;
  2070. }
  2071. if (source instanceof BABYLON.SubMesh) {
  2072. return source.clone(destinationObject);
  2073. } else if (source.clone) {
  2074. return source.clone();
  2075. }
  2076. return null;
  2077. };
  2078. var Tools = (function () {
  2079. function Tools() {
  2080. }
  2081. Tools.GetFilename = function (path) {
  2082. var index = path.lastIndexOf("/");
  2083. if (index < 0)
  2084. return path;
  2085. return path.substring(index + 1);
  2086. };
  2087. Tools.GetDOMTextContent = function (element) {
  2088. var result = "";
  2089. var child = element.firstChild;
  2090. while (child) {
  2091. if (child.nodeType == 3) {
  2092. result += child.textContent;
  2093. }
  2094. child = child.nextSibling;
  2095. }
  2096. return result;
  2097. };
  2098. Tools.ToDegrees = function (angle) {
  2099. return angle * 180 / Math.PI;
  2100. };
  2101. Tools.ToRadians = function (angle) {
  2102. return angle * Math.PI / 180;
  2103. };
  2104. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  2105. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  2106. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  2107. for (var index = indexStart; index < indexStart + indexCount; index++) {
  2108. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  2109. minimum = BABYLON.Vector3.Minimize(current, minimum);
  2110. maximum = BABYLON.Vector3.Maximize(current, maximum);
  2111. }
  2112. return {
  2113. minimum: minimum,
  2114. maximum: maximum
  2115. };
  2116. };
  2117. Tools.ExtractMinAndMax = function (positions, start, count) {
  2118. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  2119. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  2120. for (var index = start; index < start + count; index++) {
  2121. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  2122. minimum = BABYLON.Vector3.Minimize(current, minimum);
  2123. maximum = BABYLON.Vector3.Maximize(current, maximum);
  2124. }
  2125. return {
  2126. minimum: minimum,
  2127. maximum: maximum
  2128. };
  2129. };
  2130. Tools.MakeArray = function (obj, allowsNullUndefined) {
  2131. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  2132. return undefined;
  2133. return Array.isArray(obj) ? obj : [obj];
  2134. };
  2135. // Misc.
  2136. Tools.GetPointerPrefix = function () {
  2137. var eventPrefix = "pointer";
  2138. // Check if hand.js is referenced or if the browser natively supports pointer events
  2139. if (!navigator.pointerEnabled) {
  2140. eventPrefix = "mouse";
  2141. }
  2142. return eventPrefix;
  2143. };
  2144. Tools.QueueNewFrame = function (func) {
  2145. if (window.requestAnimationFrame)
  2146. window.requestAnimationFrame(func);
  2147. else if (window.msRequestAnimationFrame)
  2148. window.msRequestAnimationFrame(func);
  2149. else if (window.webkitRequestAnimationFrame)
  2150. window.webkitRequestAnimationFrame(func);
  2151. else if (window.mozRequestAnimationFrame)
  2152. window.mozRequestAnimationFrame(func);
  2153. else if (window.oRequestAnimationFrame)
  2154. window.oRequestAnimationFrame(func);
  2155. else {
  2156. window.setTimeout(func, 16);
  2157. }
  2158. };
  2159. Tools.RequestFullscreen = function (element) {
  2160. if (element.requestFullscreen)
  2161. element.requestFullscreen();
  2162. else if (element.msRequestFullscreen)
  2163. element.msRequestFullscreen();
  2164. else if (element.webkitRequestFullscreen)
  2165. element.webkitRequestFullscreen();
  2166. else if (element.mozRequestFullScreen)
  2167. element.mozRequestFullScreen();
  2168. };
  2169. Tools.ExitFullscreen = function () {
  2170. if (document.exitFullscreen) {
  2171. document.exitFullscreen();
  2172. } else if (document.mozCancelFullScreen) {
  2173. document.mozCancelFullScreen();
  2174. } else if (document.webkitCancelFullScreen) {
  2175. document.webkitCancelFullScreen();
  2176. } else if (document.msCancelFullScreen) {
  2177. document.msCancelFullScreen();
  2178. }
  2179. };
  2180. // External files
  2181. Tools.CleanUrl = function (url) {
  2182. url = url.replace(/#/mg, "%23");
  2183. return url;
  2184. };
  2185. Tools.LoadImage = function (url, onload, onerror, database) {
  2186. url = Tools.CleanUrl(url);
  2187. var img = new Image();
  2188. if (url.substr(0, 5) != "data:")
  2189. img.crossOrigin = 'anonymous';
  2190. img.onload = function () {
  2191. onload(img);
  2192. };
  2193. img.onerror = function (err) {
  2194. onerror(img, err);
  2195. };
  2196. var noIndexedDB = function () {
  2197. img.src = url;
  2198. };
  2199. var loadFromIndexedDB = function () {
  2200. database.loadImageFromDB(url, img);
  2201. };
  2202. //ANY database to do!
  2203. if (database && database.enableTexturesOffline && BABYLON.Database.isUASupportingBlobStorage) {
  2204. database.openAsync(loadFromIndexedDB, noIndexedDB);
  2205. } else {
  2206. if (url.indexOf("file:") === -1) {
  2207. noIndexedDB();
  2208. } else {
  2209. try {
  2210. var textureName = url.substring(5);
  2211. var blobURL;
  2212. try {
  2213. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  2214. } catch (ex) {
  2215. // Chrome doesn't support oneTimeOnly parameter
  2216. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  2217. }
  2218. img.src = blobURL;
  2219. } catch (e) {
  2220. Tools.Log("Error while trying to load texture: " + textureName);
  2221. img.src = null;
  2222. }
  2223. }
  2224. }
  2225. return img;
  2226. };
  2227. //ANY
  2228. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  2229. url = Tools.CleanUrl(url);
  2230. var noIndexedDB = function () {
  2231. var request = new XMLHttpRequest();
  2232. var loadUrl = Tools.BaseUrl + url;
  2233. request.open('GET', loadUrl, true);
  2234. if (useArrayBuffer) {
  2235. request.responseType = "arraybuffer";
  2236. }
  2237. request.onprogress = progressCallBack;
  2238. request.onreadystatechange = function () {
  2239. if (request.readyState == 4) {
  2240. if (request.status == 200 || BABYLON.Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  2241. callback(!useArrayBuffer ? request.responseText : request.response);
  2242. } else {
  2243. if (onError) {
  2244. onError();
  2245. } else {
  2246. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  2247. }
  2248. }
  2249. }
  2250. };
  2251. request.send(null);
  2252. };
  2253. var loadFromIndexedDB = function () {
  2254. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  2255. };
  2256. if (url.indexOf("file:") !== -1) {
  2257. var fileName = url.substring(5);
  2258. BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  2259. } else {
  2260. // Caching all files
  2261. if (database && database.enableSceneOffline) {
  2262. database.openAsync(loadFromIndexedDB, noIndexedDB);
  2263. } else {
  2264. noIndexedDB();
  2265. }
  2266. }
  2267. };
  2268. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  2269. var reader = new FileReader();
  2270. reader.onload = function (e) {
  2271. callback(e.target.result);
  2272. };
  2273. reader.onprogress = progressCallback;
  2274. reader.readAsDataURL(fileToLoad);
  2275. };
  2276. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  2277. var reader = new FileReader();
  2278. reader.onload = function (e) {
  2279. callback(e.target.result);
  2280. };
  2281. reader.onprogress = progressCallBack;
  2282. if (!useArrayBuffer) {
  2283. // Asynchronous read
  2284. reader.readAsText(fileToLoad);
  2285. } else {
  2286. reader.readAsArrayBuffer(fileToLoad);
  2287. }
  2288. };
  2289. // Misc.
  2290. Tools.Clamp = function (value, min, max) {
  2291. if (typeof min === "undefined") { min = 0; }
  2292. if (typeof max === "undefined") { max = 1; }
  2293. return Math.min(max, Math.max(min, value));
  2294. };
  2295. Tools.Format = function (value, decimals) {
  2296. if (typeof decimals === "undefined") { decimals = 2; }
  2297. return value.toFixed(decimals);
  2298. };
  2299. Tools.CheckExtends = function (v, min, max) {
  2300. if (v.x < min.x)
  2301. min.x = v.x;
  2302. if (v.y < min.y)
  2303. min.y = v.y;
  2304. if (v.z < min.z)
  2305. min.z = v.z;
  2306. if (v.x > max.x)
  2307. max.x = v.x;
  2308. if (v.y > max.y)
  2309. max.y = v.y;
  2310. if (v.z > max.z)
  2311. max.z = v.z;
  2312. };
  2313. Tools.WithinEpsilon = function (a, b) {
  2314. var num = a - b;
  2315. return -1.401298E-45 <= num && num <= 1.401298E-45;
  2316. };
  2317. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  2318. for (var prop in source) {
  2319. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  2320. continue;
  2321. }
  2322. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  2323. continue;
  2324. }
  2325. var sourceValue = source[prop];
  2326. var typeOfSourceValue = typeof sourceValue;
  2327. if (typeOfSourceValue == "function") {
  2328. continue;
  2329. }
  2330. if (typeOfSourceValue == "object") {
  2331. if (sourceValue instanceof Array) {
  2332. destination[prop] = [];
  2333. if (sourceValue.length > 0) {
  2334. if (typeof sourceValue[0] == "object") {
  2335. for (var index = 0; index < sourceValue.length; index++) {
  2336. var clonedValue = cloneValue(sourceValue[index], destination);
  2337. if (destination[prop].indexOf(clonedValue) === -1) {
  2338. destination[prop].push(clonedValue);
  2339. }
  2340. }
  2341. } else {
  2342. destination[prop] = sourceValue.slice(0);
  2343. }
  2344. }
  2345. } else {
  2346. destination[prop] = cloneValue(sourceValue, destination);
  2347. }
  2348. } else {
  2349. destination[prop] = sourceValue;
  2350. }
  2351. }
  2352. };
  2353. Tools.IsEmpty = function (obj) {
  2354. for (var i in obj) {
  2355. return false;
  2356. }
  2357. return true;
  2358. };
  2359. Tools.RegisterTopRootEvents = function (events) {
  2360. for (var index = 0; index < events.length; index++) {
  2361. var event = events[index];
  2362. window.addEventListener(event.name, event.handler, false);
  2363. try {
  2364. if (window.parent) {
  2365. window.parent.addEventListener(event.name, event.handler, false);
  2366. }
  2367. } catch (e) {
  2368. // Silently fails...
  2369. }
  2370. }
  2371. };
  2372. Tools.UnregisterTopRootEvents = function (events) {
  2373. for (var index = 0; index < events.length; index++) {
  2374. var event = events[index];
  2375. window.removeEventListener(event.name, event.handler);
  2376. try {
  2377. if (window.parent) {
  2378. window.parent.removeEventListener(event.name, event.handler);
  2379. }
  2380. } catch (e) {
  2381. // Silently fails...
  2382. }
  2383. }
  2384. };
  2385. Tools.CreateScreenshot = function (engine, camera, size) {
  2386. var width;
  2387. var height;
  2388. var scene = camera.getScene();
  2389. var previousCamera = null;
  2390. if (scene.activeCamera !== camera) {
  2391. previousCamera = scene.activeCamera;
  2392. scene.activeCamera = camera;
  2393. }
  2394. //If a precision value is specified
  2395. if (size.precision) {
  2396. width = Math.round(engine.getRenderWidth() * size.precision);
  2397. height = Math.round(width / engine.getAspectRatio(camera));
  2398. size = { width: width, height: height };
  2399. } else if (size.width && size.height) {
  2400. width = size.width;
  2401. height = size.height;
  2402. } else if (size.width && !size.height) {
  2403. width = size.width;
  2404. height = Math.round(width / engine.getAspectRatio(camera));
  2405. size = { width: width, height: height };
  2406. } else if (size.height && !size.width) {
  2407. height = size.height;
  2408. width = Math.round(height * engine.getAspectRatio(camera));
  2409. size = { width: width, height: height };
  2410. } else if (!isNaN(size)) {
  2411. height = size;
  2412. width = size;
  2413. } else {
  2414. Tools.Error("Invalid 'size' parameter !");
  2415. return;
  2416. }
  2417. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  2418. var texture = new BABYLON.RenderTargetTexture("screenShot", size, engine.scenes[0], false, false);
  2419. texture.renderList = engine.scenes[0].meshes;
  2420. texture.onAfterRender = function () {
  2421. // Read the contents of the framebuffer
  2422. var numberOfChannelsByLine = width * 4;
  2423. var halfHeight = height / 2;
  2424. //Reading datas from WebGL
  2425. var data = engine.readPixels(0, 0, width, height);
  2426. for (var i = 0; i < halfHeight; i++) {
  2427. for (var j = 0; j < numberOfChannelsByLine; j++) {
  2428. var currentCell = j + i * numberOfChannelsByLine;
  2429. var targetLine = height - i - 1;
  2430. var targetCell = j + targetLine * numberOfChannelsByLine;
  2431. var temp = data[currentCell];
  2432. data[currentCell] = data[targetCell];
  2433. data[targetCell] = temp;
  2434. }
  2435. }
  2436. // Create a 2D canvas to store the result
  2437. if (!screenshotCanvas) {
  2438. screenshotCanvas = document.createElement('canvas');
  2439. }
  2440. screenshotCanvas.width = width;
  2441. screenshotCanvas.height = height;
  2442. var context = screenshotCanvas.getContext('2d');
  2443. // Copy the pixels to a 2D canvas
  2444. var imageData = context.createImageData(width, height);
  2445. imageData.data.set(data);
  2446. context.putImageData(imageData, 0, 0);
  2447. var base64Image = screenshotCanvas.toDataURL();
  2448. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  2449. if (("download" in document.createElement("a"))) {
  2450. var a = window.document.createElement("a");
  2451. a.href = base64Image;
  2452. var date = new Date();
  2453. var stringDate = date.getFullYear() + "/" + date.getMonth() + "/" + date.getDate() + "-" + date.getHours() + ":" + date.getMinutes();
  2454. a.setAttribute("download", "screenshot-" + stringDate + ".png");
  2455. window.document.body.appendChild(a);
  2456. a.addEventListener("click", function () {
  2457. a.parentElement.removeChild(a);
  2458. });
  2459. a.click();
  2460. //Or opening a new tab with the image if it is not possible to automatically start download.
  2461. } else {
  2462. var newWindow = window.open("");
  2463. var img = newWindow.document.createElement("img");
  2464. img.src = base64Image;
  2465. newWindow.document.body.appendChild(img);
  2466. }
  2467. };
  2468. texture.render(true);
  2469. texture.dispose();
  2470. if (previousCamera) {
  2471. scene.activeCamera = previousCamera;
  2472. }
  2473. };
  2474. // XHR response validator for local file scenario
  2475. Tools.ValidateXHRData = function (xhr, dataType) {
  2476. if (typeof dataType === "undefined") { dataType = 7; }
  2477. try {
  2478. if (dataType & 1) {
  2479. if (xhr.responseText && xhr.responseText.length > 0) {
  2480. return true;
  2481. } else if (dataType === 1) {
  2482. return false;
  2483. }
  2484. }
  2485. if (dataType & 2) {
  2486. // Check header width and height since there is no "TGA" magic number
  2487. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  2488. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  2489. return true;
  2490. } else if (dataType === 2) {
  2491. return false;
  2492. }
  2493. }
  2494. if (dataType & 4) {
  2495. // Check for the "DDS" magic number
  2496. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  2497. if (ddsHeader[0] == 68 && ddsHeader[1] == 68 && ddsHeader[2] == 83) {
  2498. return true;
  2499. } else {
  2500. return false;
  2501. }
  2502. }
  2503. } catch (e) {
  2504. // Global protection
  2505. }
  2506. return false;
  2507. };
  2508. Object.defineProperty(Tools, "NoneLogLevel", {
  2509. get: function () {
  2510. return Tools._NoneLogLevel;
  2511. },
  2512. enumerable: true,
  2513. configurable: true
  2514. });
  2515. Object.defineProperty(Tools, "MessageLogLevel", {
  2516. get: function () {
  2517. return Tools._MessageLogLevel;
  2518. },
  2519. enumerable: true,
  2520. configurable: true
  2521. });
  2522. Object.defineProperty(Tools, "WarningLogLevel", {
  2523. get: function () {
  2524. return Tools._WarningLogLevel;
  2525. },
  2526. enumerable: true,
  2527. configurable: true
  2528. });
  2529. Object.defineProperty(Tools, "ErrorLogLevel", {
  2530. get: function () {
  2531. return Tools._ErrorLogLevel;
  2532. },
  2533. enumerable: true,
  2534. configurable: true
  2535. });
  2536. Object.defineProperty(Tools, "AllLogLevel", {
  2537. get: function () {
  2538. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  2539. },
  2540. enumerable: true,
  2541. configurable: true
  2542. });
  2543. Tools._AddLogEntry = function (entry) {
  2544. Tools._LogCache = entry + Tools._LogCache;
  2545. if (Tools.OnNewCacheEntry) {
  2546. Tools.OnNewCacheEntry(entry);
  2547. }
  2548. };
  2549. Tools._FormatMessage = function (message) {
  2550. var padStr = function (i) {
  2551. return (i < 10) ? "0" + i : "" + i;
  2552. };
  2553. var date = new Date();
  2554. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  2555. };
  2556. Tools._LogDisabled = function (message) {
  2557. // nothing to do
  2558. };
  2559. Tools._LogEnabled = function (message) {
  2560. var formattedMessage = Tools._FormatMessage(message);
  2561. console.log("BJS - " + formattedMessage);
  2562. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  2563. Tools._AddLogEntry(entry);
  2564. };
  2565. Tools._WarnDisabled = function (message) {
  2566. // nothing to do
  2567. };
  2568. Tools._WarnEnabled = function (message) {
  2569. var formattedMessage = Tools._FormatMessage(message);
  2570. console.warn("BJS - " + formattedMessage);
  2571. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  2572. Tools._AddLogEntry(entry);
  2573. };
  2574. Tools._ErrorDisabled = function (message) {
  2575. // nothing to do
  2576. };
  2577. Tools._ErrorEnabled = function (message) {
  2578. var formattedMessage = Tools._FormatMessage(message);
  2579. console.error("BJS - " + formattedMessage);
  2580. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  2581. Tools._AddLogEntry(entry);
  2582. };
  2583. Object.defineProperty(Tools, "LogCache", {
  2584. get: function () {
  2585. return Tools._LogCache;
  2586. },
  2587. enumerable: true,
  2588. configurable: true
  2589. });
  2590. Object.defineProperty(Tools, "LogLevels", {
  2591. set: function (level) {
  2592. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  2593. Tools.Log = Tools._LogEnabled;
  2594. } else {
  2595. Tools.Log = Tools._LogDisabled;
  2596. }
  2597. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  2598. Tools.Warn = Tools._WarnEnabled;
  2599. } else {
  2600. Tools.Warn = Tools._WarnDisabled;
  2601. }
  2602. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  2603. Tools.Error = Tools._ErrorEnabled;
  2604. } else {
  2605. Tools.Error = Tools._ErrorDisabled;
  2606. }
  2607. },
  2608. enumerable: true,
  2609. configurable: true
  2610. });
  2611. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  2612. get: function () {
  2613. return Tools._PerformanceNoneLogLevel;
  2614. },
  2615. enumerable: true,
  2616. configurable: true
  2617. });
  2618. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  2619. get: function () {
  2620. return Tools._PerformanceUserMarkLogLevel;
  2621. },
  2622. enumerable: true,
  2623. configurable: true
  2624. });
  2625. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  2626. get: function () {
  2627. return Tools._PerformanceConsoleLogLevel;
  2628. },
  2629. enumerable: true,
  2630. configurable: true
  2631. });
  2632. Object.defineProperty(Tools, "PerformanceLogLevel", {
  2633. set: function (level) {
  2634. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  2635. Tools.StartPerformanceCounter = Tools._StartUserMark;
  2636. Tools.EndPerformanceCounter = Tools._EndUserMark;
  2637. return;
  2638. }
  2639. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  2640. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  2641. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  2642. return;
  2643. }
  2644. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  2645. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  2646. },
  2647. enumerable: true,
  2648. configurable: true
  2649. });
  2650. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  2651. };
  2652. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  2653. };
  2654. Tools._StartUserMark = function (counterName, condition) {
  2655. if (typeof condition === "undefined") { condition = true; }
  2656. if (!condition || !Tools._performance.mark) {
  2657. return;
  2658. }
  2659. Tools._performance.mark(counterName + "-Begin");
  2660. };
  2661. Tools._EndUserMark = function (counterName, condition) {
  2662. if (typeof condition === "undefined") { condition = true; }
  2663. if (!condition || !Tools._performance.mark) {
  2664. return;
  2665. }
  2666. Tools._performance.mark(counterName + "-End");
  2667. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  2668. };
  2669. Tools._StartPerformanceConsole = function (counterName, condition) {
  2670. if (typeof condition === "undefined") { condition = true; }
  2671. if (!condition) {
  2672. return;
  2673. }
  2674. Tools._StartUserMark(counterName, condition);
  2675. if (console.time) {
  2676. console.time(counterName);
  2677. }
  2678. };
  2679. Tools._EndPerformanceConsole = function (counterName, condition) {
  2680. if (typeof condition === "undefined") { condition = true; }
  2681. if (!condition) {
  2682. return;
  2683. }
  2684. Tools._EndUserMark(counterName, condition);
  2685. if (console.time) {
  2686. console.timeEnd(counterName);
  2687. }
  2688. };
  2689. Object.defineProperty(Tools, "Now", {
  2690. get: function () {
  2691. if (window.performance && window.performance.now) {
  2692. return window.performance.now();
  2693. }
  2694. return new Date().getTime();
  2695. },
  2696. enumerable: true,
  2697. configurable: true
  2698. });
  2699. // Deprecated
  2700. Tools.GetFps = function () {
  2701. Tools.Warn("Tools.GetFps() is deprecated. Please use engine.getFps() instead");
  2702. return 0;
  2703. };
  2704. Tools.BaseUrl = "";
  2705. Tools.GetExponantOfTwo = function (value, max) {
  2706. var count = 1;
  2707. do {
  2708. count *= 2;
  2709. } while(count < value);
  2710. if (count > max)
  2711. count = max;
  2712. return count;
  2713. };
  2714. Tools._NoneLogLevel = 0;
  2715. Tools._MessageLogLevel = 1;
  2716. Tools._WarningLogLevel = 2;
  2717. Tools._ErrorLogLevel = 4;
  2718. Tools._LogCache = "";
  2719. Tools.Log = Tools._LogEnabled;
  2720. Tools.Warn = Tools._WarnEnabled;
  2721. Tools.Error = Tools._ErrorEnabled;
  2722. Tools._PerformanceNoneLogLevel = 0;
  2723. Tools._PerformanceUserMarkLogLevel = 1;
  2724. Tools._PerformanceConsoleLogLevel = 2;
  2725. Tools._performance = window.performance;
  2726. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  2727. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  2728. return Tools;
  2729. })();
  2730. BABYLON.Tools = Tools;
  2731. })(BABYLON || (BABYLON = {}));
  2732. //# sourceMappingURL=babylon.tools.js.map
  2733. var BABYLON;
  2734. (function (BABYLON) {
  2735. var _DepthCullingState = (function () {
  2736. function _DepthCullingState() {
  2737. this._isDepthTestDirty = false;
  2738. this._isDepthMaskDirty = false;
  2739. this._isDepthFuncDirty = false;
  2740. this._isCullFaceDirty = false;
  2741. this._isCullDirty = false;
  2742. }
  2743. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  2744. get: function () {
  2745. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty;
  2746. },
  2747. enumerable: true,
  2748. configurable: true
  2749. });
  2750. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  2751. get: function () {
  2752. return this._cullFace;
  2753. },
  2754. set: function (value) {
  2755. if (this._cullFace === value) {
  2756. return;
  2757. }
  2758. this._cullFace = value;
  2759. this._isCullFaceDirty = true;
  2760. },
  2761. enumerable: true,
  2762. configurable: true
  2763. });
  2764. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  2765. get: function () {
  2766. return this._cull;
  2767. },
  2768. set: function (value) {
  2769. if (this._cull === value) {
  2770. return;
  2771. }
  2772. this._cull = value;
  2773. this._isCullDirty = true;
  2774. },
  2775. enumerable: true,
  2776. configurable: true
  2777. });
  2778. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  2779. get: function () {
  2780. return this._depthFunc;
  2781. },
  2782. set: function (value) {
  2783. if (this._depthFunc === value) {
  2784. return;
  2785. }
  2786. this._depthFunc = value;
  2787. this._isDepthFuncDirty = true;
  2788. },
  2789. enumerable: true,
  2790. configurable: true
  2791. });
  2792. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  2793. get: function () {
  2794. return this._depthMask;
  2795. },
  2796. set: function (value) {
  2797. if (this._depthMask === value) {
  2798. return;
  2799. }
  2800. this._depthMask = value;
  2801. this._isDepthMaskDirty = true;
  2802. },
  2803. enumerable: true,
  2804. configurable: true
  2805. });
  2806. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  2807. get: function () {
  2808. return this._depthTest;
  2809. },
  2810. set: function (value) {
  2811. if (this._depthTest === value) {
  2812. return;
  2813. }
  2814. this._depthTest = value;
  2815. this._isDepthTestDirty = true;
  2816. },
  2817. enumerable: true,
  2818. configurable: true
  2819. });
  2820. _DepthCullingState.prototype.reset = function () {
  2821. this._depthMask = true;
  2822. this._depthTest = true;
  2823. this._depthFunc = null;
  2824. this._cull = null;
  2825. this._cullFace = null;
  2826. this._isDepthTestDirty = true;
  2827. this._isDepthMaskDirty = true;
  2828. this._isDepthFuncDirty = false;
  2829. this._isCullFaceDirty = false;
  2830. this._isCullDirty = false;
  2831. };
  2832. _DepthCullingState.prototype.apply = function (gl) {
  2833. if (!this.isDirty) {
  2834. return;
  2835. }
  2836. // Cull
  2837. if (this._isCullDirty) {
  2838. if (this.cull === true) {
  2839. gl.enable(gl.CULL_FACE);
  2840. } else if (this.cull === false) {
  2841. gl.disable(gl.CULL_FACE);
  2842. }
  2843. this._isCullDirty = false;
  2844. }
  2845. // Cull face
  2846. if (this._isCullFaceDirty) {
  2847. gl.cullFace(this.cullFace);
  2848. this._isCullFaceDirty = false;
  2849. }
  2850. // Depth mask
  2851. if (this._isDepthMaskDirty) {
  2852. gl.depthMask(this.depthMask);
  2853. this._isDepthMaskDirty = false;
  2854. }
  2855. // Depth test
  2856. if (this._isDepthTestDirty) {
  2857. if (this.depthTest === true) {
  2858. gl.enable(gl.DEPTH_TEST);
  2859. } else if (this.depthTest === false) {
  2860. gl.disable(gl.DEPTH_TEST);
  2861. }
  2862. this._isDepthTestDirty = false;
  2863. }
  2864. // Depth func
  2865. if (this._isDepthFuncDirty) {
  2866. gl.depthFunc(this.depthFunc);
  2867. this._isDepthFuncDirty = false;
  2868. }
  2869. };
  2870. return _DepthCullingState;
  2871. })();
  2872. BABYLON._DepthCullingState = _DepthCullingState;
  2873. var _AlphaState = (function () {
  2874. function _AlphaState() {
  2875. this._isAlphaBlendDirty = false;
  2876. this._isBlendFunctionParametersDirty = false;
  2877. this._alphaBlend = false;
  2878. this._blendFunctionParameters = new Array(4);
  2879. }
  2880. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  2881. get: function () {
  2882. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  2883. },
  2884. enumerable: true,
  2885. configurable: true
  2886. });
  2887. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  2888. get: function () {
  2889. return this._alphaBlend;
  2890. },
  2891. set: function (value) {
  2892. if (this._alphaBlend === value) {
  2893. return;
  2894. }
  2895. this._alphaBlend = value;
  2896. this._isAlphaBlendDirty = true;
  2897. },
  2898. enumerable: true,
  2899. configurable: true
  2900. });
  2901. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  2902. if (this._blendFunctionParameters[0] === value0 && this._blendFunctionParameters[1] === value1 && this._blendFunctionParameters[2] === value2 && this._blendFunctionParameters[3] === value3) {
  2903. return;
  2904. }
  2905. this._blendFunctionParameters[0] = value0;
  2906. this._blendFunctionParameters[1] = value1;
  2907. this._blendFunctionParameters[2] = value2;
  2908. this._blendFunctionParameters[3] = value3;
  2909. this._isBlendFunctionParametersDirty = true;
  2910. };
  2911. _AlphaState.prototype.reset = function () {
  2912. this._alphaBlend = false;
  2913. this._blendFunctionParameters[0] = null;
  2914. this._blendFunctionParameters[1] = null;
  2915. this._blendFunctionParameters[2] = null;
  2916. this._blendFunctionParameters[3] = null;
  2917. this._isAlphaBlendDirty = true;
  2918. this._isBlendFunctionParametersDirty = false;
  2919. };
  2920. _AlphaState.prototype.apply = function (gl) {
  2921. if (!this.isDirty) {
  2922. return;
  2923. }
  2924. // Alpha blend
  2925. if (this._isAlphaBlendDirty) {
  2926. if (this._alphaBlend === true) {
  2927. gl.enable(gl.BLEND);
  2928. } else if (this._alphaBlend === false) {
  2929. gl.disable(gl.BLEND);
  2930. }
  2931. this._isAlphaBlendDirty = false;
  2932. }
  2933. // Alpha function
  2934. if (this._isBlendFunctionParametersDirty) {
  2935. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  2936. this._isBlendFunctionParametersDirty = false;
  2937. }
  2938. };
  2939. return _AlphaState;
  2940. })();
  2941. BABYLON._AlphaState = _AlphaState;
  2942. var compileShader = function (gl, source, type, defines) {
  2943. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  2944. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  2945. gl.compileShader(shader);
  2946. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  2947. throw new Error(gl.getShaderInfoLog(shader));
  2948. }
  2949. return shader;
  2950. };
  2951. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  2952. var magFilter = gl.NEAREST;
  2953. var minFilter = gl.NEAREST;
  2954. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  2955. magFilter = gl.LINEAR;
  2956. if (generateMipMaps) {
  2957. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  2958. } else {
  2959. minFilter = gl.LINEAR;
  2960. }
  2961. } else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  2962. magFilter = gl.LINEAR;
  2963. if (generateMipMaps) {
  2964. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  2965. } else {
  2966. minFilter = gl.LINEAR;
  2967. }
  2968. } else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  2969. magFilter = gl.NEAREST;
  2970. if (generateMipMaps) {
  2971. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  2972. } else {
  2973. minFilter = gl.NEAREST;
  2974. }
  2975. }
  2976. return {
  2977. min: minFilter,
  2978. mag: magFilter
  2979. };
  2980. };
  2981. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  2982. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  2983. var engine = scene.getEngine();
  2984. var potWidth = BABYLON.Tools.GetExponantOfTwo(width, engine.getCaps().maxTextureSize);
  2985. var potHeight = BABYLON.Tools.GetExponantOfTwo(height, engine.getCaps().maxTextureSize);
  2986. gl.bindTexture(gl.TEXTURE_2D, texture);
  2987. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  2988. processFunction(potWidth, potHeight);
  2989. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  2990. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  2991. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  2992. if (!noMipmap && !isCompressed) {
  2993. gl.generateMipmap(gl.TEXTURE_2D);
  2994. }
  2995. gl.bindTexture(gl.TEXTURE_2D, null);
  2996. engine._activeTexturesCache = [];
  2997. texture._baseWidth = width;
  2998. texture._baseHeight = height;
  2999. texture._width = potWidth;
  3000. texture._height = potHeight;
  3001. texture.isReady = true;
  3002. scene._removePendingData(texture);
  3003. };
  3004. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  3005. var img;
  3006. var onload = function () {
  3007. loadedImages[index] = img;
  3008. loadedImages._internalCount++;
  3009. scene._removePendingData(img);
  3010. if (loadedImages._internalCount == 6) {
  3011. onfinish(loadedImages);
  3012. }
  3013. };
  3014. var onerror = function () {
  3015. scene._removePendingData(img);
  3016. };
  3017. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  3018. scene._addPendingData(img);
  3019. };
  3020. var cascadeLoad = function (rootUrl, scene, onfinish, extensions) {
  3021. var loadedImages = [];
  3022. loadedImages._internalCount = 0;
  3023. for (var index = 0; index < 6; index++) {
  3024. partialLoad(rootUrl + extensions[index], index, loadedImages, scene, onfinish);
  3025. }
  3026. };
  3027. var EngineCapabilities = (function () {
  3028. function EngineCapabilities() {
  3029. }
  3030. return EngineCapabilities;
  3031. })();
  3032. BABYLON.EngineCapabilities = EngineCapabilities;
  3033. var Engine = (function () {
  3034. function Engine(canvas, antialias, options) {
  3035. var _this = this;
  3036. // Public members
  3037. this.isFullscreen = false;
  3038. this.isPointerLock = false;
  3039. this.cullBackFaces = true;
  3040. this.renderEvenInBackground = true;
  3041. this.scenes = new Array();
  3042. this._windowIsBackground = false;
  3043. this._loadingDivBackgroundColor = "black";
  3044. this._drawCalls = 0;
  3045. this._renderingQueueLaunched = false;
  3046. this._activeRenderLoops = [];
  3047. // FPS
  3048. this.fpsRange = 60;
  3049. this.previousFramesDuration = [];
  3050. this.fps = 60;
  3051. this.deltaTime = 0;
  3052. // States
  3053. this._depthCullingState = new _DepthCullingState();
  3054. this._alphaState = new _AlphaState();
  3055. this._alphaMode = Engine.ALPHA_DISABLE;
  3056. // Cache
  3057. this._loadedTexturesCache = new Array();
  3058. this._activeTexturesCache = new Array();
  3059. this._compiledEffects = {};
  3060. this._uintIndicesCurrentlySet = false;
  3061. this._renderingCanvas = canvas;
  3062. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  3063. options = options || {};
  3064. options.antialias = antialias;
  3065. try {
  3066. this._gl = canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options);
  3067. } catch (e) {
  3068. throw new Error("WebGL not supported");
  3069. }
  3070. if (!this._gl) {
  3071. throw new Error("WebGL not supported");
  3072. }
  3073. this._onBlur = function () {
  3074. _this._windowIsBackground = true;
  3075. };
  3076. this._onFocus = function () {
  3077. _this._windowIsBackground = false;
  3078. };
  3079. window.addEventListener("blur", this._onBlur);
  3080. window.addEventListener("focus", this._onFocus);
  3081. // Textures
  3082. this._workingCanvas = document.createElement("canvas");
  3083. this._workingContext = this._workingCanvas.getContext("2d");
  3084. // Viewport
  3085. this._hardwareScalingLevel = 1.0 / (window.devicePixelRatio || 1.0);
  3086. this.resize();
  3087. // Caps
  3088. this._caps = new EngineCapabilities();
  3089. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  3090. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  3091. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  3092. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  3093. // Extensions
  3094. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  3095. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  3096. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  3097. 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');
  3098. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  3099. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  3100. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  3101. // Depth buffer
  3102. this.setDepthBuffer(true);
  3103. this.setDepthFunctionToLessOrEqual();
  3104. this.setDepthWrite(true);
  3105. // Fullscreen
  3106. this._onFullscreenChange = function () {
  3107. if (document.fullscreen !== undefined) {
  3108. _this.isFullscreen = document.fullscreen;
  3109. } else if (document.mozFullScreen !== undefined) {
  3110. _this.isFullscreen = document.mozFullScreen;
  3111. } else if (document.webkitIsFullScreen !== undefined) {
  3112. _this.isFullscreen = document.webkitIsFullScreen;
  3113. } else if (document.msIsFullScreen !== undefined) {
  3114. _this.isFullscreen = document.msIsFullScreen;
  3115. }
  3116. // Pointer lock
  3117. if (_this.isFullscreen && _this._pointerLockRequested) {
  3118. canvas.requestPointerLock = canvas.requestPointerLock || canvas.msRequestPointerLock || canvas.mozRequestPointerLock || canvas.webkitRequestPointerLock;
  3119. if (canvas.requestPointerLock) {
  3120. canvas.requestPointerLock();
  3121. }
  3122. }
  3123. };
  3124. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  3125. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  3126. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  3127. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  3128. // Pointer lock
  3129. this._onPointerLockChange = function () {
  3130. _this.isPointerLock = (document.mozPointerLockElement === canvas || document.webkitPointerLockElement === canvas || document.msPointerLockElement === canvas || document.pointerLockElement === canvas);
  3131. };
  3132. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  3133. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  3134. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  3135. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  3136. this._audioEngine = new BABYLON.AudioEngine();
  3137. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  3138. }
  3139. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  3140. get: function () {
  3141. return Engine._ALPHA_DISABLE;
  3142. },
  3143. enumerable: true,
  3144. configurable: true
  3145. });
  3146. Object.defineProperty(Engine, "ALPHA_ADD", {
  3147. get: function () {
  3148. return Engine._ALPHA_ADD;
  3149. },
  3150. enumerable: true,
  3151. configurable: true
  3152. });
  3153. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  3154. get: function () {
  3155. return Engine._ALPHA_COMBINE;
  3156. },
  3157. enumerable: true,
  3158. configurable: true
  3159. });
  3160. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  3161. get: function () {
  3162. return Engine._DELAYLOADSTATE_NONE;
  3163. },
  3164. enumerable: true,
  3165. configurable: true
  3166. });
  3167. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  3168. get: function () {
  3169. return Engine._DELAYLOADSTATE_LOADED;
  3170. },
  3171. enumerable: true,
  3172. configurable: true
  3173. });
  3174. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  3175. get: function () {
  3176. return Engine._DELAYLOADSTATE_LOADING;
  3177. },
  3178. enumerable: true,
  3179. configurable: true
  3180. });
  3181. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  3182. get: function () {
  3183. return Engine._DELAYLOADSTATE_NOTLOADED;
  3184. },
  3185. enumerable: true,
  3186. configurable: true
  3187. });
  3188. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  3189. get: function () {
  3190. return Engine._TEXTUREFORMAT_ALPHA;
  3191. },
  3192. enumerable: true,
  3193. configurable: true
  3194. });
  3195. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  3196. get: function () {
  3197. return Engine._TEXTUREFORMAT_LUMINANCE;
  3198. },
  3199. enumerable: true,
  3200. configurable: true
  3201. });
  3202. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  3203. get: function () {
  3204. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  3205. },
  3206. enumerable: true,
  3207. configurable: true
  3208. });
  3209. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  3210. get: function () {
  3211. return Engine._TEXTUREFORMAT_RGB;
  3212. },
  3213. enumerable: true,
  3214. configurable: true
  3215. });
  3216. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  3217. get: function () {
  3218. return Engine._TEXTUREFORMAT_RGBA;
  3219. },
  3220. enumerable: true,
  3221. configurable: true
  3222. });
  3223. Object.defineProperty(Engine, "Version", {
  3224. get: function () {
  3225. return "2.0.0";
  3226. },
  3227. enumerable: true,
  3228. configurable: true
  3229. });
  3230. Engine.prototype.getAudioEngine = function () {
  3231. return this._audioEngine;
  3232. };
  3233. Engine.prototype.getAspectRatio = function (camera) {
  3234. var viewport = camera.viewport;
  3235. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  3236. };
  3237. Engine.prototype.getRenderWidth = function () {
  3238. if (this._currentRenderTarget) {
  3239. return this._currentRenderTarget._width;
  3240. }
  3241. return this._renderingCanvas.width;
  3242. };
  3243. Engine.prototype.getRenderHeight = function () {
  3244. if (this._currentRenderTarget) {
  3245. return this._currentRenderTarget._height;
  3246. }
  3247. return this._renderingCanvas.height;
  3248. };
  3249. Engine.prototype.getRenderingCanvas = function () {
  3250. return this._renderingCanvas;
  3251. };
  3252. Engine.prototype.getRenderingCanvasClientRect = function () {
  3253. return this._renderingCanvas.getBoundingClientRect();
  3254. };
  3255. Engine.prototype.setHardwareScalingLevel = function (level) {
  3256. this._hardwareScalingLevel = level;
  3257. this.resize();
  3258. };
  3259. Engine.prototype.getHardwareScalingLevel = function () {
  3260. return this._hardwareScalingLevel;
  3261. };
  3262. Engine.prototype.getLoadedTexturesCache = function () {
  3263. return this._loadedTexturesCache;
  3264. };
  3265. Engine.prototype.getCaps = function () {
  3266. return this._caps;
  3267. };
  3268. Object.defineProperty(Engine.prototype, "drawCalls", {
  3269. get: function () {
  3270. return this._drawCalls;
  3271. },
  3272. enumerable: true,
  3273. configurable: true
  3274. });
  3275. // Methods
  3276. Engine.prototype.resetDrawCalls = function () {
  3277. this._drawCalls = 0;
  3278. };
  3279. Engine.prototype.setDepthFunctionToGreater = function () {
  3280. this._depthCullingState.depthFunc = this._gl.GREATER;
  3281. };
  3282. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  3283. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  3284. };
  3285. Engine.prototype.setDepthFunctionToLess = function () {
  3286. this._depthCullingState.depthFunc = this._gl.LESS;
  3287. };
  3288. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  3289. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  3290. };
  3291. Engine.prototype.stopRenderLoop = function (renderFunction) {
  3292. if (!renderFunction) {
  3293. this._activeRenderLoops = [];
  3294. return;
  3295. }
  3296. var index = this._activeRenderLoops.indexOf(renderFunction);
  3297. if (index >= 0) {
  3298. this._activeRenderLoops.splice(index, 1);
  3299. }
  3300. };
  3301. Engine.prototype._renderLoop = function () {
  3302. var _this = this;
  3303. var shouldRender = true;
  3304. if (!this.renderEvenInBackground && this._windowIsBackground) {
  3305. shouldRender = false;
  3306. }
  3307. if (shouldRender) {
  3308. // Start new frame
  3309. this.beginFrame();
  3310. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  3311. var renderFunction = this._activeRenderLoops[index];
  3312. renderFunction();
  3313. }
  3314. // Present
  3315. this.endFrame();
  3316. }
  3317. if (this._activeRenderLoops.length > 0) {
  3318. // Register new frame
  3319. BABYLON.Tools.QueueNewFrame(function () {
  3320. _this._renderLoop();
  3321. });
  3322. } else {
  3323. this._renderingQueueLaunched = false;
  3324. }
  3325. };
  3326. Engine.prototype.runRenderLoop = function (renderFunction) {
  3327. var _this = this;
  3328. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  3329. return;
  3330. }
  3331. this._activeRenderLoops.push(renderFunction);
  3332. if (!this._renderingQueueLaunched) {
  3333. this._renderingQueueLaunched = true;
  3334. BABYLON.Tools.QueueNewFrame(function () {
  3335. _this._renderLoop();
  3336. });
  3337. }
  3338. };
  3339. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  3340. if (this.isFullscreen) {
  3341. BABYLON.Tools.ExitFullscreen();
  3342. } else {
  3343. this._pointerLockRequested = requestPointerLock;
  3344. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  3345. }
  3346. };
  3347. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  3348. this.applyStates();
  3349. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  3350. if (this._depthCullingState.depthMask) {
  3351. this._gl.clearDepth(1.0);
  3352. }
  3353. var mode = 0;
  3354. if (backBuffer)
  3355. mode |= this._gl.COLOR_BUFFER_BIT;
  3356. if (depthStencil && this._depthCullingState.depthMask)
  3357. mode |= this._gl.DEPTH_BUFFER_BIT;
  3358. this._gl.clear(mode);
  3359. };
  3360. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  3361. var width = requiredWidth || this._renderingCanvas.width;
  3362. var height = requiredHeight || this._renderingCanvas.height;
  3363. var x = viewport.x || 0;
  3364. var y = viewport.y || 0;
  3365. this._cachedViewport = viewport;
  3366. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  3367. };
  3368. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  3369. this._cachedViewport = null;
  3370. this._gl.viewport(x, y, width, height);
  3371. };
  3372. Engine.prototype.beginFrame = function () {
  3373. this._measureFps();
  3374. };
  3375. Engine.prototype.endFrame = function () {
  3376. this.flushFramebuffer();
  3377. };
  3378. Engine.prototype.resize = function () {
  3379. this.setSize(this._renderingCanvas.clientWidth / this._hardwareScalingLevel, this._renderingCanvas.clientHeight / this._hardwareScalingLevel);
  3380. };
  3381. Engine.prototype.setSize = function (width, height) {
  3382. this._renderingCanvas.width = width;
  3383. this._renderingCanvas.height = height;
  3384. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  3385. };
  3386. Engine.prototype.bindFramebuffer = function (texture) {
  3387. this._currentRenderTarget = texture;
  3388. var gl = this._gl;
  3389. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  3390. this._gl.viewport(0, 0, texture._width, texture._height);
  3391. this.wipeCaches();
  3392. };
  3393. Engine.prototype.unBindFramebuffer = function (texture) {
  3394. this._currentRenderTarget = null;
  3395. if (texture.generateMipMaps) {
  3396. var gl = this._gl;
  3397. gl.bindTexture(gl.TEXTURE_2D, texture);
  3398. gl.generateMipmap(gl.TEXTURE_2D);
  3399. gl.bindTexture(gl.TEXTURE_2D, null);
  3400. }
  3401. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  3402. };
  3403. Engine.prototype.flushFramebuffer = function () {
  3404. // this._gl.flush();
  3405. };
  3406. Engine.prototype.restoreDefaultFramebuffer = function () {
  3407. this._currentRenderTarget = null;
  3408. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  3409. this.setViewport(this._cachedViewport);
  3410. this.wipeCaches();
  3411. };
  3412. // VBOs
  3413. Engine.prototype._resetVertexBufferBinding = function () {
  3414. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  3415. this._cachedVertexBuffers = null;
  3416. };
  3417. Engine.prototype.createVertexBuffer = function (vertices) {
  3418. var vbo = this._gl.createBuffer();
  3419. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  3420. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  3421. this._resetVertexBufferBinding();
  3422. vbo.references = 1;
  3423. return vbo;
  3424. };
  3425. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  3426. var vbo = this._gl.createBuffer();
  3427. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  3428. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  3429. this._resetVertexBufferBinding();
  3430. vbo.references = 1;
  3431. return vbo;
  3432. };
  3433. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  3434. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  3435. if (offset === undefined) {
  3436. offset = 0;
  3437. }
  3438. if (vertices instanceof Float32Array) {
  3439. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  3440. } else {
  3441. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  3442. }
  3443. this._resetVertexBufferBinding();
  3444. };
  3445. Engine.prototype._resetIndexBufferBinding = function () {
  3446. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  3447. this._cachedIndexBuffer = null;
  3448. };
  3449. Engine.prototype.createIndexBuffer = function (indices) {
  3450. var vbo = this._gl.createBuffer();
  3451. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  3452. // Check for 32 bits indices
  3453. var arrayBuffer;
  3454. var need32Bits = false;
  3455. if (this._caps.uintIndices) {
  3456. for (var index = 0; index < indices.length; index++) {
  3457. if (indices[index] > 65535) {
  3458. need32Bits = true;
  3459. break;
  3460. }
  3461. }
  3462. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  3463. } else {
  3464. arrayBuffer = new Uint16Array(indices);
  3465. }
  3466. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  3467. this._resetIndexBufferBinding();
  3468. vbo.references = 1;
  3469. vbo.is32Bits = need32Bits;
  3470. return vbo;
  3471. };
  3472. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  3473. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  3474. this._cachedVertexBuffers = vertexBuffer;
  3475. this._cachedEffectForVertexBuffers = effect;
  3476. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  3477. var offset = 0;
  3478. for (var index = 0; index < vertexDeclaration.length; index++) {
  3479. var order = effect.getAttributeLocation(index);
  3480. if (order >= 0) {
  3481. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  3482. }
  3483. offset += vertexDeclaration[index] * 4;
  3484. }
  3485. }
  3486. if (this._cachedIndexBuffer !== indexBuffer) {
  3487. this._cachedIndexBuffer = indexBuffer;
  3488. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  3489. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  3490. }
  3491. };
  3492. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  3493. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  3494. this._cachedVertexBuffers = vertexBuffers;
  3495. this._cachedEffectForVertexBuffers = effect;
  3496. var attributes = effect.getAttributesNames();
  3497. for (var index = 0; index < attributes.length; index++) {
  3498. var order = effect.getAttributeLocation(index);
  3499. if (order >= 0) {
  3500. var vertexBuffer = vertexBuffers[attributes[index]];
  3501. if (!vertexBuffer) {
  3502. continue;
  3503. }
  3504. var stride = vertexBuffer.getStrideSize();
  3505. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  3506. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  3507. }
  3508. }
  3509. }
  3510. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  3511. this._cachedIndexBuffer = indexBuffer;
  3512. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  3513. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  3514. }
  3515. };
  3516. Engine.prototype._releaseBuffer = function (buffer) {
  3517. buffer.references--;
  3518. if (buffer.references === 0) {
  3519. this._gl.deleteBuffer(buffer);
  3520. return true;
  3521. }
  3522. return false;
  3523. };
  3524. Engine.prototype.createInstancesBuffer = function (capacity) {
  3525. var buffer = this._gl.createBuffer();
  3526. buffer.capacity = capacity;
  3527. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  3528. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  3529. return buffer;
  3530. };
  3531. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  3532. this._gl.deleteBuffer(buffer);
  3533. };
  3534. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  3535. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  3536. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  3537. for (var index = 0; index < 4; index++) {
  3538. var offsetLocation = offsetLocations[index];
  3539. this._gl.enableVertexAttribArray(offsetLocation);
  3540. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  3541. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  3542. }
  3543. };
  3544. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  3545. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  3546. for (var index = 0; index < 4; index++) {
  3547. var offsetLocation = offsetLocations[index];
  3548. this._gl.disableVertexAttribArray(offsetLocation);
  3549. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  3550. }
  3551. };
  3552. Engine.prototype.applyStates = function () {
  3553. this._depthCullingState.apply(this._gl);
  3554. this._alphaState.apply(this._gl);
  3555. };
  3556. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  3557. // Apply states
  3558. this.applyStates();
  3559. this._drawCalls++;
  3560. // Render
  3561. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  3562. if (instancesCount) {
  3563. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2, instancesCount);
  3564. return;
  3565. }
  3566. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2);
  3567. };
  3568. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  3569. // Apply states
  3570. this.applyStates();
  3571. this._drawCalls++;
  3572. if (instancesCount) {
  3573. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  3574. return;
  3575. }
  3576. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  3577. };
  3578. // Shaders
  3579. Engine.prototype._releaseEffect = function (effect) {
  3580. if (this._compiledEffects[effect._key]) {
  3581. delete this._compiledEffects[effect._key];
  3582. if (effect.getProgram()) {
  3583. this._gl.deleteProgram(effect.getProgram());
  3584. }
  3585. }
  3586. };
  3587. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  3588. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  3589. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  3590. var name = vertex + "+" + fragment + "@" + defines;
  3591. if (this._compiledEffects[name]) {
  3592. return this._compiledEffects[name];
  3593. }
  3594. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  3595. effect._key = name;
  3596. this._compiledEffects[name] = effect;
  3597. return effect;
  3598. };
  3599. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  3600. if (typeof uniformsNames === "undefined") { uniformsNames = []; }
  3601. if (typeof samplers === "undefined") { samplers = []; }
  3602. if (typeof defines === "undefined") { defines = ""; }
  3603. return this.createEffect({
  3604. vertex: "particles",
  3605. fragmentElement: fragmentName
  3606. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  3607. };
  3608. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  3609. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  3610. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  3611. var shaderProgram = this._gl.createProgram();
  3612. this._gl.attachShader(shaderProgram, vertexShader);
  3613. this._gl.attachShader(shaderProgram, fragmentShader);
  3614. this._gl.linkProgram(shaderProgram);
  3615. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  3616. if (!linked) {
  3617. var error = this._gl.getProgramInfoLog(shaderProgram);
  3618. if (error) {
  3619. throw new Error(error);
  3620. }
  3621. }
  3622. this._gl.deleteShader(vertexShader);
  3623. this._gl.deleteShader(fragmentShader);
  3624. return shaderProgram;
  3625. };
  3626. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  3627. var results = [];
  3628. for (var index = 0; index < uniformsNames.length; index++) {
  3629. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  3630. }
  3631. return results;
  3632. };
  3633. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  3634. var results = [];
  3635. for (var index = 0; index < attributesNames.length; index++) {
  3636. try {
  3637. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  3638. } catch (e) {
  3639. results.push(-1);
  3640. }
  3641. }
  3642. return results;
  3643. };
  3644. Engine.prototype.enableEffect = function (effect) {
  3645. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  3646. if (effect && effect.onBind) {
  3647. effect.onBind(effect);
  3648. }
  3649. return;
  3650. }
  3651. this._vertexAttribArrays = this._vertexAttribArrays || [];
  3652. // Use program
  3653. this._gl.useProgram(effect.getProgram());
  3654. for (var i in this._vertexAttribArrays) {
  3655. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  3656. continue;
  3657. }
  3658. this._vertexAttribArrays[i] = false;
  3659. this._gl.disableVertexAttribArray(i);
  3660. }
  3661. var attributesCount = effect.getAttributesCount();
  3662. for (var index = 0; index < attributesCount; index++) {
  3663. // Attributes
  3664. var order = effect.getAttributeLocation(index);
  3665. if (order >= 0) {
  3666. this._vertexAttribArrays[order] = true;
  3667. this._gl.enableVertexAttribArray(order);
  3668. }
  3669. }
  3670. this._currentEffect = effect;
  3671. if (effect.onBind) {
  3672. effect.onBind(effect);
  3673. }
  3674. };
  3675. Engine.prototype.setArray = function (uniform, array) {
  3676. if (!uniform)
  3677. return;
  3678. this._gl.uniform1fv(uniform, array);
  3679. };
  3680. Engine.prototype.setMatrices = function (uniform, matrices) {
  3681. if (!uniform)
  3682. return;
  3683. this._gl.uniformMatrix4fv(uniform, false, matrices);
  3684. };
  3685. Engine.prototype.setMatrix = function (uniform, matrix) {
  3686. if (!uniform)
  3687. return;
  3688. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  3689. };
  3690. Engine.prototype.setFloat = function (uniform, value) {
  3691. if (!uniform)
  3692. return;
  3693. this._gl.uniform1f(uniform, value);
  3694. };
  3695. Engine.prototype.setFloat2 = function (uniform, x, y) {
  3696. if (!uniform)
  3697. return;
  3698. this._gl.uniform2f(uniform, x, y);
  3699. };
  3700. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  3701. if (!uniform)
  3702. return;
  3703. this._gl.uniform3f(uniform, x, y, z);
  3704. };
  3705. Engine.prototype.setBool = function (uniform, bool) {
  3706. if (!uniform)
  3707. return;
  3708. this._gl.uniform1i(uniform, bool);
  3709. };
  3710. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  3711. if (!uniform)
  3712. return;
  3713. this._gl.uniform4f(uniform, x, y, z, w);
  3714. };
  3715. Engine.prototype.setColor3 = function (uniform, color3) {
  3716. if (!uniform)
  3717. return;
  3718. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  3719. };
  3720. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  3721. if (!uniform)
  3722. return;
  3723. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  3724. };
  3725. // States
  3726. Engine.prototype.setState = function (culling, force) {
  3727. // Culling
  3728. if (this._depthCullingState.cull !== culling || force) {
  3729. if (culling) {
  3730. this._depthCullingState.cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  3731. this._depthCullingState.cull = true;
  3732. } else {
  3733. this._depthCullingState.cull = false;
  3734. }
  3735. }
  3736. };
  3737. Engine.prototype.setDepthBuffer = function (enable) {
  3738. this._depthCullingState.depthTest = enable;
  3739. };
  3740. Engine.prototype.getDepthWrite = function () {
  3741. return this._depthCullingState.depthMask;
  3742. };
  3743. Engine.prototype.setDepthWrite = function (enable) {
  3744. this._depthCullingState.depthMask = enable;
  3745. };
  3746. Engine.prototype.setColorWrite = function (enable) {
  3747. this._gl.colorMask(enable, enable, enable, enable);
  3748. };
  3749. Engine.prototype.setAlphaMode = function (mode) {
  3750. switch (mode) {
  3751. case BABYLON.Engine.ALPHA_DISABLE:
  3752. this.setDepthWrite(true);
  3753. this._alphaState.alphaBlend = false;
  3754. break;
  3755. case BABYLON.Engine.ALPHA_COMBINE:
  3756. this.setDepthWrite(false);
  3757. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  3758. this._alphaState.alphaBlend = true;
  3759. break;
  3760. case BABYLON.Engine.ALPHA_ADD:
  3761. this.setDepthWrite(false);
  3762. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  3763. this._alphaState.alphaBlend = true;
  3764. break;
  3765. }
  3766. this._alphaMode = mode;
  3767. };
  3768. Engine.prototype.getAlphaMode = function () {
  3769. return this._alphaMode;
  3770. };
  3771. Engine.prototype.setAlphaTesting = function (enable) {
  3772. this._alphaTest = enable;
  3773. };
  3774. Engine.prototype.getAlphaTesting = function () {
  3775. return this._alphaTest;
  3776. };
  3777. // Textures
  3778. Engine.prototype.wipeCaches = function () {
  3779. this._activeTexturesCache = [];
  3780. this._currentEffect = null;
  3781. this._depthCullingState.reset();
  3782. this._alphaState.reset();
  3783. this._cachedVertexBuffers = null;
  3784. this._cachedIndexBuffer = null;
  3785. this._cachedEffectForVertexBuffers = null;
  3786. };
  3787. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  3788. var gl = this._gl;
  3789. gl.bindTexture(gl.TEXTURE_2D, texture);
  3790. var magFilter = gl.NEAREST;
  3791. var minFilter = gl.NEAREST;
  3792. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  3793. magFilter = gl.LINEAR;
  3794. minFilter = gl.LINEAR;
  3795. } else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  3796. magFilter = gl.LINEAR;
  3797. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  3798. }
  3799. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  3800. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  3801. gl.bindTexture(gl.TEXTURE_2D, null);
  3802. };
  3803. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  3804. var _this = this;
  3805. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  3806. if (typeof onLoad === "undefined") { onLoad = null; }
  3807. if (typeof onError === "undefined") { onError = null; }
  3808. if (typeof buffer === "undefined") { buffer = null; }
  3809. var texture = this._gl.createTexture();
  3810. var extension;
  3811. var fromData = false;
  3812. if (url.substr(0, 5) === "data:") {
  3813. fromData = true;
  3814. }
  3815. if (!fromData)
  3816. extension = url.substr(url.length - 4, 4).toLowerCase();
  3817. else {
  3818. var oldUrl = url;
  3819. fromData = oldUrl.split(':');
  3820. url = oldUrl;
  3821. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  3822. }
  3823. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  3824. var isTGA = (extension === ".tga");
  3825. scene._addPendingData(texture);
  3826. texture.url = url;
  3827. texture.noMipmap = noMipmap;
  3828. texture.references = 1;
  3829. this._loadedTexturesCache.push(texture);
  3830. var onerror = function () {
  3831. scene._removePendingData(texture);
  3832. if (onError) {
  3833. onError();
  3834. }
  3835. };
  3836. if (isTGA) {
  3837. var callback = function (arrayBuffer) {
  3838. var data = new Uint8Array(arrayBuffer);
  3839. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  3840. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  3841. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  3842. if (onLoad) {
  3843. onLoad();
  3844. }
  3845. }, samplingMode);
  3846. };
  3847. if (!(fromData instanceof Array))
  3848. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  3849. callback(arrayBuffer);
  3850. }, onerror, scene.database, true);
  3851. else
  3852. callback(buffer);
  3853. } else if (isDDS) {
  3854. callback = function (data) {
  3855. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  3856. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) == 1);
  3857. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  3858. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  3859. if (onLoad) {
  3860. onLoad();
  3861. }
  3862. }, samplingMode);
  3863. };
  3864. if (!(fromData instanceof Array))
  3865. BABYLON.Tools.LoadFile(url, function (data) {
  3866. callback(data);
  3867. }, onerror, scene.database, true);
  3868. else
  3869. callback(buffer);
  3870. } else {
  3871. var onload = function (img) {
  3872. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  3873. var isPot = (img.width == potWidth && img.height == potHeight);
  3874. if (!isPot) {
  3875. _this._workingCanvas.width = potWidth;
  3876. _this._workingCanvas.height = potHeight;
  3877. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  3878. }
  3879. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  3880. if (onLoad) {
  3881. onLoad();
  3882. }
  3883. }, samplingMode);
  3884. };
  3885. if (!(fromData instanceof Array))
  3886. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  3887. else
  3888. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  3889. }
  3890. return texture;
  3891. };
  3892. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode) {
  3893. var texture = this._gl.createTexture();
  3894. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  3895. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  3896. // Format
  3897. var internalFormat = this._gl.RGBA;
  3898. switch (format) {
  3899. case Engine.TEXTUREFORMAT_ALPHA:
  3900. internalFormat = this._gl.ALPHA;
  3901. break;
  3902. case Engine.TEXTUREFORMAT_LUMINANCE:
  3903. internalFormat = this._gl.LUMINANCE;
  3904. break;
  3905. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  3906. internalFormat = this._gl.LUMINANCE_ALPHA;
  3907. break;
  3908. case Engine.TEXTUREFORMAT_RGB:
  3909. internalFormat = this._gl.RGB;
  3910. break;
  3911. case Engine.TEXTUREFORMAT_RGBA:
  3912. internalFormat = this._gl.RGBA;
  3913. break;
  3914. }
  3915. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, width, height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  3916. if (generateMipMaps) {
  3917. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  3918. }
  3919. // Filters
  3920. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  3921. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  3922. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  3923. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  3924. this._activeTexturesCache = [];
  3925. texture._baseWidth = width;
  3926. texture._baseHeight = height;
  3927. texture._width = width;
  3928. texture._height = height;
  3929. texture.isReady = true;
  3930. texture.references = 1;
  3931. this._loadedTexturesCache.push(texture);
  3932. return texture;
  3933. };
  3934. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  3935. var texture = this._gl.createTexture();
  3936. width = BABYLON.Tools.GetExponantOfTwo(width, this._caps.maxTextureSize);
  3937. height = BABYLON.Tools.GetExponantOfTwo(height, this._caps.maxTextureSize);
  3938. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  3939. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  3940. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  3941. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  3942. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  3943. this._activeTexturesCache = [];
  3944. texture._baseWidth = width;
  3945. texture._baseHeight = height;
  3946. texture._width = width;
  3947. texture._height = height;
  3948. texture.isReady = false;
  3949. texture.generateMipMaps = generateMipMaps;
  3950. texture.references = 1;
  3951. this._loadedTexturesCache.push(texture);
  3952. return texture;
  3953. };
  3954. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  3955. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  3956. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  3957. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  3958. if (texture.generateMipMaps) {
  3959. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  3960. }
  3961. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  3962. this._activeTexturesCache = [];
  3963. texture.isReady = true;
  3964. };
  3965. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  3966. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  3967. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  3968. // Scale the video if it is a NPOT using the current working canvas
  3969. if (video.videoWidth !== texture._width || video.videoHeight !== texture._height) {
  3970. if (!texture._workingCanvas) {
  3971. texture._workingCanvas = document.createElement("canvas");
  3972. texture._workingContext = texture._workingCanvas.getContext("2d");
  3973. texture._workingCanvas.width = texture._width;
  3974. texture._workingCanvas.height = texture._height;
  3975. }
  3976. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  3977. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  3978. } else {
  3979. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  3980. }
  3981. if (texture.generateMipMaps) {
  3982. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  3983. }
  3984. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  3985. this._activeTexturesCache = [];
  3986. texture.isReady = true;
  3987. };
  3988. Engine.prototype.createRenderTargetTexture = function (size, options) {
  3989. // old version had a "generateMipMaps" arg instead of options.
  3990. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  3991. // in the same way, generateDepthBuffer is defaulted to true
  3992. var generateMipMaps = false;
  3993. var generateDepthBuffer = true;
  3994. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  3995. if (options !== undefined) {
  3996. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipmaps;
  3997. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  3998. if (options.samplingMode !== undefined) {
  3999. samplingMode = options.samplingMode;
  4000. }
  4001. }
  4002. var gl = this._gl;
  4003. var texture = gl.createTexture();
  4004. gl.bindTexture(gl.TEXTURE_2D, texture);
  4005. var width = size.width || size;
  4006. var height = size.height || size;
  4007. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  4008. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  4009. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  4010. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4011. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4012. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  4013. var depthBuffer;
  4014. // Create the depth buffer
  4015. if (generateDepthBuffer) {
  4016. depthBuffer = gl.createRenderbuffer();
  4017. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  4018. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  4019. }
  4020. // Create the framebuffer
  4021. var framebuffer = gl.createFramebuffer();
  4022. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  4023. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  4024. if (generateDepthBuffer) {
  4025. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  4026. }
  4027. // Unbind
  4028. gl.bindTexture(gl.TEXTURE_2D, null);
  4029. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  4030. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  4031. texture._framebuffer = framebuffer;
  4032. if (generateDepthBuffer) {
  4033. texture._depthBuffer = depthBuffer;
  4034. }
  4035. texture._width = width;
  4036. texture._height = height;
  4037. texture.isReady = true;
  4038. texture.generateMipMaps = generateMipMaps;
  4039. texture.references = 1;
  4040. this._activeTexturesCache = [];
  4041. this._loadedTexturesCache.push(texture);
  4042. return texture;
  4043. };
  4044. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  4045. var _this = this;
  4046. var gl = this._gl;
  4047. var texture = gl.createTexture();
  4048. texture.isCube = true;
  4049. texture.url = rootUrl;
  4050. texture.references = 1;
  4051. this._loadedTexturesCache.push(texture);
  4052. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  4053. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  4054. if (isDDS) {
  4055. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  4056. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  4057. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  4058. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  4059. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  4060. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  4061. if (!noMipmap && !info.isFourCC && info.mipmapCount == 1) {
  4062. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  4063. }
  4064. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  4065. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  4066. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4067. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4068. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  4069. _this._activeTexturesCache = [];
  4070. texture._width = info.width;
  4071. texture._height = info.height;
  4072. texture.isReady = true;
  4073. }, null, null, true);
  4074. } else {
  4075. cascadeLoad(rootUrl, scene, function (imgs) {
  4076. var width = BABYLON.Tools.GetExponantOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  4077. var height = width;
  4078. _this._workingCanvas.width = width;
  4079. _this._workingCanvas.height = height;
  4080. var faces = [
  4081. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  4082. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  4083. ];
  4084. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  4085. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  4086. for (var index = 0; index < faces.length; index++) {
  4087. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  4088. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  4089. }
  4090. if (!noMipmap) {
  4091. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  4092. }
  4093. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  4094. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  4095. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4096. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4097. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  4098. _this._activeTexturesCache = [];
  4099. texture._width = width;
  4100. texture._height = height;
  4101. texture.isReady = true;
  4102. }, extensions);
  4103. }
  4104. return texture;
  4105. };
  4106. Engine.prototype._releaseTexture = function (texture) {
  4107. var gl = this._gl;
  4108. if (texture._framebuffer) {
  4109. gl.deleteFramebuffer(texture._framebuffer);
  4110. }
  4111. if (texture._depthBuffer) {
  4112. gl.deleteRenderbuffer(texture._depthBuffer);
  4113. }
  4114. gl.deleteTexture(texture);
  4115. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  4116. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4117. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4118. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  4119. this._activeTexturesCache[channel] = null;
  4120. }
  4121. var index = this._loadedTexturesCache.indexOf(texture);
  4122. if (index !== -1) {
  4123. this._loadedTexturesCache.splice(index, 1);
  4124. }
  4125. };
  4126. Engine.prototype.bindSamplers = function (effect) {
  4127. this._gl.useProgram(effect.getProgram());
  4128. var samplers = effect.getSamplers();
  4129. for (var index = 0; index < samplers.length; index++) {
  4130. var uniform = effect.getUniform(samplers[index]);
  4131. this._gl.uniform1i(uniform, index);
  4132. }
  4133. this._currentEffect = null;
  4134. };
  4135. Engine.prototype._bindTexture = function (channel, texture) {
  4136. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4137. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4138. this._activeTexturesCache[channel] = null;
  4139. };
  4140. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  4141. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  4142. };
  4143. Engine.prototype.setTexture = function (channel, texture) {
  4144. if (channel < 0) {
  4145. return;
  4146. }
  4147. // Not ready?
  4148. if (!texture || !texture.isReady()) {
  4149. if (this._activeTexturesCache[channel] != null) {
  4150. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4151. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4152. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  4153. this._activeTexturesCache[channel] = null;
  4154. }
  4155. return;
  4156. }
  4157. // Video
  4158. if (texture instanceof BABYLON.VideoTexture) {
  4159. if (texture.update()) {
  4160. this._activeTexturesCache[channel] = null;
  4161. }
  4162. } else if (texture.delayLoadState == BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  4163. texture.delayLoad();
  4164. return;
  4165. }
  4166. if (this._activeTexturesCache[channel] == texture) {
  4167. return;
  4168. }
  4169. this._activeTexturesCache[channel] = texture;
  4170. var internalTexture = texture.getInternalTexture();
  4171. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4172. if (internalTexture.isCube) {
  4173. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  4174. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  4175. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  4176. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  4177. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  4178. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  4179. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  4180. }
  4181. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  4182. } else {
  4183. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  4184. if (internalTexture._cachedWrapU !== texture.wrapU) {
  4185. internalTexture._cachedWrapU = texture.wrapU;
  4186. switch (texture.wrapU) {
  4187. case BABYLON.Texture.WRAP_ADDRESSMODE:
  4188. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  4189. break;
  4190. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  4191. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  4192. break;
  4193. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  4194. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  4195. break;
  4196. }
  4197. }
  4198. if (internalTexture._cachedWrapV !== texture.wrapV) {
  4199. internalTexture._cachedWrapV = texture.wrapV;
  4200. switch (texture.wrapV) {
  4201. case BABYLON.Texture.WRAP_ADDRESSMODE:
  4202. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  4203. break;
  4204. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  4205. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  4206. break;
  4207. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  4208. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  4209. break;
  4210. }
  4211. }
  4212. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  4213. }
  4214. };
  4215. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  4216. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  4217. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== texture.anisotropicFilteringLevel) {
  4218. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropicFilteringLevel, this._caps.maxAnisotropy));
  4219. texture._cachedAnisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  4220. }
  4221. };
  4222. Engine.prototype.readPixels = function (x, y, width, height) {
  4223. var data = new Uint8Array(height * width * 4);
  4224. this._gl.readPixels(0, 0, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  4225. return data;
  4226. };
  4227. // Dispose
  4228. Engine.prototype.dispose = function () {
  4229. this.hideLoadingUI();
  4230. this.stopRenderLoop();
  4231. while (this.scenes.length) {
  4232. this.scenes[0].dispose();
  4233. }
  4234. for (var name in this._compiledEffects) {
  4235. this._gl.deleteProgram(this._compiledEffects[name]._program);
  4236. }
  4237. for (var i in this._vertexAttribArrays) {
  4238. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  4239. continue;
  4240. }
  4241. this._gl.disableVertexAttribArray(i);
  4242. }
  4243. // Events
  4244. window.removeEventListener("blur", this._onBlur);
  4245. window.removeEventListener("focus", this._onFocus);
  4246. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  4247. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  4248. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  4249. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  4250. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  4251. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  4252. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  4253. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  4254. };
  4255. // Loading screen
  4256. Engine.prototype.displayLoadingUI = function () {
  4257. var _this = this;
  4258. this._loadingDiv = document.createElement("div");
  4259. this._loadingDiv.style.opacity = "0";
  4260. this._loadingDiv.style.transition = "opacity 1.5s ease";
  4261. // Loading text
  4262. this._loadingTextDiv = document.createElement("div");
  4263. this._loadingTextDiv.style.position = "absolute";
  4264. this._loadingTextDiv.style.left = "0";
  4265. this._loadingTextDiv.style.top = "50%";
  4266. this._loadingTextDiv.style.marginTop = "80px";
  4267. this._loadingTextDiv.style.width = "100%";
  4268. this._loadingTextDiv.style.height = "20px";
  4269. this._loadingTextDiv.style.fontFamily = "Arial";
  4270. this._loadingTextDiv.style.fontSize = "14px";
  4271. this._loadingTextDiv.style.color = "white";
  4272. this._loadingTextDiv.style.textAlign = "center";
  4273. this._loadingTextDiv.innerHTML = "Loading";
  4274. this._loadingDiv.appendChild(this._loadingTextDiv);
  4275. // Loading img
  4276. var imgBack = new Image();
  4277. 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==";
  4278. imgBack.style.position = "absolute";
  4279. imgBack.style.left = "50%";
  4280. imgBack.style.top = "50%";
  4281. imgBack.style.marginLeft = "-50px";
  4282. imgBack.style.marginTop = "-50px";
  4283. imgBack.style.transition = "transform 1.0s ease";
  4284. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  4285. var deg = 360;
  4286. var onTransitionEnd = function () {
  4287. deg += 360;
  4288. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  4289. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  4290. };
  4291. imgBack.addEventListener("transitionend", onTransitionEnd);
  4292. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  4293. this._loadingDiv.appendChild(imgBack);
  4294. // front image
  4295. var imgFront = new Image();
  4296. 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=";
  4297. imgFront.style.position = "absolute";
  4298. imgFront.style.left = "50%";
  4299. imgFront.style.top = "50%";
  4300. imgFront.style.marginLeft = "-50px";
  4301. imgFront.style.marginTop = "-50px";
  4302. this._loadingDiv.appendChild(imgFront);
  4303. // Resize
  4304. this._resizeLoadingUI = function () {
  4305. var canvasRect = _this.getRenderingCanvasClientRect();
  4306. _this._loadingDiv.style.position = "absolute";
  4307. _this._loadingDiv.style.left = canvasRect.left + "px";
  4308. _this._loadingDiv.style.top = canvasRect.top + "px";
  4309. _this._loadingDiv.style.width = canvasRect.width + "px";
  4310. _this._loadingDiv.style.height = canvasRect.height + "px";
  4311. };
  4312. this._resizeLoadingUI();
  4313. window.addEventListener("resize", this._resizeLoadingUI);
  4314. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  4315. document.body.appendChild(this._loadingDiv);
  4316. setTimeout(function () {
  4317. _this._loadingDiv.style.opacity = "1";
  4318. imgBack.style.transform = "rotateZ(360deg)";
  4319. imgBack.style.webkitTransform = "rotateZ(360deg)";
  4320. }, 0);
  4321. };
  4322. Object.defineProperty(Engine.prototype, "loadingUIText", {
  4323. set: function (text) {
  4324. if (!this._loadingDiv) {
  4325. return;
  4326. }
  4327. this._loadingTextDiv.innerHTML = text;
  4328. },
  4329. enumerable: true,
  4330. configurable: true
  4331. });
  4332. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  4333. get: function () {
  4334. return this._loadingDivBackgroundColor;
  4335. },
  4336. set: function (color) {
  4337. this._loadingDivBackgroundColor = color;
  4338. if (!this._loadingDiv) {
  4339. return;
  4340. }
  4341. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  4342. },
  4343. enumerable: true,
  4344. configurable: true
  4345. });
  4346. Engine.prototype.hideLoadingUI = function () {
  4347. var _this = this;
  4348. if (!this._loadingDiv) {
  4349. return;
  4350. }
  4351. var onTransitionEnd = function () {
  4352. if (!_this._loadingDiv) {
  4353. return;
  4354. }
  4355. document.body.removeChild(_this._loadingDiv);
  4356. window.removeEventListener("resize", _this._resizeLoadingUI);
  4357. _this._loadingDiv = null;
  4358. };
  4359. this._loadingDiv.style.opacity = "0";
  4360. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  4361. };
  4362. // FPS
  4363. Engine.prototype.getFps = function () {
  4364. return this.fps;
  4365. };
  4366. Engine.prototype.getDeltaTime = function () {
  4367. return this.deltaTime;
  4368. };
  4369. Engine.prototype._measureFps = function () {
  4370. this.previousFramesDuration.push(BABYLON.Tools.Now);
  4371. var length = this.previousFramesDuration.length;
  4372. if (length >= 2) {
  4373. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  4374. }
  4375. if (length >= this.fpsRange) {
  4376. if (length > this.fpsRange) {
  4377. this.previousFramesDuration.splice(0, 1);
  4378. length = this.previousFramesDuration.length;
  4379. }
  4380. var sum = 0;
  4381. for (var id = 0; id < length - 1; id++) {
  4382. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  4383. }
  4384. this.fps = 1000.0 / (sum / (length - 1));
  4385. }
  4386. };
  4387. // Statics
  4388. Engine.isSupported = function () {
  4389. try {
  4390. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  4391. if (navigator.isCocoonJS) {
  4392. return true;
  4393. }
  4394. var tempcanvas = document.createElement("canvas");
  4395. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  4396. return gl != null && !!window.WebGLRenderingContext;
  4397. } catch (e) {
  4398. return false;
  4399. }
  4400. };
  4401. Engine._ALPHA_DISABLE = 0;
  4402. Engine._ALPHA_ADD = 1;
  4403. Engine._ALPHA_COMBINE = 2;
  4404. Engine._DELAYLOADSTATE_NONE = 0;
  4405. Engine._DELAYLOADSTATE_LOADED = 1;
  4406. Engine._DELAYLOADSTATE_LOADING = 2;
  4407. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  4408. Engine._TEXTUREFORMAT_ALPHA = 0;
  4409. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  4410. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  4411. Engine._TEXTUREFORMAT_RGB = 4;
  4412. Engine._TEXTUREFORMAT_RGBA = 4;
  4413. Engine.Epsilon = 0.001;
  4414. Engine.CollisionsEpsilon = 0.001;
  4415. Engine.ShadersRepository = "Babylon/Shaders/";
  4416. return Engine;
  4417. })();
  4418. BABYLON.Engine = Engine;
  4419. })(BABYLON || (BABYLON = {}));
  4420. //# sourceMappingURL=babylon.engine.js.map
  4421. var BABYLON;
  4422. (function (BABYLON) {
  4423. var Node = (function () {
  4424. function Node(name, scene) {
  4425. this.state = "";
  4426. this.animations = new Array();
  4427. this._childrenFlag = -1;
  4428. this._isEnabled = true;
  4429. this._isReady = true;
  4430. this._currentRenderId = -1;
  4431. this.name = name;
  4432. this.id = name;
  4433. this._scene = scene;
  4434. this._initCache();
  4435. }
  4436. Node.prototype.getScene = function () {
  4437. return this._scene;
  4438. };
  4439. Node.prototype.getEngine = function () {
  4440. return this._scene.getEngine();
  4441. };
  4442. // override it in derived class
  4443. Node.prototype.getWorldMatrix = function () {
  4444. return BABYLON.Matrix.Identity();
  4445. };
  4446. // override it in derived class if you add new variables to the cache
  4447. // and call the parent class method
  4448. Node.prototype._initCache = function () {
  4449. this._cache = {};
  4450. this._cache.parent = undefined;
  4451. };
  4452. Node.prototype.updateCache = function (force) {
  4453. if (!force && this.isSynchronized())
  4454. return;
  4455. this._cache.parent = this.parent;
  4456. this._updateCache();
  4457. };
  4458. // override it in derived class if you add new variables to the cache
  4459. // and call the parent class method if !ignoreParentClass
  4460. Node.prototype._updateCache = function (ignoreParentClass) {
  4461. };
  4462. // override it in derived class if you add new variables to the cache
  4463. Node.prototype._isSynchronized = function () {
  4464. return true;
  4465. };
  4466. Node.prototype.isSynchronizedWithParent = function () {
  4467. return this.parent ? this.parent._currentRenderId <= this._currentRenderId : true;
  4468. };
  4469. Node.prototype.isSynchronized = function (updateCache) {
  4470. var check = this.hasNewParent();
  4471. check = check || !this.isSynchronizedWithParent();
  4472. check = check || !this._isSynchronized();
  4473. if (updateCache)
  4474. this.updateCache(true);
  4475. return !check;
  4476. };
  4477. Node.prototype.hasNewParent = function (update) {
  4478. if (this._cache.parent === this.parent)
  4479. return false;
  4480. if (update)
  4481. this._cache.parent = this.parent;
  4482. return true;
  4483. };
  4484. Node.prototype.isReady = function () {
  4485. return this._isReady;
  4486. };
  4487. Node.prototype.isEnabled = function () {
  4488. if (!this._isEnabled) {
  4489. return false;
  4490. }
  4491. if (this.parent) {
  4492. return this.parent.isEnabled();
  4493. }
  4494. return true;
  4495. };
  4496. Node.prototype.setEnabled = function (value) {
  4497. this._isEnabled = value;
  4498. };
  4499. Node.prototype.isDescendantOf = function (ancestor) {
  4500. if (this.parent) {
  4501. if (this.parent === ancestor) {
  4502. return true;
  4503. }
  4504. return this.parent.isDescendantOf(ancestor);
  4505. }
  4506. return false;
  4507. };
  4508. Node.prototype._getDescendants = function (list, results) {
  4509. for (var index = 0; index < list.length; index++) {
  4510. var item = list[index];
  4511. if (item.isDescendantOf(this)) {
  4512. results.push(item);
  4513. }
  4514. }
  4515. };
  4516. Node.prototype.getDescendants = function () {
  4517. var results = [];
  4518. this._getDescendants(this._scene.meshes, results);
  4519. this._getDescendants(this._scene.lights, results);
  4520. this._getDescendants(this._scene.cameras, results);
  4521. return results;
  4522. };
  4523. Node.prototype._setReady = function (state) {
  4524. if (state == this._isReady) {
  4525. return;
  4526. }
  4527. if (!state) {
  4528. this._isReady = false;
  4529. return;
  4530. }
  4531. this._isReady = true;
  4532. if (this.onReady) {
  4533. this.onReady(this);
  4534. }
  4535. };
  4536. return Node;
  4537. })();
  4538. BABYLON.Node = Node;
  4539. })(BABYLON || (BABYLON = {}));
  4540. //# sourceMappingURL=babylon.node.js.map
  4541. var BABYLON;
  4542. (function (BABYLON) {
  4543. var BoundingSphere = (function () {
  4544. function BoundingSphere(minimum, maximum) {
  4545. this.minimum = minimum;
  4546. this.maximum = maximum;
  4547. this._tempRadiusVector = BABYLON.Vector3.Zero();
  4548. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  4549. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  4550. this.radius = distance * 0.5;
  4551. this.centerWorld = BABYLON.Vector3.Zero();
  4552. this._update(BABYLON.Matrix.Identity());
  4553. }
  4554. // Methods
  4555. BoundingSphere.prototype._update = function (world) {
  4556. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  4557. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  4558. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  4559. };
  4560. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  4561. for (var i = 0; i < 6; i++) {
  4562. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  4563. return false;
  4564. }
  4565. return true;
  4566. };
  4567. BoundingSphere.prototype.intersectsPoint = function (point) {
  4568. var x = this.centerWorld.x - point.x;
  4569. var y = this.centerWorld.y - point.y;
  4570. var z = this.centerWorld.z - point.z;
  4571. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  4572. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  4573. return false;
  4574. return true;
  4575. };
  4576. // Statics
  4577. BoundingSphere.Intersects = function (sphere0, sphere1) {
  4578. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  4579. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  4580. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  4581. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  4582. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  4583. return false;
  4584. return true;
  4585. };
  4586. return BoundingSphere;
  4587. })();
  4588. BABYLON.BoundingSphere = BoundingSphere;
  4589. })(BABYLON || (BABYLON = {}));
  4590. //# sourceMappingURL=babylon.boundingSphere.js.map
  4591. var BABYLON;
  4592. (function (BABYLON) {
  4593. var BoundingBox = (function () {
  4594. function BoundingBox(minimum, maximum) {
  4595. this.minimum = minimum;
  4596. this.maximum = maximum;
  4597. this.vectors = new Array();
  4598. this.vectorsWorld = new Array();
  4599. // Bounding vectors
  4600. this.vectors.push(this.minimum.clone());
  4601. this.vectors.push(this.maximum.clone());
  4602. this.vectors.push(this.minimum.clone());
  4603. this.vectors[2].x = this.maximum.x;
  4604. this.vectors.push(this.minimum.clone());
  4605. this.vectors[3].y = this.maximum.y;
  4606. this.vectors.push(this.minimum.clone());
  4607. this.vectors[4].z = this.maximum.z;
  4608. this.vectors.push(this.maximum.clone());
  4609. this.vectors[5].z = this.minimum.z;
  4610. this.vectors.push(this.maximum.clone());
  4611. this.vectors[6].x = this.minimum.x;
  4612. this.vectors.push(this.maximum.clone());
  4613. this.vectors[7].y = this.minimum.y;
  4614. // OBB
  4615. this.center = this.maximum.add(this.minimum).scale(0.5);
  4616. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  4617. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  4618. for (var index = 0; index < this.vectors.length; index++) {
  4619. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  4620. }
  4621. this.minimumWorld = BABYLON.Vector3.Zero();
  4622. this.maximumWorld = BABYLON.Vector3.Zero();
  4623. this._update(BABYLON.Matrix.Identity());
  4624. }
  4625. // Methods
  4626. BoundingBox.prototype.getWorldMatrix = function () {
  4627. return this._worldMatrix;
  4628. };
  4629. BoundingBox.prototype._update = function (world) {
  4630. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  4631. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  4632. for (var index = 0; index < this.vectors.length; index++) {
  4633. var v = this.vectorsWorld[index];
  4634. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  4635. if (v.x < this.minimumWorld.x)
  4636. this.minimumWorld.x = v.x;
  4637. if (v.y < this.minimumWorld.y)
  4638. this.minimumWorld.y = v.y;
  4639. if (v.z < this.minimumWorld.z)
  4640. this.minimumWorld.z = v.z;
  4641. if (v.x > this.maximumWorld.x)
  4642. this.maximumWorld.x = v.x;
  4643. if (v.y > this.maximumWorld.y)
  4644. this.maximumWorld.y = v.y;
  4645. if (v.z > this.maximumWorld.z)
  4646. this.maximumWorld.z = v.z;
  4647. }
  4648. // OBB
  4649. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  4650. this.center.scaleInPlace(0.5);
  4651. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  4652. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  4653. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  4654. this._worldMatrix = world;
  4655. };
  4656. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  4657. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  4658. };
  4659. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  4660. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  4661. };
  4662. BoundingBox.prototype.intersectsPoint = function (point) {
  4663. var delta = BABYLON.Engine.Epsilon;
  4664. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  4665. return false;
  4666. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  4667. return false;
  4668. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  4669. return false;
  4670. return true;
  4671. };
  4672. BoundingBox.prototype.intersectsSphere = function (sphere) {
  4673. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  4674. };
  4675. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  4676. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  4677. return false;
  4678. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  4679. return false;
  4680. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  4681. return false;
  4682. return true;
  4683. };
  4684. // Statics
  4685. BoundingBox.Intersects = function (box0, box1) {
  4686. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  4687. return false;
  4688. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  4689. return false;
  4690. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  4691. return false;
  4692. return true;
  4693. };
  4694. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  4695. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  4696. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  4697. return (num <= (sphereRadius * sphereRadius));
  4698. };
  4699. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  4700. for (var p = 0; p < 6; p++) {
  4701. for (var i = 0; i < 8; i++) {
  4702. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  4703. return false;
  4704. }
  4705. }
  4706. }
  4707. return true;
  4708. };
  4709. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  4710. for (var p = 0; p < 6; p++) {
  4711. var inCount = 8;
  4712. for (var i = 0; i < 8; i++) {
  4713. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  4714. --inCount;
  4715. } else {
  4716. break;
  4717. }
  4718. }
  4719. if (inCount == 0)
  4720. return false;
  4721. }
  4722. return true;
  4723. };
  4724. return BoundingBox;
  4725. })();
  4726. BABYLON.BoundingBox = BoundingBox;
  4727. })(BABYLON || (BABYLON = {}));
  4728. //# sourceMappingURL=babylon.boundingBox.js.map
  4729. var BABYLON;
  4730. (function (BABYLON) {
  4731. var computeBoxExtents = function (axis, box) {
  4732. var p = BABYLON.Vector3.Dot(box.center, axis);
  4733. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  4734. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  4735. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  4736. var r = r0 + r1 + r2;
  4737. return {
  4738. min: p - r,
  4739. max: p + r
  4740. };
  4741. };
  4742. var extentsOverlap = function (min0, max0, min1, max1) {
  4743. return !(min0 > max1 || min1 > max0);
  4744. };
  4745. var axisOverlap = function (axis, box0, box1) {
  4746. var result0 = computeBoxExtents(axis, box0);
  4747. var result1 = computeBoxExtents(axis, box1);
  4748. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  4749. };
  4750. var BoundingInfo = (function () {
  4751. function BoundingInfo(minimum, maximum) {
  4752. this.minimum = minimum;
  4753. this.maximum = maximum;
  4754. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  4755. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  4756. }
  4757. // Methods
  4758. BoundingInfo.prototype._update = function (world) {
  4759. this.boundingBox._update(world);
  4760. this.boundingSphere._update(world);
  4761. };
  4762. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  4763. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  4764. return false;
  4765. return this.boundingBox.isInFrustum(frustumPlanes);
  4766. };
  4767. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  4768. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  4769. };
  4770. BoundingInfo.prototype._checkCollision = function (collider) {
  4771. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  4772. };
  4773. BoundingInfo.prototype.intersectsPoint = function (point) {
  4774. if (!this.boundingSphere.centerWorld) {
  4775. return false;
  4776. }
  4777. if (!this.boundingSphere.intersectsPoint(point)) {
  4778. return false;
  4779. }
  4780. if (!this.boundingBox.intersectsPoint(point)) {
  4781. return false;
  4782. }
  4783. return true;
  4784. };
  4785. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  4786. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  4787. return false;
  4788. }
  4789. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  4790. return false;
  4791. }
  4792. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  4793. return false;
  4794. }
  4795. if (!precise) {
  4796. return true;
  4797. }
  4798. var box0 = this.boundingBox;
  4799. var box1 = boundingInfo.boundingBox;
  4800. if (!axisOverlap(box0.directions[0], box0, box1))
  4801. return false;
  4802. if (!axisOverlap(box0.directions[1], box0, box1))
  4803. return false;
  4804. if (!axisOverlap(box0.directions[2], box0, box1))
  4805. return false;
  4806. if (!axisOverlap(box1.directions[0], box0, box1))
  4807. return false;
  4808. if (!axisOverlap(box1.directions[1], box0, box1))
  4809. return false;
  4810. if (!axisOverlap(box1.directions[2], box0, box1))
  4811. return false;
  4812. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  4813. return false;
  4814. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  4815. return false;
  4816. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  4817. return false;
  4818. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  4819. return false;
  4820. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  4821. return false;
  4822. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  4823. return false;
  4824. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  4825. return false;
  4826. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  4827. return false;
  4828. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  4829. return false;
  4830. return true;
  4831. };
  4832. return BoundingInfo;
  4833. })();
  4834. BABYLON.BoundingInfo = BoundingInfo;
  4835. })(BABYLON || (BABYLON = {}));
  4836. //# sourceMappingURL=babylon.boundingInfo.js.map
  4837. var BABYLON;
  4838. (function (BABYLON) {
  4839. var Light = (function (_super) {
  4840. __extends(Light, _super);
  4841. function Light(name, scene) {
  4842. _super.call(this, name, scene);
  4843. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  4844. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  4845. this.intensity = 1.0;
  4846. this.range = Number.MAX_VALUE;
  4847. this.includedOnlyMeshes = new Array();
  4848. this.excludedMeshes = new Array();
  4849. this._excludedMeshesIds = new Array();
  4850. this._includedOnlyMeshesIds = new Array();
  4851. scene.lights.push(this);
  4852. }
  4853. Light.prototype.getShadowGenerator = function () {
  4854. return this._shadowGenerator;
  4855. };
  4856. Light.prototype.getAbsolutePosition = function () {
  4857. return BABYLON.Vector3.Zero();
  4858. };
  4859. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  4860. };
  4861. Light.prototype._getWorldMatrix = function () {
  4862. return BABYLON.Matrix.Identity();
  4863. };
  4864. Light.prototype.canAffectMesh = function (mesh) {
  4865. if (!mesh) {
  4866. return true;
  4867. }
  4868. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  4869. return false;
  4870. }
  4871. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  4872. return false;
  4873. }
  4874. return true;
  4875. };
  4876. Light.prototype.getWorldMatrix = function () {
  4877. this._currentRenderId = this.getScene().getRenderId();
  4878. var worldMatrix = this._getWorldMatrix();
  4879. if (this.parent && this.parent.getWorldMatrix) {
  4880. if (!this._parentedWorldMatrix) {
  4881. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  4882. }
  4883. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  4884. return this._parentedWorldMatrix;
  4885. }
  4886. return worldMatrix;
  4887. };
  4888. Light.prototype.dispose = function () {
  4889. if (this._shadowGenerator) {
  4890. this._shadowGenerator.dispose();
  4891. this._shadowGenerator = null;
  4892. }
  4893. // Remove from scene
  4894. var index = this.getScene().lights.indexOf(this);
  4895. this.getScene().lights.splice(index, 1);
  4896. };
  4897. return Light;
  4898. })(BABYLON.Node);
  4899. BABYLON.Light = Light;
  4900. })(BABYLON || (BABYLON = {}));
  4901. //# sourceMappingURL=babylon.light.js.map
  4902. var BABYLON;
  4903. (function (BABYLON) {
  4904. var PointLight = (function (_super) {
  4905. __extends(PointLight, _super);
  4906. function PointLight(name, position, scene) {
  4907. _super.call(this, name, scene);
  4908. this.position = position;
  4909. }
  4910. PointLight.prototype.getAbsolutePosition = function () {
  4911. return this._transformedPosition ? this._transformedPosition : this.position;
  4912. };
  4913. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  4914. if (this.parent && this.parent.getWorldMatrix) {
  4915. if (!this._transformedPosition) {
  4916. this._transformedPosition = BABYLON.Vector3.Zero();
  4917. }
  4918. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  4919. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, 0);
  4920. return;
  4921. }
  4922. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  4923. };
  4924. PointLight.prototype.getShadowGenerator = function () {
  4925. return null;
  4926. };
  4927. PointLight.prototype._getWorldMatrix = function () {
  4928. if (!this._worldMatrix) {
  4929. this._worldMatrix = BABYLON.Matrix.Identity();
  4930. }
  4931. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  4932. return this._worldMatrix;
  4933. };
  4934. return PointLight;
  4935. })(BABYLON.Light);
  4936. BABYLON.PointLight = PointLight;
  4937. })(BABYLON || (BABYLON = {}));
  4938. //# sourceMappingURL=babylon.pointLight.js.map
  4939. var BABYLON;
  4940. (function (BABYLON) {
  4941. var SpotLight = (function (_super) {
  4942. __extends(SpotLight, _super);
  4943. function SpotLight(name, position, direction, angle, exponent, scene) {
  4944. _super.call(this, name, scene);
  4945. this.position = position;
  4946. this.direction = direction;
  4947. this.angle = angle;
  4948. this.exponent = exponent;
  4949. }
  4950. SpotLight.prototype.getAbsolutePosition = function () {
  4951. return this._transformedPosition ? this._transformedPosition : this.position;
  4952. };
  4953. SpotLight.prototype.setDirectionToTarget = function (target) {
  4954. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  4955. return this.direction;
  4956. };
  4957. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  4958. var normalizeDirection;
  4959. if (this.parent && this.parent.getWorldMatrix) {
  4960. if (!this._transformedDirection) {
  4961. this._transformedDirection = BABYLON.Vector3.Zero();
  4962. }
  4963. if (!this._transformedPosition) {
  4964. this._transformedPosition = BABYLON.Vector3.Zero();
  4965. }
  4966. var parentWorldMatrix = this.parent.getWorldMatrix();
  4967. BABYLON.Vector3.TransformCoordinatesToRef(this.position, parentWorldMatrix, this._transformedPosition);
  4968. BABYLON.Vector3.TransformNormalToRef(this.direction, parentWorldMatrix, this._transformedDirection);
  4969. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, this.exponent);
  4970. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  4971. } else {
  4972. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  4973. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  4974. }
  4975. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  4976. };
  4977. SpotLight.prototype._getWorldMatrix = function () {
  4978. if (!this._worldMatrix) {
  4979. this._worldMatrix = BABYLON.Matrix.Identity();
  4980. }
  4981. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  4982. return this._worldMatrix;
  4983. };
  4984. return SpotLight;
  4985. })(BABYLON.Light);
  4986. BABYLON.SpotLight = SpotLight;
  4987. })(BABYLON || (BABYLON = {}));
  4988. //# sourceMappingURL=babylon.spotLight.js.map
  4989. var BABYLON;
  4990. (function (BABYLON) {
  4991. var DirectionalLight = (function (_super) {
  4992. __extends(DirectionalLight, _super);
  4993. function DirectionalLight(name, direction, scene) {
  4994. _super.call(this, name, scene);
  4995. this.direction = direction;
  4996. this.position = direction.scale(-1);
  4997. }
  4998. DirectionalLight.prototype.getAbsolutePosition = function () {
  4999. return this._transformedPosition ? this._transformedPosition : this.position;
  5000. };
  5001. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  5002. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  5003. return this.direction;
  5004. };
  5005. DirectionalLight.prototype._computeTransformedPosition = function () {
  5006. if (this.parent && this.parent.getWorldMatrix) {
  5007. if (!this._transformedPosition) {
  5008. this._transformedPosition = BABYLON.Vector3.Zero();
  5009. }
  5010. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  5011. return true;
  5012. }
  5013. return false;
  5014. };
  5015. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  5016. if (this.parent && this.parent.getWorldMatrix) {
  5017. if (!this._transformedDirection) {
  5018. this._transformedDirection = BABYLON.Vector3.Zero();
  5019. }
  5020. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  5021. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  5022. return;
  5023. }
  5024. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  5025. };
  5026. DirectionalLight.prototype._getWorldMatrix = function () {
  5027. if (!this._worldMatrix) {
  5028. this._worldMatrix = BABYLON.Matrix.Identity();
  5029. }
  5030. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  5031. return this._worldMatrix;
  5032. };
  5033. return DirectionalLight;
  5034. })(BABYLON.Light);
  5035. BABYLON.DirectionalLight = DirectionalLight;
  5036. })(BABYLON || (BABYLON = {}));
  5037. //# sourceMappingURL=babylon.directionalLight.js.map
  5038. var BABYLON;
  5039. (function (BABYLON) {
  5040. var ShadowGenerator = (function () {
  5041. function ShadowGenerator(mapSize, light) {
  5042. var _this = this;
  5043. // Members
  5044. this.filter = ShadowGenerator.FILTER_VARIANCESHADOWMAP;
  5045. this._darkness = 0;
  5046. this._transparencyShadow = false;
  5047. this._viewMatrix = BABYLON.Matrix.Zero();
  5048. this._projectionMatrix = BABYLON.Matrix.Zero();
  5049. this._transformMatrix = BABYLON.Matrix.Zero();
  5050. this._worldViewProjection = BABYLON.Matrix.Zero();
  5051. this._light = light;
  5052. this._scene = light.getScene();
  5053. light._shadowGenerator = this;
  5054. // Render target
  5055. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false);
  5056. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  5057. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  5058. this._shadowMap.renderParticles = false;
  5059. // Custom render function
  5060. var renderSubMesh = function (subMesh) {
  5061. var mesh = subMesh.getRenderingMesh();
  5062. var scene = _this._scene;
  5063. var engine = scene.getEngine();
  5064. // Culling
  5065. engine.setState(subMesh.getMaterial().backFaceCulling);
  5066. // Managing instances
  5067. var batch = mesh._getInstancesRenderList(subMesh._id);
  5068. if (batch.mustReturn) {
  5069. return;
  5070. }
  5071. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  5072. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  5073. engine.enableEffect(_this._effect);
  5074. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  5075. var material = subMesh.getMaterial();
  5076. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  5077. // Alpha test
  5078. if (material && material.needAlphaTesting()) {
  5079. var alphaTexture = material.getAlphaTestTexture();
  5080. _this._effect.setTexture("diffuseSampler", alphaTexture);
  5081. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  5082. }
  5083. // Bones
  5084. var useBones = mesh.skeleton && scene.skeletonsEnabled && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  5085. if (useBones) {
  5086. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  5087. }
  5088. if (hardwareInstancedRendering) {
  5089. mesh._renderWithInstances(subMesh, BABYLON.Material.TriangleFillMode, batch, _this._effect, engine);
  5090. } else {
  5091. if (batch.renderSelf[subMesh._id]) {
  5092. _this._effect.setMatrix("world", mesh.getWorldMatrix());
  5093. // Draw
  5094. mesh._draw(subMesh, BABYLON.Material.TriangleFillMode);
  5095. }
  5096. if (batch.visibleInstances[subMesh._id]) {
  5097. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  5098. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  5099. _this._effect.setMatrix("world", instance.getWorldMatrix());
  5100. // Draw
  5101. mesh._draw(subMesh, BABYLON.Material.TriangleFillMode);
  5102. }
  5103. }
  5104. }
  5105. } else {
  5106. // Need to reset refresh rate of the shadowMap
  5107. _this._shadowMap.resetRefreshCounter();
  5108. }
  5109. };
  5110. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  5111. var index;
  5112. for (index = 0; index < opaqueSubMeshes.length; index++) {
  5113. renderSubMesh(opaqueSubMeshes.data[index]);
  5114. }
  5115. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  5116. renderSubMesh(alphaTestSubMeshes.data[index]);
  5117. }
  5118. if (_this._transparencyShadow) {
  5119. for (index = 0; index < transparentSubMeshes.length; index++) {
  5120. renderSubMesh(transparentSubMeshes.data[index]);
  5121. }
  5122. }
  5123. };
  5124. }
  5125. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  5126. // Static
  5127. get: function () {
  5128. return ShadowGenerator._FILTER_NONE;
  5129. },
  5130. enumerable: true,
  5131. configurable: true
  5132. });
  5133. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  5134. get: function () {
  5135. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  5136. },
  5137. enumerable: true,
  5138. configurable: true
  5139. });
  5140. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  5141. get: function () {
  5142. return ShadowGenerator._FILTER_POISSONSAMPLING;
  5143. },
  5144. enumerable: true,
  5145. configurable: true
  5146. });
  5147. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  5148. get: function () {
  5149. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP;
  5150. },
  5151. set: function (value) {
  5152. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  5153. },
  5154. enumerable: true,
  5155. configurable: true
  5156. });
  5157. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  5158. get: function () {
  5159. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  5160. },
  5161. set: function (value) {
  5162. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  5163. },
  5164. enumerable: true,
  5165. configurable: true
  5166. });
  5167. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  5168. var defines = [];
  5169. if (this.useVarianceShadowMap) {
  5170. defines.push("#define VSM");
  5171. }
  5172. var attribs = [BABYLON.VertexBuffer.PositionKind];
  5173. var mesh = subMesh.getMesh();
  5174. var scene = mesh.getScene();
  5175. var material = subMesh.getMaterial();
  5176. // Alpha test
  5177. if (material && material.needAlphaTesting()) {
  5178. defines.push("#define ALPHATEST");
  5179. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  5180. attribs.push(BABYLON.VertexBuffer.UVKind);
  5181. defines.push("#define UV1");
  5182. }
  5183. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  5184. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  5185. defines.push("#define UV2");
  5186. }
  5187. }
  5188. // Bones
  5189. if (mesh.skeleton && scene.skeletonsEnabled && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  5190. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  5191. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  5192. defines.push("#define BONES");
  5193. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  5194. }
  5195. // Instances
  5196. if (useInstances) {
  5197. defines.push("#define INSTANCES");
  5198. attribs.push("world0");
  5199. attribs.push("world1");
  5200. attribs.push("world2");
  5201. attribs.push("world3");
  5202. }
  5203. // Get correct effect
  5204. var join = defines.join("\n");
  5205. if (this._cachedDefines != join) {
  5206. this._cachedDefines = join;
  5207. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  5208. }
  5209. return this._effect.isReady();
  5210. };
  5211. ShadowGenerator.prototype.getShadowMap = function () {
  5212. return this._shadowMap;
  5213. };
  5214. ShadowGenerator.prototype.getLight = function () {
  5215. return this._light;
  5216. };
  5217. // Methods
  5218. ShadowGenerator.prototype.getTransformMatrix = function () {
  5219. var lightPosition = this._light.position;
  5220. var lightDirection = this._light.direction;
  5221. if (this._light._computeTransformedPosition()) {
  5222. lightPosition = this._light._transformedPosition;
  5223. }
  5224. if (!this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !lightDirection.equals(this._cachedDirection)) {
  5225. this._cachedPosition = lightPosition.clone();
  5226. this._cachedDirection = lightDirection.clone();
  5227. var activeCamera = this._scene.activeCamera;
  5228. BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  5229. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2.0, 1.0, activeCamera.minZ, activeCamera.maxZ, this._projectionMatrix);
  5230. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  5231. }
  5232. return this._transformMatrix;
  5233. };
  5234. ShadowGenerator.prototype.getDarkness = function () {
  5235. return this._darkness;
  5236. };
  5237. ShadowGenerator.prototype.setDarkness = function (darkness) {
  5238. if (darkness >= 1.0)
  5239. this._darkness = 1.0;
  5240. else if (darkness <= 0.0)
  5241. this._darkness = 0.0;
  5242. else
  5243. this._darkness = darkness;
  5244. };
  5245. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  5246. this._transparencyShadow = hasShadow;
  5247. };
  5248. ShadowGenerator.prototype.dispose = function () {
  5249. this._shadowMap.dispose();
  5250. };
  5251. ShadowGenerator._FILTER_NONE = 0;
  5252. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  5253. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  5254. return ShadowGenerator;
  5255. })();
  5256. BABYLON.ShadowGenerator = ShadowGenerator;
  5257. })(BABYLON || (BABYLON = {}));
  5258. //# sourceMappingURL=babylon.shadowGenerator.js.map
  5259. var BABYLON;
  5260. (function (BABYLON) {
  5261. var HemisphericLight = (function (_super) {
  5262. __extends(HemisphericLight, _super);
  5263. function HemisphericLight(name, direction, scene) {
  5264. _super.call(this, name, scene);
  5265. this.direction = direction;
  5266. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  5267. }
  5268. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  5269. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  5270. return this.direction;
  5271. };
  5272. HemisphericLight.prototype.getShadowGenerator = function () {
  5273. return null;
  5274. };
  5275. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  5276. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  5277. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  5278. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  5279. };
  5280. HemisphericLight.prototype._getWorldMatrix = function () {
  5281. if (!this._worldMatrix) {
  5282. this._worldMatrix = BABYLON.Matrix.Identity();
  5283. }
  5284. return this._worldMatrix;
  5285. };
  5286. return HemisphericLight;
  5287. })(BABYLON.Light);
  5288. BABYLON.HemisphericLight = HemisphericLight;
  5289. })(BABYLON || (BABYLON = {}));
  5290. //# sourceMappingURL=babylon.hemisphericLight.js.map
  5291. var BABYLON;
  5292. (function (BABYLON) {
  5293. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  5294. if (boxMin.x > sphereCenter.x + sphereRadius)
  5295. return false;
  5296. if (sphereCenter.x - sphereRadius > boxMax.x)
  5297. return false;
  5298. if (boxMin.y > sphereCenter.y + sphereRadius)
  5299. return false;
  5300. if (sphereCenter.y - sphereRadius > boxMax.y)
  5301. return false;
  5302. if (boxMin.z > sphereCenter.z + sphereRadius)
  5303. return false;
  5304. if (sphereCenter.z - sphereRadius > boxMax.z)
  5305. return false;
  5306. return true;
  5307. };
  5308. var getLowestRoot = function (a, b, c, maxR) {
  5309. var determinant = b * b - 4.0 * a * c;
  5310. var result = { root: 0, found: false };
  5311. if (determinant < 0)
  5312. return result;
  5313. var sqrtD = Math.sqrt(determinant);
  5314. var r1 = (-b - sqrtD) / (2.0 * a);
  5315. var r2 = (-b + sqrtD) / (2.0 * a);
  5316. if (r1 > r2) {
  5317. var temp = r2;
  5318. r2 = r1;
  5319. r1 = temp;
  5320. }
  5321. if (r1 > 0 && r1 < maxR) {
  5322. result.root = r1;
  5323. result.found = true;
  5324. return result;
  5325. }
  5326. if (r2 > 0 && r2 < maxR) {
  5327. result.root = r2;
  5328. result.found = true;
  5329. return result;
  5330. }
  5331. return result;
  5332. };
  5333. var Collider = (function () {
  5334. function Collider() {
  5335. this.radius = new BABYLON.Vector3(1, 1, 1);
  5336. this.retry = 0;
  5337. this.basePointWorld = BABYLON.Vector3.Zero();
  5338. this.velocityWorld = BABYLON.Vector3.Zero();
  5339. this.normalizedVelocity = BABYLON.Vector3.Zero();
  5340. this._collisionPoint = BABYLON.Vector3.Zero();
  5341. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  5342. this._tempVector = BABYLON.Vector3.Zero();
  5343. this._tempVector2 = BABYLON.Vector3.Zero();
  5344. this._tempVector3 = BABYLON.Vector3.Zero();
  5345. this._tempVector4 = BABYLON.Vector3.Zero();
  5346. this._edge = BABYLON.Vector3.Zero();
  5347. this._baseToVertex = BABYLON.Vector3.Zero();
  5348. this._destinationPoint = BABYLON.Vector3.Zero();
  5349. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  5350. this._displacementVector = BABYLON.Vector3.Zero();
  5351. }
  5352. // Methods
  5353. Collider.prototype._initialize = function (source, dir, e) {
  5354. this.velocity = dir;
  5355. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  5356. this.basePoint = source;
  5357. source.multiplyToRef(this.radius, this.basePointWorld);
  5358. dir.multiplyToRef(this.radius, this.velocityWorld);
  5359. this.velocityWorldLength = this.velocityWorld.length();
  5360. this.epsilon = e;
  5361. this.collisionFound = false;
  5362. };
  5363. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  5364. pa.subtractToRef(point, this._tempVector);
  5365. pb.subtractToRef(point, this._tempVector2);
  5366. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  5367. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  5368. if (d < 0)
  5369. return false;
  5370. pc.subtractToRef(point, this._tempVector3);
  5371. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  5372. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  5373. if (d < 0)
  5374. return false;
  5375. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  5376. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  5377. return d >= 0;
  5378. };
  5379. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  5380. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  5381. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  5382. if (distance > this.velocityWorldLength + max + sphereRadius) {
  5383. return false;
  5384. }
  5385. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  5386. return false;
  5387. return true;
  5388. };
  5389. Collider.prototype._testTriangle = function (faceIndex, subMesh, p1, p2, p3) {
  5390. var t0;
  5391. var embeddedInPlane = false;
  5392. if (!subMesh._trianglePlanes) {
  5393. subMesh._trianglePlanes = [];
  5394. }
  5395. if (!subMesh._trianglePlanes[faceIndex]) {
  5396. subMesh._trianglePlanes[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  5397. subMesh._trianglePlanes[faceIndex].copyFromPoints(p1, p2, p3);
  5398. }
  5399. var trianglePlane = subMesh._trianglePlanes[faceIndex];
  5400. if ((!subMesh.getMaterial()) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  5401. return;
  5402. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  5403. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  5404. if (normalDotVelocity == 0) {
  5405. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  5406. return;
  5407. embeddedInPlane = true;
  5408. t0 = 0;
  5409. } else {
  5410. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  5411. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  5412. if (t0 > t1) {
  5413. var temp = t1;
  5414. t1 = t0;
  5415. t0 = temp;
  5416. }
  5417. if (t0 > 1.0 || t1 < 0.0)
  5418. return;
  5419. if (t0 < 0)
  5420. t0 = 0;
  5421. if (t0 > 1.0)
  5422. t0 = 1.0;
  5423. }
  5424. this._collisionPoint.copyFromFloats(0, 0, 0);
  5425. var found = false;
  5426. var t = 1.0;
  5427. if (!embeddedInPlane) {
  5428. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  5429. this.velocity.scaleToRef(t0, this._tempVector);
  5430. this._planeIntersectionPoint.addInPlace(this._tempVector);
  5431. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  5432. found = true;
  5433. t = t0;
  5434. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  5435. }
  5436. }
  5437. if (!found) {
  5438. var velocitySquaredLength = this.velocity.lengthSquared();
  5439. var a = velocitySquaredLength;
  5440. this.basePoint.subtractToRef(p1, this._tempVector);
  5441. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  5442. var c = this._tempVector.lengthSquared() - 1.0;
  5443. var lowestRoot = getLowestRoot(a, b, c, t);
  5444. if (lowestRoot.found) {
  5445. t = lowestRoot.root;
  5446. found = true;
  5447. this._collisionPoint.copyFrom(p1);
  5448. }
  5449. this.basePoint.subtractToRef(p2, this._tempVector);
  5450. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  5451. c = this._tempVector.lengthSquared() - 1.0;
  5452. lowestRoot = getLowestRoot(a, b, c, t);
  5453. if (lowestRoot.found) {
  5454. t = lowestRoot.root;
  5455. found = true;
  5456. this._collisionPoint.copyFrom(p2);
  5457. }
  5458. this.basePoint.subtractToRef(p3, this._tempVector);
  5459. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  5460. c = this._tempVector.lengthSquared() - 1.0;
  5461. lowestRoot = getLowestRoot(a, b, c, t);
  5462. if (lowestRoot.found) {
  5463. t = lowestRoot.root;
  5464. found = true;
  5465. this._collisionPoint.copyFrom(p3);
  5466. }
  5467. p2.subtractToRef(p1, this._edge);
  5468. p1.subtractToRef(this.basePoint, this._baseToVertex);
  5469. var edgeSquaredLength = this._edge.lengthSquared();
  5470. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  5471. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  5472. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  5473. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  5474. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  5475. lowestRoot = getLowestRoot(a, b, c, t);
  5476. if (lowestRoot.found) {
  5477. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  5478. if (f >= 0.0 && f <= 1.0) {
  5479. t = lowestRoot.root;
  5480. found = true;
  5481. this._edge.scaleInPlace(f);
  5482. p1.addToRef(this._edge, this._collisionPoint);
  5483. }
  5484. }
  5485. p3.subtractToRef(p2, this._edge);
  5486. p2.subtractToRef(this.basePoint, this._baseToVertex);
  5487. edgeSquaredLength = this._edge.lengthSquared();
  5488. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  5489. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  5490. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  5491. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  5492. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  5493. lowestRoot = getLowestRoot(a, b, c, t);
  5494. if (lowestRoot.found) {
  5495. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  5496. if (f >= 0.0 && f <= 1.0) {
  5497. t = lowestRoot.root;
  5498. found = true;
  5499. this._edge.scaleInPlace(f);
  5500. p2.addToRef(this._edge, this._collisionPoint);
  5501. }
  5502. }
  5503. p1.subtractToRef(p3, this._edge);
  5504. p3.subtractToRef(this.basePoint, this._baseToVertex);
  5505. edgeSquaredLength = this._edge.lengthSquared();
  5506. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  5507. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  5508. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  5509. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  5510. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  5511. lowestRoot = getLowestRoot(a, b, c, t);
  5512. if (lowestRoot.found) {
  5513. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  5514. if (f >= 0.0 && f <= 1.0) {
  5515. t = lowestRoot.root;
  5516. found = true;
  5517. this._edge.scaleInPlace(f);
  5518. p3.addToRef(this._edge, this._collisionPoint);
  5519. }
  5520. }
  5521. }
  5522. if (found) {
  5523. var distToCollision = t * this.velocity.length();
  5524. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  5525. if (!this.intersectionPoint) {
  5526. this.intersectionPoint = this._collisionPoint.clone();
  5527. } else {
  5528. this.intersectionPoint.copyFrom(this._collisionPoint);
  5529. }
  5530. this.nearestDistance = distToCollision;
  5531. this.collisionFound = true;
  5532. this.collidedMesh = subMesh.getMesh();
  5533. }
  5534. }
  5535. };
  5536. Collider.prototype._collide = function (subMesh, pts, indices, indexStart, indexEnd, decal) {
  5537. for (var i = indexStart; i < indexEnd; i += 3) {
  5538. var p1 = pts[indices[i] - decal];
  5539. var p2 = pts[indices[i + 1] - decal];
  5540. var p3 = pts[indices[i + 2] - decal];
  5541. this._testTriangle(i, subMesh, p3, p2, p1);
  5542. }
  5543. };
  5544. Collider.prototype._getResponse = function (pos, vel) {
  5545. pos.addToRef(vel, this._destinationPoint);
  5546. vel.scaleInPlace((this.nearestDistance / vel.length()));
  5547. this.basePoint.addToRef(vel, pos);
  5548. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  5549. this._slidePlaneNormal.normalize();
  5550. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  5551. pos.addInPlace(this._displacementVector);
  5552. this.intersectionPoint.addInPlace(this._displacementVector);
  5553. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  5554. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  5555. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  5556. };
  5557. return Collider;
  5558. })();
  5559. BABYLON.Collider = Collider;
  5560. })(BABYLON || (BABYLON = {}));
  5561. //# sourceMappingURL=babylon.collider.js.map
  5562. var BABYLON;
  5563. (function (BABYLON) {
  5564. var Camera = (function (_super) {
  5565. __extends(Camera, _super);
  5566. function Camera(name, position, scene) {
  5567. _super.call(this, name, scene);
  5568. this.position = position;
  5569. // Members
  5570. this.upVector = BABYLON.Vector3.Up();
  5571. this.orthoLeft = null;
  5572. this.orthoRight = null;
  5573. this.orthoBottom = null;
  5574. this.orthoTop = null;
  5575. this.fov = 0.8;
  5576. this.minZ = 1.0;
  5577. this.maxZ = 10000.0;
  5578. this.inertia = 0.9;
  5579. this.mode = Camera.PERSPECTIVE_CAMERA;
  5580. this.isIntermediate = false;
  5581. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  5582. this.subCameras = [];
  5583. this.layerMask = 0xFFFFFFFF;
  5584. this._computedViewMatrix = BABYLON.Matrix.Identity();
  5585. this._projectionMatrix = new BABYLON.Matrix();
  5586. this._postProcesses = new Array();
  5587. this._postProcessesTakenIndices = [];
  5588. scene.cameras.push(this);
  5589. if (!scene.activeCamera) {
  5590. scene.activeCamera = this;
  5591. }
  5592. }
  5593. //Cache
  5594. Camera.prototype._initCache = function () {
  5595. _super.prototype._initCache.call(this);
  5596. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5597. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5598. this._cache.mode = undefined;
  5599. this._cache.minZ = undefined;
  5600. this._cache.maxZ = undefined;
  5601. this._cache.fov = undefined;
  5602. this._cache.aspectRatio = undefined;
  5603. this._cache.orthoLeft = undefined;
  5604. this._cache.orthoRight = undefined;
  5605. this._cache.orthoBottom = undefined;
  5606. this._cache.orthoTop = undefined;
  5607. this._cache.renderWidth = undefined;
  5608. this._cache.renderHeight = undefined;
  5609. };
  5610. Camera.prototype._updateCache = function (ignoreParentClass) {
  5611. if (!ignoreParentClass) {
  5612. _super.prototype._updateCache.call(this);
  5613. }
  5614. var engine = this.getEngine();
  5615. this._cache.position.copyFrom(this.position);
  5616. this._cache.upVector.copyFrom(this.upVector);
  5617. this._cache.mode = this.mode;
  5618. this._cache.minZ = this.minZ;
  5619. this._cache.maxZ = this.maxZ;
  5620. this._cache.fov = this.fov;
  5621. this._cache.aspectRatio = engine.getAspectRatio(this);
  5622. this._cache.orthoLeft = this.orthoLeft;
  5623. this._cache.orthoRight = this.orthoRight;
  5624. this._cache.orthoBottom = this.orthoBottom;
  5625. this._cache.orthoTop = this.orthoTop;
  5626. this._cache.renderWidth = engine.getRenderWidth();
  5627. this._cache.renderHeight = engine.getRenderHeight();
  5628. };
  5629. Camera.prototype._updateFromScene = function () {
  5630. this.updateCache();
  5631. this._update();
  5632. };
  5633. // Synchronized
  5634. Camera.prototype._isSynchronized = function () {
  5635. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  5636. };
  5637. Camera.prototype._isSynchronizedViewMatrix = function () {
  5638. if (!_super.prototype._isSynchronized.call(this))
  5639. return false;
  5640. return this._cache.position.equals(this.position) && this._cache.upVector.equals(this.upVector) && this.isSynchronizedWithParent();
  5641. };
  5642. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  5643. var check = this._cache.mode === this.mode && this._cache.minZ === this.minZ && this._cache.maxZ === this.maxZ;
  5644. if (!check) {
  5645. return false;
  5646. }
  5647. var engine = this.getEngine();
  5648. if (this.mode === BABYLON.Camera.PERSPECTIVE_CAMERA) {
  5649. check = this._cache.fov === this.fov && this._cache.aspectRatio === engine.getAspectRatio(this);
  5650. } else {
  5651. 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();
  5652. }
  5653. return check;
  5654. };
  5655. // Controls
  5656. Camera.prototype.attachControl = function (element) {
  5657. };
  5658. Camera.prototype.detachControl = function (element) {
  5659. };
  5660. Camera.prototype._update = function () {
  5661. };
  5662. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  5663. if (typeof insertAt === "undefined") { insertAt = null; }
  5664. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  5665. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  5666. return 0;
  5667. }
  5668. if (insertAt == null || insertAt < 0) {
  5669. this._postProcesses.push(postProcess);
  5670. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  5671. return this._postProcesses.length - 1;
  5672. }
  5673. var add = 0;
  5674. if (this._postProcesses[insertAt]) {
  5675. var start = this._postProcesses.length - 1;
  5676. for (var i = start; i >= insertAt + 1; --i) {
  5677. this._postProcesses[i + 1] = this._postProcesses[i];
  5678. }
  5679. add = 1;
  5680. }
  5681. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  5682. if (this._postProcessesTakenIndices[i] < insertAt) {
  5683. continue;
  5684. }
  5685. start = this._postProcessesTakenIndices.length - 1;
  5686. for (var j = start; j >= i; --j) {
  5687. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  5688. }
  5689. this._postProcessesTakenIndices[i] = insertAt;
  5690. break;
  5691. }
  5692. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) == -1) {
  5693. this._postProcessesTakenIndices.push(insertAt);
  5694. }
  5695. var result = insertAt + add;
  5696. this._postProcesses[result] = postProcess;
  5697. return result;
  5698. };
  5699. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  5700. if (typeof atIndices === "undefined") { atIndices = null; }
  5701. var result = [];
  5702. if (!atIndices) {
  5703. var length = this._postProcesses.length;
  5704. for (var i = 0; i < length; i++) {
  5705. if (this._postProcesses[i] !== postProcess) {
  5706. continue;
  5707. }
  5708. delete this._postProcesses[i];
  5709. var index = this._postProcessesTakenIndices.indexOf(i);
  5710. this._postProcessesTakenIndices.splice(index, 1);
  5711. }
  5712. } else {
  5713. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  5714. for (i = 0; i < atIndices.length; i++) {
  5715. var foundPostProcess = this._postProcesses[atIndices[i]];
  5716. if (foundPostProcess !== postProcess) {
  5717. result.push(i);
  5718. continue;
  5719. }
  5720. delete this._postProcesses[atIndices[i]];
  5721. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  5722. this._postProcessesTakenIndices.splice(index, 1);
  5723. }
  5724. }
  5725. return result;
  5726. };
  5727. Camera.prototype.getWorldMatrix = function () {
  5728. if (!this._worldMatrix) {
  5729. this._worldMatrix = BABYLON.Matrix.Identity();
  5730. }
  5731. var viewMatrix = this.getViewMatrix();
  5732. viewMatrix.invertToRef(this._worldMatrix);
  5733. return this._worldMatrix;
  5734. };
  5735. Camera.prototype._getViewMatrix = function () {
  5736. return BABYLON.Matrix.Identity();
  5737. };
  5738. Camera.prototype.getViewMatrix = function () {
  5739. this._computedViewMatrix = this._computeViewMatrix();
  5740. if (!this.parent || !this.parent.getWorldMatrix || this.isSynchronized()) {
  5741. return this._computedViewMatrix;
  5742. }
  5743. if (!this._worldMatrix) {
  5744. this._worldMatrix = BABYLON.Matrix.Identity();
  5745. }
  5746. this._computedViewMatrix.invertToRef(this._worldMatrix);
  5747. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  5748. this._computedViewMatrix.invert();
  5749. this._currentRenderId = this.getScene().getRenderId();
  5750. return this._computedViewMatrix;
  5751. };
  5752. Camera.prototype._computeViewMatrix = function (force) {
  5753. if (!force && this._isSynchronizedViewMatrix()) {
  5754. return this._computedViewMatrix;
  5755. }
  5756. this._computedViewMatrix = this._getViewMatrix();
  5757. if (!this.parent || !this.parent.getWorldMatrix) {
  5758. this._currentRenderId = this.getScene().getRenderId();
  5759. }
  5760. return this._computedViewMatrix;
  5761. };
  5762. Camera.prototype.getProjectionMatrix = function (force) {
  5763. if (!force && this._isSynchronizedProjectionMatrix()) {
  5764. return this._projectionMatrix;
  5765. }
  5766. var engine = this.getEngine();
  5767. if (this.mode === BABYLON.Camera.PERSPECTIVE_CAMERA) {
  5768. if (this.minZ <= 0) {
  5769. this.minZ = 0.1;
  5770. }
  5771. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix);
  5772. return this._projectionMatrix;
  5773. }
  5774. var halfWidth = engine.getRenderWidth() / 2.0;
  5775. var halfHeight = engine.getRenderHeight() / 2.0;
  5776. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  5777. return this._projectionMatrix;
  5778. };
  5779. Camera.prototype.dispose = function () {
  5780. // Remove from scene
  5781. var index = this.getScene().cameras.indexOf(this);
  5782. this.getScene().cameras.splice(index, 1);
  5783. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  5784. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  5785. }
  5786. };
  5787. Camera.PERSPECTIVE_CAMERA = 0;
  5788. Camera.ORTHOGRAPHIC_CAMERA = 1;
  5789. return Camera;
  5790. })(BABYLON.Node);
  5791. BABYLON.Camera = Camera;
  5792. })(BABYLON || (BABYLON = {}));
  5793. //# sourceMappingURL=babylon.camera.js.map
  5794. var BABYLON;
  5795. (function (BABYLON) {
  5796. var TargetCamera = (function (_super) {
  5797. __extends(TargetCamera, _super);
  5798. function TargetCamera(name, position, scene) {
  5799. _super.call(this, name, position, scene);
  5800. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  5801. this.cameraRotation = new BABYLON.Vector2(0, 0);
  5802. this.rotation = new BABYLON.Vector3(0, 0, 0);
  5803. this.speed = 2.0;
  5804. this.noRotationConstraint = false;
  5805. this.lockedTarget = null;
  5806. this._currentTarget = BABYLON.Vector3.Zero();
  5807. this._viewMatrix = BABYLON.Matrix.Zero();
  5808. this._camMatrix = BABYLON.Matrix.Zero();
  5809. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  5810. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  5811. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  5812. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  5813. this._lookAtTemp = BABYLON.Matrix.Zero();
  5814. this._tempMatrix = BABYLON.Matrix.Zero();
  5815. }
  5816. TargetCamera.prototype._getLockedTargetPosition = function () {
  5817. if (!this.lockedTarget) {
  5818. return null;
  5819. }
  5820. return this.lockedTarget.position || this.lockedTarget;
  5821. };
  5822. // Cache
  5823. TargetCamera.prototype._initCache = function () {
  5824. _super.prototype._initCache.call(this);
  5825. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5826. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5827. };
  5828. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  5829. if (!ignoreParentClass) {
  5830. _super.prototype._updateCache.call(this);
  5831. }
  5832. var lockedTargetPosition = this._getLockedTargetPosition();
  5833. if (!lockedTargetPosition) {
  5834. this._cache.lockedTarget = null;
  5835. } else {
  5836. if (!this._cache.lockedTarget) {
  5837. this._cache.lockedTarget = lockedTargetPosition.clone();
  5838. } else {
  5839. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  5840. }
  5841. }
  5842. this._cache.rotation.copyFrom(this.rotation);
  5843. };
  5844. // Synchronized
  5845. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  5846. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  5847. return false;
  5848. }
  5849. var lockedTargetPosition = this._getLockedTargetPosition();
  5850. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition) && this._cache.rotation.equals(this.rotation);
  5851. };
  5852. // Methods
  5853. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  5854. var engine = this.getEngine();
  5855. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  5856. };
  5857. // Target
  5858. TargetCamera.prototype.setTarget = function (target) {
  5859. this.upVector.normalize();
  5860. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  5861. this._camMatrix.invert();
  5862. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  5863. var vDir = target.subtract(this.position);
  5864. if (vDir.x >= 0.0) {
  5865. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  5866. } else {
  5867. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  5868. }
  5869. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  5870. if (isNaN(this.rotation.x)) {
  5871. this.rotation.x = 0;
  5872. }
  5873. if (isNaN(this.rotation.y)) {
  5874. this.rotation.y = 0;
  5875. }
  5876. if (isNaN(this.rotation.z)) {
  5877. this.rotation.z = 0;
  5878. }
  5879. };
  5880. TargetCamera.prototype.getTarget = function () {
  5881. return this._currentTarget;
  5882. };
  5883. TargetCamera.prototype._decideIfNeedsToMove = function () {
  5884. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  5885. };
  5886. TargetCamera.prototype._updatePosition = function () {
  5887. this.position.addInPlace(this.cameraDirection);
  5888. };
  5889. TargetCamera.prototype._update = function () {
  5890. var needToMove = this._decideIfNeedsToMove();
  5891. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  5892. // Move
  5893. if (needToMove) {
  5894. this._updatePosition();
  5895. }
  5896. // Rotate
  5897. if (needToRotate) {
  5898. this.rotation.x += this.cameraRotation.x;
  5899. this.rotation.y += this.cameraRotation.y;
  5900. if (!this.noRotationConstraint) {
  5901. var limit = (Math.PI / 2) * 0.95;
  5902. if (this.rotation.x > limit)
  5903. this.rotation.x = limit;
  5904. if (this.rotation.x < -limit)
  5905. this.rotation.x = -limit;
  5906. }
  5907. }
  5908. // Inertia
  5909. if (needToMove) {
  5910. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  5911. this.cameraDirection.x = 0;
  5912. }
  5913. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  5914. this.cameraDirection.y = 0;
  5915. }
  5916. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  5917. this.cameraDirection.z = 0;
  5918. }
  5919. this.cameraDirection.scaleInPlace(this.inertia);
  5920. }
  5921. if (needToRotate) {
  5922. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  5923. this.cameraRotation.x = 0;
  5924. }
  5925. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  5926. this.cameraRotation.y = 0;
  5927. }
  5928. this.cameraRotation.scaleInPlace(this.inertia);
  5929. }
  5930. };
  5931. TargetCamera.prototype._getViewMatrix = function () {
  5932. if (!this.lockedTarget) {
  5933. // Compute
  5934. if (this.upVector.x != 0 || this.upVector.y != 1.0 || this.upVector.z != 0) {
  5935. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  5936. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  5937. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  5938. this._lookAtTemp.invert();
  5939. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  5940. } else {
  5941. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  5942. }
  5943. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  5944. // Computing target and final matrix
  5945. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  5946. } else {
  5947. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  5948. }
  5949. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  5950. return this._viewMatrix;
  5951. };
  5952. return TargetCamera;
  5953. })(BABYLON.Camera);
  5954. BABYLON.TargetCamera = TargetCamera;
  5955. })(BABYLON || (BABYLON = {}));
  5956. //# sourceMappingURL=babylon.targetCamera.js.map
  5957. var BABYLON;
  5958. (function (BABYLON) {
  5959. var FollowCamera = (function (_super) {
  5960. __extends(FollowCamera, _super);
  5961. function FollowCamera(name, position, scene) {
  5962. _super.call(this, name, position, scene);
  5963. this.radius = 12;
  5964. this.rotationOffset = 0;
  5965. this.heightOffset = 4;
  5966. this.cameraAcceleration = 0.05;
  5967. this.maxCameraSpeed = 20;
  5968. }
  5969. FollowCamera.prototype.getRadians = function (degrees) {
  5970. return degrees * Math.PI / 180;
  5971. };
  5972. FollowCamera.prototype.follow = function (cameraTarget) {
  5973. if (!cameraTarget)
  5974. return;
  5975. var radians = this.getRadians(this.rotationOffset) + cameraTarget.rotation.y;
  5976. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  5977. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  5978. var dx = targetX - this.position.x;
  5979. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  5980. var dz = (targetZ) - this.position.z;
  5981. var vx = dx * this.cameraAcceleration * 2;
  5982. var vy = dy * this.cameraAcceleration;
  5983. var vz = dz * this.cameraAcceleration * 2;
  5984. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  5985. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  5986. }
  5987. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  5988. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  5989. }
  5990. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  5991. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  5992. }
  5993. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  5994. this.setTarget(cameraTarget.position);
  5995. };
  5996. FollowCamera.prototype._update = function () {
  5997. _super.prototype._update.call(this);
  5998. this.follow(this.target);
  5999. };
  6000. return FollowCamera;
  6001. })(BABYLON.TargetCamera);
  6002. BABYLON.FollowCamera = FollowCamera;
  6003. })(BABYLON || (BABYLON = {}));
  6004. //# sourceMappingURL=babylon.followCamera.js.map
  6005. var BABYLON;
  6006. (function (BABYLON) {
  6007. var FreeCamera = (function (_super) {
  6008. __extends(FreeCamera, _super);
  6009. function FreeCamera(name, position, scene) {
  6010. _super.call(this, name, position, scene);
  6011. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  6012. this.keysUp = [38];
  6013. this.keysDown = [40];
  6014. this.keysLeft = [37];
  6015. this.keysRight = [39];
  6016. this.checkCollisions = false;
  6017. this.applyGravity = false;
  6018. this.angularSensibility = 2000.0;
  6019. this._keys = [];
  6020. this._collider = new BABYLON.Collider();
  6021. this._needMoveForGravity = true;
  6022. this._oldPosition = BABYLON.Vector3.Zero();
  6023. this._diffPosition = BABYLON.Vector3.Zero();
  6024. this._newPosition = BABYLON.Vector3.Zero();
  6025. }
  6026. // Controls
  6027. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  6028. var _this = this;
  6029. var previousPosition;
  6030. var engine = this.getEngine();
  6031. if (this._attachedElement) {
  6032. return;
  6033. }
  6034. this._attachedElement = element;
  6035. if (this._onMouseDown === undefined) {
  6036. this._onMouseDown = function (evt) {
  6037. previousPosition = {
  6038. x: evt.clientX,
  6039. y: evt.clientY
  6040. };
  6041. if (!noPreventDefault) {
  6042. evt.preventDefault();
  6043. }
  6044. };
  6045. this._onMouseUp = function (evt) {
  6046. previousPosition = null;
  6047. if (!noPreventDefault) {
  6048. evt.preventDefault();
  6049. }
  6050. };
  6051. this._onMouseOut = function (evt) {
  6052. previousPosition = null;
  6053. _this._keys = [];
  6054. if (!noPreventDefault) {
  6055. evt.preventDefault();
  6056. }
  6057. };
  6058. this._onMouseMove = function (evt) {
  6059. if (!previousPosition && !engine.isPointerLock) {
  6060. return;
  6061. }
  6062. var offsetX;
  6063. var offsetY;
  6064. if (!engine.isPointerLock) {
  6065. offsetX = evt.clientX - previousPosition.x;
  6066. offsetY = evt.clientY - previousPosition.y;
  6067. } else {
  6068. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  6069. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  6070. }
  6071. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  6072. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  6073. previousPosition = {
  6074. x: evt.clientX,
  6075. y: evt.clientY
  6076. };
  6077. if (!noPreventDefault) {
  6078. evt.preventDefault();
  6079. }
  6080. };
  6081. this._onKeyDown = function (evt) {
  6082. 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) {
  6083. var index = _this._keys.indexOf(evt.keyCode);
  6084. if (index === -1) {
  6085. _this._keys.push(evt.keyCode);
  6086. }
  6087. if (!noPreventDefault) {
  6088. evt.preventDefault();
  6089. }
  6090. }
  6091. };
  6092. this._onKeyUp = function (evt) {
  6093. 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) {
  6094. var index = _this._keys.indexOf(evt.keyCode);
  6095. if (index >= 0) {
  6096. _this._keys.splice(index, 1);
  6097. }
  6098. if (!noPreventDefault) {
  6099. evt.preventDefault();
  6100. }
  6101. }
  6102. };
  6103. this._onLostFocus = function () {
  6104. _this._keys = [];
  6105. };
  6106. this._reset = function () {
  6107. _this._keys = [];
  6108. previousPosition = null;
  6109. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  6110. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  6111. };
  6112. }
  6113. element.addEventListener("mousedown", this._onMouseDown, false);
  6114. element.addEventListener("mouseup", this._onMouseUp, false);
  6115. element.addEventListener("mouseout", this._onMouseOut, false);
  6116. element.addEventListener("mousemove", this._onMouseMove, false);
  6117. BABYLON.Tools.RegisterTopRootEvents([
  6118. { name: "keydown", handler: this._onKeyDown },
  6119. { name: "keyup", handler: this._onKeyUp },
  6120. { name: "blur", handler: this._onLostFocus }
  6121. ]);
  6122. };
  6123. FreeCamera.prototype.detachControl = function (element) {
  6124. if (this._attachedElement != element) {
  6125. return;
  6126. }
  6127. element.removeEventListener("mousedown", this._onMouseDown);
  6128. element.removeEventListener("mouseup", this._onMouseUp);
  6129. element.removeEventListener("mouseout", this._onMouseOut);
  6130. element.removeEventListener("mousemove", this._onMouseMove);
  6131. BABYLON.Tools.UnregisterTopRootEvents([
  6132. { name: "keydown", handler: this._onKeyDown },
  6133. { name: "keyup", handler: this._onKeyUp },
  6134. { name: "blur", handler: this._onLostFocus }
  6135. ]);
  6136. this._attachedElement = null;
  6137. if (this._reset) {
  6138. this._reset();
  6139. }
  6140. };
  6141. FreeCamera.prototype._collideWithWorld = function (velocity) {
  6142. var globalPosition;
  6143. if (this.parent) {
  6144. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  6145. } else {
  6146. globalPosition = this.position;
  6147. }
  6148. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  6149. this._collider.radius = this.ellipsoid;
  6150. this.getScene()._getNewPosition(this._oldPosition, velocity, this._collider, 3, this._newPosition);
  6151. this._newPosition.subtractToRef(this._oldPosition, this._diffPosition);
  6152. if (this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  6153. this.position.addInPlace(this._diffPosition);
  6154. if (this.onCollide) {
  6155. this.onCollide(this._collider.collidedMesh);
  6156. }
  6157. }
  6158. };
  6159. FreeCamera.prototype._checkInputs = function () {
  6160. if (!this._localDirection) {
  6161. this._localDirection = BABYLON.Vector3.Zero();
  6162. this._transformedDirection = BABYLON.Vector3.Zero();
  6163. }
  6164. for (var index = 0; index < this._keys.length; index++) {
  6165. var keyCode = this._keys[index];
  6166. var speed = this._computeLocalCameraSpeed();
  6167. if (this.keysLeft.indexOf(keyCode) !== -1) {
  6168. this._localDirection.copyFromFloats(-speed, 0, 0);
  6169. } else if (this.keysUp.indexOf(keyCode) !== -1) {
  6170. this._localDirection.copyFromFloats(0, 0, speed);
  6171. } else if (this.keysRight.indexOf(keyCode) !== -1) {
  6172. this._localDirection.copyFromFloats(speed, 0, 0);
  6173. } else if (this.keysDown.indexOf(keyCode) !== -1) {
  6174. this._localDirection.copyFromFloats(0, 0, -speed);
  6175. }
  6176. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  6177. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  6178. this.cameraDirection.addInPlace(this._transformedDirection);
  6179. }
  6180. };
  6181. FreeCamera.prototype._decideIfNeedsToMove = function () {
  6182. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  6183. };
  6184. FreeCamera.prototype._updatePosition = function () {
  6185. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  6186. this._collideWithWorld(this.cameraDirection);
  6187. if (this.applyGravity) {
  6188. var oldPosition = this.position;
  6189. this._collideWithWorld(this.getScene().gravity);
  6190. this._needMoveForGravity = (BABYLON.Vector3.DistanceSquared(oldPosition, this.position) != 0);
  6191. }
  6192. } else {
  6193. this.position.addInPlace(this.cameraDirection);
  6194. }
  6195. };
  6196. FreeCamera.prototype._update = function () {
  6197. this._checkInputs();
  6198. _super.prototype._update.call(this);
  6199. };
  6200. return FreeCamera;
  6201. })(BABYLON.TargetCamera);
  6202. BABYLON.FreeCamera = FreeCamera;
  6203. })(BABYLON || (BABYLON = {}));
  6204. //# sourceMappingURL=babylon.freeCamera.js.map
  6205. var BABYLON;
  6206. (function (BABYLON) {
  6207. // We're mainly based on the logic defined into the FreeCamera code
  6208. var TouchCamera = (function (_super) {
  6209. __extends(TouchCamera, _super);
  6210. function TouchCamera(name, position, scene) {
  6211. _super.call(this, name, position, scene);
  6212. this._offsetX = null;
  6213. this._offsetY = null;
  6214. this._pointerCount = 0;
  6215. this._pointerPressed = [];
  6216. this.angularSensibility = 200000.0;
  6217. this.moveSensibility = 500.0;
  6218. }
  6219. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  6220. var _this = this;
  6221. var previousPosition;
  6222. if (this._attachedCanvas) {
  6223. return;
  6224. }
  6225. this._attachedCanvas = canvas;
  6226. if (this._onPointerDown === undefined) {
  6227. this._onPointerDown = function (evt) {
  6228. if (!noPreventDefault) {
  6229. evt.preventDefault();
  6230. }
  6231. _this._pointerPressed.push(evt.pointerId);
  6232. if (_this._pointerPressed.length !== 1) {
  6233. return;
  6234. }
  6235. previousPosition = {
  6236. x: evt.clientX,
  6237. y: evt.clientY
  6238. };
  6239. };
  6240. this._onPointerUp = function (evt) {
  6241. if (!noPreventDefault) {
  6242. evt.preventDefault();
  6243. }
  6244. var index = _this._pointerPressed.indexOf(evt.pointerId);
  6245. if (index === -1) {
  6246. return;
  6247. }
  6248. _this._pointerPressed.splice(index, 1);
  6249. if (index != 0) {
  6250. return;
  6251. }
  6252. previousPosition = null;
  6253. _this._offsetX = null;
  6254. _this._offsetY = null;
  6255. };
  6256. this._onPointerMove = function (evt) {
  6257. if (!noPreventDefault) {
  6258. evt.preventDefault();
  6259. }
  6260. if (!previousPosition) {
  6261. return;
  6262. }
  6263. var index = _this._pointerPressed.indexOf(evt.pointerId);
  6264. if (index != 0) {
  6265. return;
  6266. }
  6267. _this._offsetX = evt.clientX - previousPosition.x;
  6268. _this._offsetY = -(evt.clientY - previousPosition.y);
  6269. };
  6270. this._onLostFocus = function () {
  6271. _this._offsetX = null;
  6272. _this._offsetY = null;
  6273. };
  6274. }
  6275. canvas.addEventListener("pointerdown", this._onPointerDown);
  6276. canvas.addEventListener("pointerup", this._onPointerUp);
  6277. canvas.addEventListener("pointerout", this._onPointerUp);
  6278. canvas.addEventListener("pointermove", this._onPointerMove);
  6279. BABYLON.Tools.RegisterTopRootEvents([
  6280. { name: "blur", handler: this._onLostFocus }
  6281. ]);
  6282. };
  6283. TouchCamera.prototype.detachControl = function (canvas) {
  6284. if (this._attachedCanvas != canvas) {
  6285. return;
  6286. }
  6287. canvas.removeEventListener("pointerdown", this._onPointerDown);
  6288. canvas.removeEventListener("pointerup", this._onPointerUp);
  6289. canvas.removeEventListener("pointerout", this._onPointerUp);
  6290. canvas.removeEventListener("pointermove", this._onPointerMove);
  6291. BABYLON.Tools.UnregisterTopRootEvents([
  6292. { name: "blur", handler: this._onLostFocus }
  6293. ]);
  6294. this._attachedCanvas = null;
  6295. };
  6296. TouchCamera.prototype._checkInputs = function () {
  6297. if (!this._offsetX) {
  6298. return;
  6299. }
  6300. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  6301. if (this._pointerPressed.length > 1) {
  6302. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  6303. } else {
  6304. var speed = this._computeLocalCameraSpeed();
  6305. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  6306. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  6307. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  6308. }
  6309. };
  6310. return TouchCamera;
  6311. })(BABYLON.FreeCamera);
  6312. BABYLON.TouchCamera = TouchCamera;
  6313. })(BABYLON || (BABYLON = {}));
  6314. //# sourceMappingURL=babylon.touchCamera.js.map
  6315. var BABYLON;
  6316. (function (BABYLON) {
  6317. // We're mainly based on the logic defined into the FreeCamera code
  6318. var DeviceOrientationCamera = (function (_super) {
  6319. __extends(DeviceOrientationCamera, _super);
  6320. function DeviceOrientationCamera(name, position, scene) {
  6321. var _this = this;
  6322. _super.call(this, name, position, scene);
  6323. this._offsetX = null;
  6324. this._offsetY = null;
  6325. this._orientationGamma = 0;
  6326. this._orientationBeta = 0;
  6327. this._initialOrientationGamma = 0;
  6328. this._initialOrientationBeta = 0;
  6329. this.angularSensibility = 10000.0;
  6330. this.moveSensibility = 50.0;
  6331. window.addEventListener("resize", function () {
  6332. _this._initialOrientationGamma = null;
  6333. }, false);
  6334. }
  6335. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  6336. var _this = this;
  6337. if (this._attachedCanvas) {
  6338. return;
  6339. }
  6340. this._attachedCanvas = canvas;
  6341. if (!this._orientationChanged) {
  6342. this._orientationChanged = function (evt) {
  6343. if (!_this._initialOrientationGamma) {
  6344. _this._initialOrientationGamma = evt.gamma;
  6345. _this._initialOrientationBeta = evt.beta;
  6346. }
  6347. _this._orientationGamma = evt.gamma;
  6348. _this._orientationBeta = evt.beta;
  6349. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  6350. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  6351. };
  6352. }
  6353. window.addEventListener("deviceorientation", this._orientationChanged);
  6354. };
  6355. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  6356. if (this._attachedCanvas != canvas) {
  6357. return;
  6358. }
  6359. window.removeEventListener("deviceorientation", this._orientationChanged);
  6360. this._attachedCanvas = null;
  6361. this._orientationGamma = 0;
  6362. this._orientationBeta = 0;
  6363. this._initialOrientationGamma = 0;
  6364. this._initialOrientationBeta = 0;
  6365. };
  6366. DeviceOrientationCamera.prototype._checkInputs = function () {
  6367. if (!this._offsetX) {
  6368. return;
  6369. }
  6370. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  6371. var speed = this._computeLocalCameraSpeed();
  6372. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  6373. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  6374. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  6375. };
  6376. return DeviceOrientationCamera;
  6377. })(BABYLON.FreeCamera);
  6378. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  6379. })(BABYLON || (BABYLON = {}));
  6380. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  6381. var BABYLON;
  6382. (function (BABYLON) {
  6383. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  6384. var ArcRotateCamera = (function (_super) {
  6385. __extends(ArcRotateCamera, _super);
  6386. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  6387. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  6388. this.alpha = alpha;
  6389. this.beta = beta;
  6390. this.radius = radius;
  6391. this.target = target;
  6392. this.inertialAlphaOffset = 0;
  6393. this.inertialBetaOffset = 0;
  6394. this.inertialRadiusOffset = 0;
  6395. this.lowerAlphaLimit = null;
  6396. this.upperAlphaLimit = null;
  6397. this.lowerBetaLimit = 0.01;
  6398. this.upperBetaLimit = Math.PI;
  6399. this.lowerRadiusLimit = null;
  6400. this.upperRadiusLimit = null;
  6401. this.angularSensibility = 1000.0;
  6402. this.wheelPrecision = 3.0;
  6403. this.keysUp = [38];
  6404. this.keysDown = [40];
  6405. this.keysLeft = [37];
  6406. this.keysRight = [39];
  6407. this.zoomOnFactor = 1;
  6408. this.targetScreenOffset = BABYLON.Vector2.Zero();
  6409. this._keys = [];
  6410. this._viewMatrix = new BABYLON.Matrix();
  6411. this.checkCollisions = false;
  6412. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  6413. this._collider = new BABYLON.Collider();
  6414. this._previousPosition = BABYLON.Vector3.Zero();
  6415. this._collisionVelocity = BABYLON.Vector3.Zero();
  6416. this._newPosition = BABYLON.Vector3.Zero();
  6417. // Pinch
  6418. // value for pinch step scaling
  6419. // set to 20 by default
  6420. this.pinchPrecision = 20;
  6421. this.getViewMatrix();
  6422. }
  6423. ArcRotateCamera.prototype._getTargetPosition = function () {
  6424. return this.target.position || this.target;
  6425. };
  6426. // Cache
  6427. ArcRotateCamera.prototype._initCache = function () {
  6428. _super.prototype._initCache.call(this);
  6429. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6430. this._cache.alpha = undefined;
  6431. this._cache.beta = undefined;
  6432. this._cache.radius = undefined;
  6433. this._cache.targetScreenOffset = undefined;
  6434. };
  6435. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  6436. if (!ignoreParentClass) {
  6437. _super.prototype._updateCache.call(this);
  6438. }
  6439. this._cache.target.copyFrom(this._getTargetPosition());
  6440. this._cache.alpha = this.alpha;
  6441. this._cache.beta = this.beta;
  6442. this._cache.radius = this.radius;
  6443. this._cache.targetScreenOffset = this.targetScreenOffset.clone();
  6444. };
  6445. // Synchronized
  6446. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  6447. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  6448. return false;
  6449. 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);
  6450. };
  6451. // Methods
  6452. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault) {
  6453. var _this = this;
  6454. var previousPosition;
  6455. var pointerId;
  6456. // to know if pinch started
  6457. var pinchStarted = false;
  6458. // two pinch point on X
  6459. // that will use for find if user action is pinch open or pinch close
  6460. var pinchPointX1, pinchPointX2;
  6461. if (this._attachedElement) {
  6462. return;
  6463. }
  6464. this._attachedElement = element;
  6465. var engine = this.getEngine();
  6466. if (this._onPointerDown === undefined) {
  6467. this._onPointerDown = function (evt) {
  6468. if (pointerId) {
  6469. return;
  6470. }
  6471. pointerId = evt.pointerId;
  6472. previousPosition = {
  6473. x: evt.clientX,
  6474. y: evt.clientY
  6475. };
  6476. if (!noPreventDefault) {
  6477. evt.preventDefault();
  6478. }
  6479. };
  6480. this._onPointerUp = function (evt) {
  6481. previousPosition = null;
  6482. pointerId = null;
  6483. if (!noPreventDefault) {
  6484. evt.preventDefault();
  6485. }
  6486. };
  6487. this._onPointerMove = function (evt) {
  6488. if (!previousPosition) {
  6489. return;
  6490. }
  6491. if (pointerId !== evt.pointerId) {
  6492. return;
  6493. }
  6494. // return pinch is started
  6495. if (pinchStarted) {
  6496. return;
  6497. }
  6498. var offsetX = evt.clientX - previousPosition.x;
  6499. var offsetY = evt.clientY - previousPosition.y;
  6500. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  6501. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  6502. previousPosition = {
  6503. x: evt.clientX,
  6504. y: evt.clientY
  6505. };
  6506. if (!noPreventDefault) {
  6507. evt.preventDefault();
  6508. }
  6509. };
  6510. this._onMouseMove = function (evt) {
  6511. if (!engine.isPointerLock) {
  6512. return;
  6513. }
  6514. // return pinch is started
  6515. if (pinchStarted) {
  6516. return;
  6517. }
  6518. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  6519. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  6520. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  6521. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  6522. if (!noPreventDefault) {
  6523. evt.preventDefault();
  6524. }
  6525. };
  6526. this._wheel = function (event) {
  6527. var delta = 0;
  6528. if (event.wheelDelta) {
  6529. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  6530. } else if (event.detail) {
  6531. delta = -event.detail / _this.wheelPrecision;
  6532. }
  6533. if (delta)
  6534. _this.inertialRadiusOffset += delta;
  6535. if (event.preventDefault) {
  6536. if (!noPreventDefault) {
  6537. event.preventDefault();
  6538. }
  6539. }
  6540. };
  6541. this._onKeyDown = function (evt) {
  6542. 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) {
  6543. var index = _this._keys.indexOf(evt.keyCode);
  6544. if (index === -1) {
  6545. _this._keys.push(evt.keyCode);
  6546. }
  6547. if (evt.preventDefault) {
  6548. if (!noPreventDefault) {
  6549. evt.preventDefault();
  6550. }
  6551. }
  6552. }
  6553. };
  6554. this._onKeyUp = function (evt) {
  6555. 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) {
  6556. var index = _this._keys.indexOf(evt.keyCode);
  6557. if (index >= 0) {
  6558. _this._keys.splice(index, 1);
  6559. }
  6560. if (evt.preventDefault) {
  6561. if (!noPreventDefault) {
  6562. evt.preventDefault();
  6563. }
  6564. }
  6565. }
  6566. };
  6567. this._onLostFocus = function () {
  6568. _this._keys = [];
  6569. pointerId = null;
  6570. };
  6571. this._onGestureStart = function (e) {
  6572. if (window.MSGesture === undefined) {
  6573. return;
  6574. }
  6575. if (!_this._MSGestureHandler) {
  6576. _this._MSGestureHandler = new MSGesture();
  6577. _this._MSGestureHandler.target = element;
  6578. }
  6579. _this._MSGestureHandler.addPointer(e.pointerId);
  6580. };
  6581. this._onGesture = function (e) {
  6582. _this.radius *= e.scale;
  6583. if (e.preventDefault) {
  6584. if (!noPreventDefault) {
  6585. e.stopPropagation();
  6586. e.preventDefault();
  6587. }
  6588. }
  6589. };
  6590. this._reset = function () {
  6591. _this._keys = [];
  6592. _this.inertialAlphaOffset = 0;
  6593. _this.inertialBetaOffset = 0;
  6594. _this.inertialRadiusOffset = 0;
  6595. previousPosition = null;
  6596. pointerId = null;
  6597. };
  6598. this._touchStart = function (event) {
  6599. if (event.touches.length == 2) {
  6600. //-- start pinch if two fingers on the screen
  6601. pinchStarted = true;
  6602. _this._pinchStart(event);
  6603. }
  6604. };
  6605. this._touchMove = function (event) {
  6606. if (pinchStarted) {
  6607. //-- make scaling
  6608. _this._pinchMove(event);
  6609. }
  6610. };
  6611. this._touchEnd = function (event) {
  6612. if (pinchStarted) {
  6613. //-- end of pinch
  6614. _this._pinchEnd(event);
  6615. }
  6616. };
  6617. this._pinchStart = function (event) {
  6618. // save origin touch point
  6619. pinchPointX1 = event.touches[0].clientX;
  6620. pinchPointX2 = event.touches[1].clientX;
  6621. // block the camera
  6622. // if not it rotate around target during pinch
  6623. pinchStarted = true;
  6624. };
  6625. this._pinchMove = function (event) {
  6626. // variable for new camera's radius
  6627. var delta = 0;
  6628. // variables to know if pinch open or pinch close
  6629. var direction = 1;
  6630. var distanceXOrigine, distanceXNow;
  6631. if (event.touches.length != 2)
  6632. return;
  6633. // calculate absolute distances of the two fingers
  6634. distanceXOrigine = Math.abs(pinchPointX1 - pinchPointX2);
  6635. distanceXNow = Math.abs(event.touches[0].clientX - event.touches[1].clientX);
  6636. // if distanceXNow < distanceXOrigine -> pinch close so direction = -1
  6637. if (distanceXNow < distanceXOrigine) {
  6638. direction = -1;
  6639. }
  6640. // calculate new radius
  6641. delta = (_this.pinchPrecision / (_this.wheelPrecision * 40)) * direction;
  6642. // set new radius
  6643. _this.inertialRadiusOffset += delta;
  6644. // save origin touch point
  6645. pinchPointX1 = event.touches[0].clientX;
  6646. pinchPointX2 = event.touches[1].clientX;
  6647. };
  6648. this._pinchEnd = function (event) {
  6649. // cancel pinch and deblock camera rotation
  6650. pinchStarted = false;
  6651. };
  6652. }
  6653. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  6654. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  6655. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  6656. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  6657. element.addEventListener("mousemove", this._onMouseMove, false);
  6658. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  6659. element.addEventListener("MSGestureChange", this._onGesture, false);
  6660. element.addEventListener('mousewheel', this._wheel, false);
  6661. element.addEventListener('DOMMouseScroll', this._wheel, false);
  6662. // pinch
  6663. element.addEventListener('touchstart', this._touchStart, false);
  6664. element.addEventListener('touchmove', this._touchMove, false);
  6665. element.addEventListener('touchend', this._touchEnd, false);
  6666. BABYLON.Tools.RegisterTopRootEvents([
  6667. { name: "keydown", handler: this._onKeyDown },
  6668. { name: "keyup", handler: this._onKeyUp },
  6669. { name: "blur", handler: this._onLostFocus }
  6670. ]);
  6671. };
  6672. ArcRotateCamera.prototype.detachControl = function (element) {
  6673. if (this._attachedElement != element) {
  6674. return;
  6675. }
  6676. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  6677. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  6678. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  6679. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  6680. element.removeEventListener("mousemove", this._onMouseMove);
  6681. element.removeEventListener("MSPointerDown", this._onGestureStart);
  6682. element.removeEventListener("MSGestureChange", this._onGesture);
  6683. element.removeEventListener('mousewheel', this._wheel);
  6684. element.removeEventListener('DOMMouseScroll', this._wheel);
  6685. // pinch
  6686. element.removeEventListener('touchstart', this._touchStart);
  6687. element.removeEventListener('touchmove', this._touchMove);
  6688. element.removeEventListener('touchend', this._touchEnd);
  6689. BABYLON.Tools.UnregisterTopRootEvents([
  6690. { name: "keydown", handler: this._onKeyDown },
  6691. { name: "keyup", handler: this._onKeyUp },
  6692. { name: "blur", handler: this._onLostFocus }
  6693. ]);
  6694. this._MSGestureHandler = null;
  6695. this._attachedElement = null;
  6696. if (this._reset) {
  6697. this._reset();
  6698. }
  6699. };
  6700. ArcRotateCamera.prototype._update = function () {
  6701. for (var index = 0; index < this._keys.length; index++) {
  6702. var keyCode = this._keys[index];
  6703. if (this.keysLeft.indexOf(keyCode) !== -1) {
  6704. this.inertialAlphaOffset -= 0.01;
  6705. } else if (this.keysUp.indexOf(keyCode) !== -1) {
  6706. this.inertialBetaOffset -= 0.01;
  6707. } else if (this.keysRight.indexOf(keyCode) !== -1) {
  6708. this.inertialAlphaOffset += 0.01;
  6709. } else if (this.keysDown.indexOf(keyCode) !== -1) {
  6710. this.inertialBetaOffset += 0.01;
  6711. }
  6712. }
  6713. // Inertia
  6714. if (this.inertialAlphaOffset != 0 || this.inertialBetaOffset != 0 || this.inertialRadiusOffset != 0) {
  6715. this.alpha += this.inertialAlphaOffset;
  6716. this.beta += this.inertialBetaOffset;
  6717. this.radius -= this.inertialRadiusOffset;
  6718. this.inertialAlphaOffset *= this.inertia;
  6719. this.inertialBetaOffset *= this.inertia;
  6720. this.inertialRadiusOffset *= this.inertia;
  6721. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  6722. this.inertialAlphaOffset = 0;
  6723. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  6724. this.inertialBetaOffset = 0;
  6725. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  6726. this.inertialRadiusOffset = 0;
  6727. }
  6728. // Limits
  6729. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  6730. this.alpha = this.lowerAlphaLimit;
  6731. }
  6732. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  6733. this.alpha = this.upperAlphaLimit;
  6734. }
  6735. if (this.lowerBetaLimit && this.beta < this.lowerBetaLimit) {
  6736. this.beta = this.lowerBetaLimit;
  6737. }
  6738. if (this.upperBetaLimit && this.beta > this.upperBetaLimit) {
  6739. this.beta = this.upperBetaLimit;
  6740. }
  6741. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  6742. this.radius = this.lowerRadiusLimit;
  6743. }
  6744. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  6745. this.radius = this.upperRadiusLimit;
  6746. }
  6747. };
  6748. ArcRotateCamera.prototype.setPosition = function (position) {
  6749. var radiusv3 = position.subtract(this._getTargetPosition());
  6750. this.radius = radiusv3.length();
  6751. // Alpha
  6752. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  6753. if (radiusv3.z < 0) {
  6754. this.alpha = 2 * Math.PI - this.alpha;
  6755. }
  6756. // Beta
  6757. this.beta = Math.acos(radiusv3.y / this.radius);
  6758. };
  6759. ArcRotateCamera.prototype._getViewMatrix = function () {
  6760. // Compute
  6761. var cosa = Math.cos(this.alpha);
  6762. var sina = Math.sin(this.alpha);
  6763. var cosb = Math.cos(this.beta);
  6764. var sinb = Math.sin(this.beta);
  6765. var target = this._getTargetPosition();
  6766. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this.position);
  6767. if (this.checkCollisions) {
  6768. this._collider.radius = this.collisionRadius;
  6769. this.position.subtractToRef(this._previousPosition, this._collisionVelocity);
  6770. this.getScene()._getNewPosition(this._previousPosition, this._collisionVelocity, this._collider, 3, this._newPosition);
  6771. if (!this._newPosition.equalsWithEpsilon(this.position)) {
  6772. this.position.copyFrom(this._previousPosition);
  6773. this.alpha = this._previousAlpha;
  6774. this.beta = this._previousBeta;
  6775. this.radius = this._previousRadius;
  6776. if (this.onCollide) {
  6777. this.onCollide(this._collider.collidedMesh);
  6778. }
  6779. }
  6780. }
  6781. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._viewMatrix);
  6782. this._previousAlpha = this.alpha;
  6783. this._previousBeta = this.beta;
  6784. this._previousRadius = this.radius;
  6785. this._previousPosition.copyFrom(this.position);
  6786. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  6787. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  6788. return this._viewMatrix;
  6789. };
  6790. ArcRotateCamera.prototype.zoomOn = function (meshes) {
  6791. meshes = meshes || this.getScene().meshes;
  6792. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  6793. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  6794. this.radius = distance * this.zoomOnFactor;
  6795. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance });
  6796. };
  6797. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance) {
  6798. var meshesOrMinMaxVector;
  6799. var distance;
  6800. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  6801. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  6802. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  6803. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  6804. } else {
  6805. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  6806. distance = meshesOrMinMaxVectorAndDistance.distance;
  6807. }
  6808. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  6809. this.maxZ = distance * 2;
  6810. };
  6811. return ArcRotateCamera;
  6812. })(BABYLON.Camera);
  6813. BABYLON.ArcRotateCamera = ArcRotateCamera;
  6814. })(BABYLON || (BABYLON = {}));
  6815. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  6816. var BABYLON;
  6817. (function (BABYLON) {
  6818. var Scene = (function () {
  6819. // Constructor
  6820. function Scene(engine) {
  6821. // Members
  6822. this.autoClear = true;
  6823. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  6824. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  6825. this.forceWireframe = false;
  6826. this.forcePointsCloud = false;
  6827. this.forceShowBoundingBoxes = false;
  6828. this.animationsEnabled = true;
  6829. this.cameraToUseForPointers = null;
  6830. // Fog
  6831. this.fogEnabled = true;
  6832. this.fogMode = Scene.FOGMODE_NONE;
  6833. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  6834. this.fogDensity = 0.1;
  6835. this.fogStart = 0;
  6836. this.fogEnd = 1000.0;
  6837. // Lights
  6838. this.shadowsEnabled = true;
  6839. this.lightsEnabled = true;
  6840. this.lights = new Array();
  6841. // Cameras
  6842. this.cameras = new Array();
  6843. this.activeCameras = new Array();
  6844. // Meshes
  6845. this.meshes = new Array();
  6846. // Geometries
  6847. this._geometries = new Array();
  6848. this.materials = new Array();
  6849. this.multiMaterials = new Array();
  6850. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  6851. // Textures
  6852. this.texturesEnabled = true;
  6853. this.textures = new Array();
  6854. // Particles
  6855. this.particlesEnabled = true;
  6856. this.particleSystems = new Array();
  6857. // Sprites
  6858. this.spriteManagers = new Array();
  6859. // Layers
  6860. this.layers = new Array();
  6861. // Skeletons
  6862. this.skeletonsEnabled = true;
  6863. this.skeletons = new Array();
  6864. // Lens flares
  6865. this.lensFlaresEnabled = true;
  6866. this.lensFlareSystems = new Array();
  6867. // Collisions
  6868. this.collisionsEnabled = true;
  6869. this.gravity = new BABYLON.Vector3(0, -9.0, 0);
  6870. // Postprocesses
  6871. this.postProcessesEnabled = true;
  6872. // Customs render targets
  6873. this.renderTargetsEnabled = true;
  6874. this.customRenderTargets = new Array();
  6875. // Imported meshes
  6876. this.importedMeshesFiles = new Array();
  6877. this._actionManagers = new Array();
  6878. this._meshesForIntersections = new BABYLON.SmartArray(256);
  6879. // Procedural textures
  6880. this.proceduralTexturesEnabled = true;
  6881. this._proceduralTextures = new Array();
  6882. this.soundTracks = new Array();
  6883. this._totalVertices = 0;
  6884. this._activeVertices = 0;
  6885. this._activeParticles = 0;
  6886. this._lastFrameDuration = 0;
  6887. this._evaluateActiveMeshesDuration = 0;
  6888. this._renderTargetsDuration = 0;
  6889. this._particlesDuration = 0;
  6890. this._renderDuration = 0;
  6891. this._spritesDuration = 0;
  6892. this._animationRatio = 0;
  6893. this._renderId = 0;
  6894. this._executeWhenReadyTimeoutId = -1;
  6895. this._toBeDisposed = new BABYLON.SmartArray(256);
  6896. this._onReadyCallbacks = new Array();
  6897. this._pendingData = [];
  6898. this._onBeforeRenderCallbacks = new Array();
  6899. this._onAfterRenderCallbacks = new Array();
  6900. this._activeMeshes = new BABYLON.SmartArray(256);
  6901. this._processedMaterials = new BABYLON.SmartArray(256);
  6902. this._renderTargets = new BABYLON.SmartArray(256);
  6903. this._activeParticleSystems = new BABYLON.SmartArray(256);
  6904. this._activeSkeletons = new BABYLON.SmartArray(32);
  6905. this._activeBones = 0;
  6906. this._activeAnimatables = new Array();
  6907. this._transformMatrix = BABYLON.Matrix.Zero();
  6908. this._scaledPosition = BABYLON.Vector3.Zero();
  6909. this._scaledVelocity = BABYLON.Vector3.Zero();
  6910. this._engine = engine;
  6911. engine.scenes.push(this);
  6912. this._renderingManager = new BABYLON.RenderingManager(this);
  6913. this.postProcessManager = new BABYLON.PostProcessManager(this);
  6914. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  6915. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  6916. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  6917. this.attachControl();
  6918. this._debugLayer = new BABYLON.DebugLayer(this);
  6919. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  6920. }
  6921. Object.defineProperty(Scene.prototype, "debugLayer", {
  6922. // Properties
  6923. get: function () {
  6924. return this._debugLayer;
  6925. },
  6926. enumerable: true,
  6927. configurable: true
  6928. });
  6929. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  6930. get: function () {
  6931. return this._meshUnderPointer;
  6932. },
  6933. enumerable: true,
  6934. configurable: true
  6935. });
  6936. Object.defineProperty(Scene.prototype, "pointerX", {
  6937. get: function () {
  6938. return this._pointerX;
  6939. },
  6940. enumerable: true,
  6941. configurable: true
  6942. });
  6943. Object.defineProperty(Scene.prototype, "pointerY", {
  6944. get: function () {
  6945. return this._pointerY;
  6946. },
  6947. enumerable: true,
  6948. configurable: true
  6949. });
  6950. Scene.prototype.getCachedMaterial = function () {
  6951. return this._cachedMaterial;
  6952. };
  6953. Scene.prototype.getBoundingBoxRenderer = function () {
  6954. return this._boundingBoxRenderer;
  6955. };
  6956. Scene.prototype.getOutlineRenderer = function () {
  6957. return this._outlineRenderer;
  6958. };
  6959. Scene.prototype.getEngine = function () {
  6960. return this._engine;
  6961. };
  6962. Scene.prototype.getTotalVertices = function () {
  6963. return this._totalVertices;
  6964. };
  6965. Scene.prototype.getActiveVertices = function () {
  6966. return this._activeVertices;
  6967. };
  6968. Scene.prototype.getActiveParticles = function () {
  6969. return this._activeParticles;
  6970. };
  6971. Scene.prototype.getActiveBones = function () {
  6972. return this._activeBones;
  6973. };
  6974. // Stats
  6975. Scene.prototype.getLastFrameDuration = function () {
  6976. return this._lastFrameDuration;
  6977. };
  6978. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  6979. return this._evaluateActiveMeshesDuration;
  6980. };
  6981. Scene.prototype.getActiveMeshes = function () {
  6982. return this._activeMeshes;
  6983. };
  6984. Scene.prototype.getRenderTargetsDuration = function () {
  6985. return this._renderTargetsDuration;
  6986. };
  6987. Scene.prototype.getRenderDuration = function () {
  6988. return this._renderDuration;
  6989. };
  6990. Scene.prototype.getParticlesDuration = function () {
  6991. return this._particlesDuration;
  6992. };
  6993. Scene.prototype.getSpritesDuration = function () {
  6994. return this._spritesDuration;
  6995. };
  6996. Scene.prototype.getAnimationRatio = function () {
  6997. return this._animationRatio;
  6998. };
  6999. Scene.prototype.getRenderId = function () {
  7000. return this._renderId;
  7001. };
  7002. Scene.prototype._updatePointerPosition = function (evt) {
  7003. var canvasRect = this._engine.getRenderingCanvasClientRect();
  7004. this._pointerX = evt.clientX - canvasRect.left;
  7005. this._pointerY = evt.clientY - canvasRect.top;
  7006. if (this.cameraToUseForPointers) {
  7007. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  7008. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  7009. }
  7010. };
  7011. // Pointers handling
  7012. Scene.prototype.attachControl = function () {
  7013. var _this = this;
  7014. this._onPointerMove = function (evt) {
  7015. var canvas = _this._engine.getRenderingCanvas();
  7016. _this._updatePointerPosition(evt);
  7017. var pickResult = _this.pick(_this._pointerX, _this._pointerY, function (mesh) {
  7018. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPointerTriggers;
  7019. }, false, _this.cameraToUseForPointers);
  7020. if (pickResult.hit) {
  7021. _this._meshUnderPointer = pickResult.pickedMesh;
  7022. _this.setPointerOverMesh(pickResult.pickedMesh);
  7023. canvas.style.cursor = "pointer";
  7024. } else {
  7025. _this.setPointerOverMesh(null);
  7026. canvas.style.cursor = "";
  7027. _this._meshUnderPointer = null;
  7028. }
  7029. };
  7030. this._onPointerDown = function (evt) {
  7031. var predicate = null;
  7032. if (!_this.onPointerDown) {
  7033. predicate = function (mesh) {
  7034. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  7035. };
  7036. }
  7037. _this._updatePointerPosition(evt);
  7038. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  7039. if (pickResult.hit) {
  7040. if (pickResult.pickedMesh.actionManager) {
  7041. switch (evt.button) {
  7042. case 0:
  7043. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  7044. break;
  7045. case 1:
  7046. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  7047. break;
  7048. case 2:
  7049. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  7050. break;
  7051. }
  7052. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  7053. }
  7054. }
  7055. if (_this.onPointerDown) {
  7056. _this.onPointerDown(evt, pickResult);
  7057. }
  7058. };
  7059. this._onKeyDown = function (evt) {
  7060. if (_this.actionManager) {
  7061. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  7062. }
  7063. };
  7064. this._onKeyUp = function (evt) {
  7065. if (_this.actionManager) {
  7066. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  7067. }
  7068. };
  7069. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  7070. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  7071. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  7072. window.addEventListener("keydown", this._onKeyDown, false);
  7073. window.addEventListener("keyup", this._onKeyUp, false);
  7074. };
  7075. Scene.prototype.detachControl = function () {
  7076. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  7077. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  7078. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  7079. window.removeEventListener("keydown", this._onKeyDown);
  7080. window.removeEventListener("keyup", this._onKeyUp);
  7081. };
  7082. // Ready
  7083. Scene.prototype.isReady = function () {
  7084. if (this._pendingData.length > 0) {
  7085. return false;
  7086. }
  7087. for (var index = 0; index < this._geometries.length; index++) {
  7088. var geometry = this._geometries[index];
  7089. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  7090. return false;
  7091. }
  7092. }
  7093. for (index = 0; index < this.meshes.length; index++) {
  7094. var mesh = this.meshes[index];
  7095. if (!mesh.isReady()) {
  7096. return false;
  7097. }
  7098. var mat = mesh.material;
  7099. if (mat) {
  7100. if (!mat.isReady(mesh)) {
  7101. return false;
  7102. }
  7103. }
  7104. }
  7105. return true;
  7106. };
  7107. Scene.prototype.resetCachedMaterial = function () {
  7108. this._cachedMaterial = null;
  7109. };
  7110. Scene.prototype.registerBeforeRender = function (func) {
  7111. this._onBeforeRenderCallbacks.push(func);
  7112. };
  7113. Scene.prototype.unregisterBeforeRender = function (func) {
  7114. var index = this._onBeforeRenderCallbacks.indexOf(func);
  7115. if (index > -1) {
  7116. this._onBeforeRenderCallbacks.splice(index, 1);
  7117. }
  7118. };
  7119. Scene.prototype.registerAfterRender = function (func) {
  7120. this._onAfterRenderCallbacks.push(func);
  7121. };
  7122. Scene.prototype.unregisterAfterRender = function (func) {
  7123. var index = this._onAfterRenderCallbacks.indexOf(func);
  7124. if (index > -1) {
  7125. this._onAfterRenderCallbacks.splice(index, 1);
  7126. }
  7127. };
  7128. Scene.prototype._addPendingData = function (data) {
  7129. this._pendingData.push(data);
  7130. };
  7131. Scene.prototype._removePendingData = function (data) {
  7132. var index = this._pendingData.indexOf(data);
  7133. if (index !== -1) {
  7134. this._pendingData.splice(index, 1);
  7135. }
  7136. };
  7137. Scene.prototype.getWaitingItemsCount = function () {
  7138. return this._pendingData.length;
  7139. };
  7140. Scene.prototype.executeWhenReady = function (func) {
  7141. var _this = this;
  7142. this._onReadyCallbacks.push(func);
  7143. if (this._executeWhenReadyTimeoutId !== -1) {
  7144. return;
  7145. }
  7146. this._executeWhenReadyTimeoutId = setTimeout(function () {
  7147. _this._checkIsReady();
  7148. }, 150);
  7149. };
  7150. Scene.prototype._checkIsReady = function () {
  7151. var _this = this;
  7152. if (this.isReady()) {
  7153. this._onReadyCallbacks.forEach(function (func) {
  7154. func();
  7155. });
  7156. this._onReadyCallbacks = [];
  7157. this._executeWhenReadyTimeoutId = -1;
  7158. return;
  7159. }
  7160. this._executeWhenReadyTimeoutId = setTimeout(function () {
  7161. _this._checkIsReady();
  7162. }, 150);
  7163. };
  7164. // Animations
  7165. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  7166. if (speedRatio === undefined) {
  7167. speedRatio = 1.0;
  7168. }
  7169. this.stopAnimation(target);
  7170. if (!animatable) {
  7171. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  7172. }
  7173. // Local animations
  7174. if (target.animations) {
  7175. animatable.appendAnimations(target, target.animations);
  7176. }
  7177. // Children animations
  7178. if (target.getAnimatables) {
  7179. var animatables = target.getAnimatables();
  7180. for (var index = 0; index < animatables.length; index++) {
  7181. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  7182. }
  7183. }
  7184. return animatable;
  7185. };
  7186. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  7187. if (speedRatio === undefined) {
  7188. speedRatio = 1.0;
  7189. }
  7190. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  7191. return animatable;
  7192. };
  7193. Scene.prototype.getAnimatableByTarget = function (target) {
  7194. for (var index = 0; index < this._activeAnimatables.length; index++) {
  7195. if (this._activeAnimatables[index].target === target) {
  7196. return this._activeAnimatables[index];
  7197. }
  7198. }
  7199. return null;
  7200. };
  7201. Scene.prototype.stopAnimation = function (target) {
  7202. var animatable = this.getAnimatableByTarget(target);
  7203. if (animatable) {
  7204. animatable.stop();
  7205. }
  7206. };
  7207. Scene.prototype._animate = function () {
  7208. if (!this.animationsEnabled) {
  7209. return;
  7210. }
  7211. if (!this._animationStartDate) {
  7212. this._animationStartDate = BABYLON.Tools.Now;
  7213. }
  7214. // Getting time
  7215. var now = BABYLON.Tools.Now;
  7216. var delay = now - this._animationStartDate;
  7217. for (var index = 0; index < this._activeAnimatables.length; index++) {
  7218. if (!this._activeAnimatables[index]._animate(delay)) {
  7219. this._activeAnimatables.splice(index, 1);
  7220. index--;
  7221. }
  7222. }
  7223. };
  7224. // Matrix
  7225. Scene.prototype.getViewMatrix = function () {
  7226. return this._viewMatrix;
  7227. };
  7228. Scene.prototype.getProjectionMatrix = function () {
  7229. return this._projectionMatrix;
  7230. };
  7231. Scene.prototype.getTransformMatrix = function () {
  7232. return this._transformMatrix;
  7233. };
  7234. Scene.prototype.setTransformMatrix = function (view, projection) {
  7235. this._viewMatrix = view;
  7236. this._projectionMatrix = projection;
  7237. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  7238. };
  7239. // Methods
  7240. Scene.prototype.setActiveCameraByID = function (id) {
  7241. var camera = this.getCameraByID(id);
  7242. if (camera) {
  7243. this.activeCamera = camera;
  7244. return camera;
  7245. }
  7246. return null;
  7247. };
  7248. Scene.prototype.setActiveCameraByName = function (name) {
  7249. var camera = this.getCameraByName(name);
  7250. if (camera) {
  7251. this.activeCamera = camera;
  7252. return camera;
  7253. }
  7254. return null;
  7255. };
  7256. Scene.prototype.getMaterialByID = function (id) {
  7257. for (var index = 0; index < this.materials.length; index++) {
  7258. if (this.materials[index].id === id) {
  7259. return this.materials[index];
  7260. }
  7261. }
  7262. return null;
  7263. };
  7264. Scene.prototype.getMaterialByName = function (name) {
  7265. for (var index = 0; index < this.materials.length; index++) {
  7266. if (this.materials[index].name === name) {
  7267. return this.materials[index];
  7268. }
  7269. }
  7270. return null;
  7271. };
  7272. Scene.prototype.getCameraByID = function (id) {
  7273. for (var index = 0; index < this.cameras.length; index++) {
  7274. if (this.cameras[index].id === id) {
  7275. return this.cameras[index];
  7276. }
  7277. }
  7278. return null;
  7279. };
  7280. Scene.prototype.getCameraByName = function (name) {
  7281. for (var index = 0; index < this.cameras.length; index++) {
  7282. if (this.cameras[index].name === name) {
  7283. return this.cameras[index];
  7284. }
  7285. }
  7286. return null;
  7287. };
  7288. Scene.prototype.getLightByName = function (name) {
  7289. for (var index = 0; index < this.lights.length; index++) {
  7290. if (this.lights[index].name === name) {
  7291. return this.lights[index];
  7292. }
  7293. }
  7294. return null;
  7295. };
  7296. Scene.prototype.getLightByID = function (id) {
  7297. for (var index = 0; index < this.lights.length; index++) {
  7298. if (this.lights[index].id === id) {
  7299. return this.lights[index];
  7300. }
  7301. }
  7302. return null;
  7303. };
  7304. Scene.prototype.getGeometryByID = function (id) {
  7305. for (var index = 0; index < this._geometries.length; index++) {
  7306. if (this._geometries[index].id === id) {
  7307. return this._geometries[index];
  7308. }
  7309. }
  7310. return null;
  7311. };
  7312. Scene.prototype.pushGeometry = function (geometry, force) {
  7313. if (!force && this.getGeometryByID(geometry.id)) {
  7314. return false;
  7315. }
  7316. this._geometries.push(geometry);
  7317. return true;
  7318. };
  7319. Scene.prototype.getGeometries = function () {
  7320. return this._geometries;
  7321. };
  7322. Scene.prototype.getMeshByID = function (id) {
  7323. for (var index = 0; index < this.meshes.length; index++) {
  7324. if (this.meshes[index].id === id) {
  7325. return this.meshes[index];
  7326. }
  7327. }
  7328. return null;
  7329. };
  7330. Scene.prototype.getLastMeshByID = function (id) {
  7331. for (var index = this.meshes.length - 1; index >= 0; index--) {
  7332. if (this.meshes[index].id === id) {
  7333. return this.meshes[index];
  7334. }
  7335. }
  7336. return null;
  7337. };
  7338. Scene.prototype.getLastEntryByID = function (id) {
  7339. for (var index = this.meshes.length - 1; index >= 0; index--) {
  7340. if (this.meshes[index].id === id) {
  7341. return this.meshes[index];
  7342. }
  7343. }
  7344. for (index = this.cameras.length - 1; index >= 0; index--) {
  7345. if (this.cameras[index].id === id) {
  7346. return this.cameras[index];
  7347. }
  7348. }
  7349. for (index = this.lights.length - 1; index >= 0; index--) {
  7350. if (this.lights[index].id === id) {
  7351. return this.lights[index];
  7352. }
  7353. }
  7354. return null;
  7355. };
  7356. Scene.prototype.getMeshByName = function (name) {
  7357. for (var index = 0; index < this.meshes.length; index++) {
  7358. if (this.meshes[index].name === name) {
  7359. return this.meshes[index];
  7360. }
  7361. }
  7362. return null;
  7363. };
  7364. Scene.prototype.getLastSkeletonByID = function (id) {
  7365. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  7366. if (this.skeletons[index].id === id) {
  7367. return this.skeletons[index];
  7368. }
  7369. }
  7370. return null;
  7371. };
  7372. Scene.prototype.getSkeletonById = function (id) {
  7373. for (var index = 0; index < this.skeletons.length; index++) {
  7374. if (this.skeletons[index].id === id) {
  7375. return this.skeletons[index];
  7376. }
  7377. }
  7378. return null;
  7379. };
  7380. Scene.prototype.getSkeletonByName = function (name) {
  7381. for (var index = 0; index < this.skeletons.length; index++) {
  7382. if (this.skeletons[index].name === name) {
  7383. return this.skeletons[index];
  7384. }
  7385. }
  7386. return null;
  7387. };
  7388. Scene.prototype.isActiveMesh = function (mesh) {
  7389. return (this._activeMeshes.indexOf(mesh) !== -1);
  7390. };
  7391. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  7392. if (mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  7393. var material = subMesh.getMaterial();
  7394. if (mesh.showSubMeshesBoundingBox) {
  7395. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  7396. }
  7397. if (material) {
  7398. // Render targets
  7399. if (material.getRenderTargetTextures) {
  7400. if (this._processedMaterials.indexOf(material) === -1) {
  7401. this._processedMaterials.push(material);
  7402. this._renderTargets.concat(material.getRenderTargetTextures());
  7403. }
  7404. }
  7405. // Dispatch
  7406. this._activeVertices += subMesh.indexCount;
  7407. this._renderingManager.dispatch(subMesh);
  7408. }
  7409. }
  7410. };
  7411. Scene.prototype._evaluateActiveMeshes = function () {
  7412. this._activeMeshes.reset();
  7413. this._renderingManager.reset();
  7414. this._processedMaterials.reset();
  7415. this._activeParticleSystems.reset();
  7416. this._activeSkeletons.reset();
  7417. this._boundingBoxRenderer.reset();
  7418. if (!this._frustumPlanes) {
  7419. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  7420. } else {
  7421. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  7422. }
  7423. // Meshes
  7424. var meshes;
  7425. var len;
  7426. if (this._selectionOctree) {
  7427. var selection = this._selectionOctree.select(this._frustumPlanes);
  7428. meshes = selection.data;
  7429. len = selection.length;
  7430. } else {
  7431. len = this.meshes.length;
  7432. meshes = this.meshes;
  7433. }
  7434. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  7435. var mesh = meshes[meshIndex];
  7436. if (mesh.isBlocked) {
  7437. continue;
  7438. }
  7439. this._totalVertices += mesh.getTotalVertices();
  7440. if (!mesh.isReady()) {
  7441. continue;
  7442. }
  7443. mesh.computeWorldMatrix();
  7444. // Intersections
  7445. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  7446. this._meshesForIntersections.pushNoDuplicate(mesh);
  7447. }
  7448. // Switch to current LOD
  7449. var meshLOD = mesh.getLOD(this.activeCamera);
  7450. if (!meshLOD) {
  7451. continue;
  7452. }
  7453. mesh._preActivate();
  7454. if (mesh.isEnabled() && mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  7455. this._activeMeshes.push(mesh);
  7456. mesh._activate(this._renderId);
  7457. this._activeMesh(meshLOD);
  7458. }
  7459. }
  7460. // Particle systems
  7461. var beforeParticlesDate = BABYLON.Tools.Now;
  7462. if (this.particlesEnabled) {
  7463. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  7464. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  7465. var particleSystem = this.particleSystems[particleIndex];
  7466. if (!particleSystem.isStarted()) {
  7467. continue;
  7468. }
  7469. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  7470. this._activeParticleSystems.push(particleSystem);
  7471. particleSystem.animate();
  7472. }
  7473. }
  7474. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  7475. }
  7476. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  7477. };
  7478. Scene.prototype._activeMesh = function (mesh) {
  7479. if (mesh.skeleton && this.skeletonsEnabled) {
  7480. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  7481. }
  7482. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  7483. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  7484. }
  7485. if (mesh && mesh.subMeshes) {
  7486. // Submeshes Octrees
  7487. var len;
  7488. var subMeshes;
  7489. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  7490. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  7491. len = intersections.length;
  7492. subMeshes = intersections.data;
  7493. } else {
  7494. subMeshes = mesh.subMeshes;
  7495. len = subMeshes.length;
  7496. }
  7497. for (var subIndex = 0; subIndex < len; subIndex++) {
  7498. var subMesh = subMeshes[subIndex];
  7499. this._evaluateSubMesh(subMesh, mesh);
  7500. }
  7501. }
  7502. };
  7503. Scene.prototype.updateTransformMatrix = function (force) {
  7504. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  7505. };
  7506. Scene.prototype._renderForCamera = function (camera) {
  7507. var engine = this._engine;
  7508. this.activeCamera = camera;
  7509. if (!this.activeCamera)
  7510. throw new Error("Active camera not set");
  7511. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  7512. // Viewport
  7513. engine.setViewport(this.activeCamera.viewport);
  7514. // Camera
  7515. this._renderId++;
  7516. this.updateTransformMatrix();
  7517. if (this.beforeCameraRender) {
  7518. this.beforeCameraRender(this.activeCamera);
  7519. }
  7520. // Meshes
  7521. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  7522. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  7523. this._evaluateActiveMeshes();
  7524. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  7525. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  7526. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  7527. var skeleton = this._activeSkeletons.data[skeletonIndex];
  7528. skeleton.prepare();
  7529. this._activeBones += skeleton.bones.length;
  7530. }
  7531. // Render targets
  7532. var beforeRenderTargetDate = BABYLON.Tools.Now;
  7533. if (this.renderTargetsEnabled) {
  7534. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  7535. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  7536. var renderTarget = this._renderTargets.data[renderIndex];
  7537. if (renderTarget._shouldRender()) {
  7538. this._renderId++;
  7539. renderTarget.render();
  7540. }
  7541. }
  7542. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  7543. this._renderId++;
  7544. }
  7545. if (this._renderTargets.length > 0) {
  7546. engine.restoreDefaultFramebuffer();
  7547. }
  7548. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  7549. // Prepare Frame
  7550. this.postProcessManager._prepareFrame();
  7551. var beforeRenderDate = BABYLON.Tools.Now;
  7552. // Backgrounds
  7553. if (this.layers.length) {
  7554. engine.setDepthBuffer(false);
  7555. var layerIndex;
  7556. var layer;
  7557. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  7558. layer = this.layers[layerIndex];
  7559. if (layer.isBackground) {
  7560. layer.render();
  7561. }
  7562. }
  7563. engine.setDepthBuffer(true);
  7564. }
  7565. // Render
  7566. BABYLON.Tools.StartPerformanceCounter("Main render");
  7567. this._renderingManager.render(null, null, true, true);
  7568. BABYLON.Tools.EndPerformanceCounter("Main render");
  7569. // Bounding boxes
  7570. this._boundingBoxRenderer.render();
  7571. // Lens flares
  7572. if (this.lensFlaresEnabled) {
  7573. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  7574. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  7575. this.lensFlareSystems[lensFlareSystemIndex].render();
  7576. }
  7577. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  7578. }
  7579. // Foregrounds
  7580. if (this.layers.length) {
  7581. engine.setDepthBuffer(false);
  7582. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  7583. layer = this.layers[layerIndex];
  7584. if (!layer.isBackground) {
  7585. layer.render();
  7586. }
  7587. }
  7588. engine.setDepthBuffer(true);
  7589. }
  7590. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  7591. // Finalize frame
  7592. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  7593. // Update camera
  7594. this.activeCamera._updateFromScene();
  7595. // Reset some special arrays
  7596. this._renderTargets.reset();
  7597. if (this.afterCameraRender) {
  7598. this.afterCameraRender(this.activeCamera);
  7599. }
  7600. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  7601. };
  7602. Scene.prototype._processSubCameras = function (camera) {
  7603. if (camera.subCameras.length === 0) {
  7604. this._renderForCamera(camera);
  7605. return;
  7606. }
  7607. for (var index = 0; index < camera.subCameras.length; index++) {
  7608. this._renderForCamera(camera.subCameras[index]);
  7609. }
  7610. this.activeCamera = camera;
  7611. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  7612. // Update camera
  7613. this.activeCamera._updateFromScene();
  7614. };
  7615. Scene.prototype._checkIntersections = function () {
  7616. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  7617. var sourceMesh = this._meshesForIntersections.data[index];
  7618. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  7619. var action = sourceMesh.actionManager.actions[actionIndex];
  7620. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  7621. var otherMesh = action.getTriggerParameter();
  7622. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, false);
  7623. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  7624. if (areIntersecting && currentIntersectionInProgress === -1 && action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  7625. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  7626. sourceMesh._intersectionsInProgress.push(otherMesh);
  7627. } else if (!areIntersecting && currentIntersectionInProgress > -1 && action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  7628. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  7629. var indexOfOther = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  7630. if (indexOfOther > -1) {
  7631. sourceMesh._intersectionsInProgress.splice(indexOfOther, 1);
  7632. }
  7633. }
  7634. }
  7635. }
  7636. }
  7637. };
  7638. Scene.prototype.render = function () {
  7639. var startDate = BABYLON.Tools.Now;
  7640. this._particlesDuration = 0;
  7641. this._spritesDuration = 0;
  7642. this._activeParticles = 0;
  7643. this._renderDuration = 0;
  7644. this._renderTargetsDuration = 0;
  7645. this._evaluateActiveMeshesDuration = 0;
  7646. this._totalVertices = 0;
  7647. this._activeVertices = 0;
  7648. this._activeBones = 0;
  7649. this.getEngine().resetDrawCalls();
  7650. this._meshesForIntersections.reset();
  7651. this.resetCachedMaterial();
  7652. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  7653. // Actions
  7654. if (this.actionManager) {
  7655. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  7656. }
  7657. // Before render
  7658. if (this.beforeRender) {
  7659. this.beforeRender();
  7660. }
  7661. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  7662. this._onBeforeRenderCallbacks[callbackIndex]();
  7663. }
  7664. // Animations
  7665. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  7666. this._animationRatio = deltaTime * (60.0 / 1000.0);
  7667. this._animate();
  7668. // Physics
  7669. if (this._physicsEngine) {
  7670. BABYLON.Tools.StartPerformanceCounter("Physics");
  7671. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  7672. BABYLON.Tools.EndPerformanceCounter("Physics");
  7673. }
  7674. // Customs render targets
  7675. var beforeRenderTargetDate = BABYLON.Tools.Now;
  7676. var engine = this.getEngine();
  7677. if (this.renderTargetsEnabled) {
  7678. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  7679. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  7680. var renderTarget = this.customRenderTargets[customIndex];
  7681. if (renderTarget._shouldRender()) {
  7682. this._renderId++;
  7683. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  7684. if (!this.activeCamera)
  7685. throw new Error("Active camera not set");
  7686. // Viewport
  7687. engine.setViewport(this.activeCamera.viewport);
  7688. // Camera
  7689. this.updateTransformMatrix();
  7690. renderTarget.render();
  7691. }
  7692. }
  7693. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  7694. this._renderId++;
  7695. }
  7696. if (this.customRenderTargets.length > 0) {
  7697. engine.restoreDefaultFramebuffer();
  7698. }
  7699. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  7700. // Procedural textures
  7701. if (this.proceduralTexturesEnabled) {
  7702. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  7703. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  7704. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  7705. if (proceduralTexture._shouldRender()) {
  7706. proceduralTexture.render();
  7707. }
  7708. }
  7709. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  7710. }
  7711. // Clear
  7712. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  7713. // Shadows
  7714. if (this.shadowsEnabled) {
  7715. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  7716. var light = this.lights[lightIndex];
  7717. var shadowGenerator = light.getShadowGenerator();
  7718. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  7719. this._renderTargets.push(shadowGenerator.getShadowMap());
  7720. }
  7721. }
  7722. }
  7723. // RenderPipeline
  7724. this.postProcessRenderPipelineManager.update();
  7725. // Multi-cameras?
  7726. if (this.activeCameras.length > 0) {
  7727. var currentRenderId = this._renderId;
  7728. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  7729. this._renderId = currentRenderId;
  7730. this._processSubCameras(this.activeCameras[cameraIndex]);
  7731. }
  7732. } else {
  7733. if (!this.activeCamera) {
  7734. throw new Error("No camera defined");
  7735. }
  7736. this._processSubCameras(this.activeCamera);
  7737. }
  7738. // Intersection checks
  7739. this._checkIntersections();
  7740. // Update the audio listener attached to the camera
  7741. this._updateAudioParameters();
  7742. // After render
  7743. if (this.afterRender) {
  7744. this.afterRender();
  7745. }
  7746. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  7747. this._onAfterRenderCallbacks[callbackIndex]();
  7748. }
  7749. for (var index = 0; index < this._toBeDisposed.length; index++) {
  7750. this._toBeDisposed.data[index].dispose();
  7751. this._toBeDisposed[index] = null;
  7752. }
  7753. this._toBeDisposed.reset();
  7754. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  7755. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  7756. };
  7757. Scene.prototype._updateAudioParameters = function () {
  7758. var listeningCamera;
  7759. var audioEngine = this._engine.getAudioEngine();
  7760. if (this.activeCameras.length > 0) {
  7761. listeningCamera = this.activeCameras[0];
  7762. } else {
  7763. listeningCamera = this.activeCamera;
  7764. }
  7765. if (listeningCamera && audioEngine.canUseWebAudio) {
  7766. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  7767. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  7768. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  7769. cameraDirection.normalize();
  7770. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  7771. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  7772. var sound = this.mainSoundTrack.soundCollection[i];
  7773. if (sound.useBabylonJSAttenuation) {
  7774. sound.updateDistanceFromListener();
  7775. }
  7776. }
  7777. for (var i = 0; i < this.soundTracks.length; i++) {
  7778. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  7779. var sound = this.soundTracks[i].soundCollection[j];
  7780. if (sound.useBabylonJSAttenuation) {
  7781. sound.updateDistanceFromListener();
  7782. }
  7783. }
  7784. }
  7785. }
  7786. };
  7787. Scene.prototype.dispose = function () {
  7788. this.beforeRender = null;
  7789. this.afterRender = null;
  7790. this.skeletons = [];
  7791. this._boundingBoxRenderer.dispose();
  7792. // Debug layer
  7793. this.debugLayer.hide();
  7794. // Events
  7795. if (this.onDispose) {
  7796. this.onDispose();
  7797. }
  7798. this._onBeforeRenderCallbacks = [];
  7799. this._onAfterRenderCallbacks = [];
  7800. this.detachControl();
  7801. // Detach cameras
  7802. var canvas = this._engine.getRenderingCanvas();
  7803. var index;
  7804. for (index = 0; index < this.cameras.length; index++) {
  7805. this.cameras[index].detachControl(canvas);
  7806. }
  7807. while (this.lights.length) {
  7808. this.lights[0].dispose();
  7809. }
  7810. while (this.meshes.length) {
  7811. this.meshes[0].dispose(true);
  7812. }
  7813. while (this.cameras.length) {
  7814. this.cameras[0].dispose();
  7815. }
  7816. while (this.materials.length) {
  7817. this.materials[0].dispose();
  7818. }
  7819. while (this.particleSystems.length) {
  7820. this.particleSystems[0].dispose();
  7821. }
  7822. while (this.spriteManagers.length) {
  7823. this.spriteManagers[0].dispose();
  7824. }
  7825. while (this.layers.length) {
  7826. this.layers[0].dispose();
  7827. }
  7828. while (this.textures.length) {
  7829. this.textures[0].dispose();
  7830. }
  7831. // Post-processes
  7832. this.postProcessManager.dispose();
  7833. // Physics
  7834. if (this._physicsEngine) {
  7835. this.disablePhysicsEngine();
  7836. }
  7837. // Remove from engine
  7838. index = this._engine.scenes.indexOf(this);
  7839. if (index > -1) {
  7840. this._engine.scenes.splice(index, 1);
  7841. }
  7842. this._engine.wipeCaches();
  7843. };
  7844. // Collisions
  7845. Scene.prototype._getNewPosition = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  7846. if (typeof excludedMesh === "undefined") { excludedMesh = null; }
  7847. position.divideToRef(collider.radius, this._scaledPosition);
  7848. velocity.divideToRef(collider.radius, this._scaledVelocity);
  7849. collider.retry = 0;
  7850. collider.initialVelocity = this._scaledVelocity;
  7851. collider.initialPosition = this._scaledPosition;
  7852. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, finalPosition, excludedMesh);
  7853. finalPosition.multiplyInPlace(collider.radius);
  7854. };
  7855. Scene.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  7856. if (typeof excludedMesh === "undefined") { excludedMesh = null; }
  7857. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  7858. if (collider.retry >= maximumRetry) {
  7859. finalPosition.copyFrom(position);
  7860. return;
  7861. }
  7862. collider._initialize(position, velocity, closeDistance);
  7863. for (var index = 0; index < this.meshes.length; index++) {
  7864. var mesh = this.meshes[index];
  7865. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  7866. mesh._checkCollision(collider);
  7867. }
  7868. }
  7869. if (!collider.collisionFound) {
  7870. position.addToRef(velocity, finalPosition);
  7871. return;
  7872. }
  7873. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  7874. collider._getResponse(position, velocity);
  7875. }
  7876. if (velocity.length() <= closeDistance) {
  7877. finalPosition.copyFrom(position);
  7878. return;
  7879. }
  7880. collider.retry++;
  7881. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  7882. };
  7883. // Octrees
  7884. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  7885. if (typeof maxCapacity === "undefined") { maxCapacity = 64; }
  7886. if (typeof maxDepth === "undefined") { maxDepth = 2; }
  7887. if (!this._selectionOctree) {
  7888. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  7889. }
  7890. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7891. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  7892. for (var index = 0; index < this.meshes.length; index++) {
  7893. var mesh = this.meshes[index];
  7894. mesh.computeWorldMatrix(true);
  7895. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  7896. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  7897. BABYLON.Tools.CheckExtends(minBox, min, max);
  7898. BABYLON.Tools.CheckExtends(maxBox, min, max);
  7899. }
  7900. // Update octree
  7901. this._selectionOctree.update(min, max, this.meshes);
  7902. return this._selectionOctree;
  7903. };
  7904. // Picking
  7905. Scene.prototype.createPickingRay = function (x, y, world, camera) {
  7906. var engine = this._engine;
  7907. if (!camera) {
  7908. if (!this.activeCamera)
  7909. throw new Error("Active camera not set");
  7910. camera = this.activeCamera;
  7911. }
  7912. var cameraViewport = camera.viewport;
  7913. var viewport = cameraViewport.toGlobal(engine);
  7914. // Moving coordinates to local viewport world
  7915. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  7916. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  7917. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  7918. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  7919. };
  7920. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  7921. var pickingInfo = null;
  7922. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  7923. var mesh = this.meshes[meshIndex];
  7924. if (predicate) {
  7925. if (!predicate(mesh)) {
  7926. continue;
  7927. }
  7928. } else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  7929. continue;
  7930. }
  7931. var world = mesh.getWorldMatrix();
  7932. var ray = rayFunction(world);
  7933. var result = mesh.intersects(ray, fastCheck);
  7934. if (!result || !result.hit)
  7935. continue;
  7936. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  7937. continue;
  7938. pickingInfo = result;
  7939. if (fastCheck) {
  7940. break;
  7941. }
  7942. }
  7943. return pickingInfo || new BABYLON.PickingInfo();
  7944. };
  7945. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  7946. var _this = this;
  7947. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  7948. /// <param name="x">X position on screen</param>
  7949. /// <param name="y">Y position on screen</param>
  7950. /// <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>
  7951. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  7952. /// <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>
  7953. return this._internalPick(function (world) {
  7954. return _this.createPickingRay(x, y, world, camera);
  7955. }, predicate, fastCheck);
  7956. };
  7957. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  7958. var _this = this;
  7959. return this._internalPick(function (world) {
  7960. if (!_this._pickWithRayInverseMatrix) {
  7961. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  7962. }
  7963. world.invertToRef(_this._pickWithRayInverseMatrix);
  7964. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  7965. }, predicate, fastCheck);
  7966. };
  7967. Scene.prototype.setPointerOverMesh = function (mesh) {
  7968. if (this._pointerOverMesh === mesh) {
  7969. return;
  7970. }
  7971. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  7972. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  7973. }
  7974. this._pointerOverMesh = mesh;
  7975. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  7976. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  7977. }
  7978. };
  7979. Scene.prototype.getPointerOverMesh = function () {
  7980. return this._pointerOverMesh;
  7981. };
  7982. // Physics
  7983. Scene.prototype.getPhysicsEngine = function () {
  7984. return this._physicsEngine;
  7985. };
  7986. Scene.prototype.enablePhysics = function (gravity, plugin) {
  7987. if (this._physicsEngine) {
  7988. return true;
  7989. }
  7990. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  7991. if (!this._physicsEngine.isSupported()) {
  7992. this._physicsEngine = null;
  7993. return false;
  7994. }
  7995. this._physicsEngine._initialize(gravity);
  7996. return true;
  7997. };
  7998. Scene.prototype.disablePhysicsEngine = function () {
  7999. if (!this._physicsEngine) {
  8000. return;
  8001. }
  8002. this._physicsEngine.dispose();
  8003. this._physicsEngine = undefined;
  8004. };
  8005. Scene.prototype.isPhysicsEnabled = function () {
  8006. return this._physicsEngine !== undefined;
  8007. };
  8008. Scene.prototype.setGravity = function (gravity) {
  8009. if (!this._physicsEngine) {
  8010. return;
  8011. }
  8012. this._physicsEngine._setGravity(gravity);
  8013. };
  8014. Scene.prototype.createCompoundImpostor = function (parts, options) {
  8015. if (parts.parts) {
  8016. options = parts;
  8017. parts = parts.parts;
  8018. }
  8019. if (!this._physicsEngine) {
  8020. return null;
  8021. }
  8022. for (var index = 0; index < parts.length; index++) {
  8023. var mesh = parts[index].mesh;
  8024. mesh._physicImpostor = parts[index].impostor;
  8025. mesh._physicsMass = options.mass / parts.length;
  8026. mesh._physicsFriction = options.friction;
  8027. mesh._physicRestitution = options.restitution;
  8028. }
  8029. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  8030. };
  8031. //ANY
  8032. Scene.prototype.deleteCompoundImpostor = function (compound) {
  8033. for (var index = 0; index < compound.parts.length; index++) {
  8034. var mesh = compound.parts[index].mesh;
  8035. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  8036. this._physicsEngine._unregisterMesh(mesh);
  8037. }
  8038. };
  8039. // Tags
  8040. Scene.prototype._getByTags = function (list, tagsQuery) {
  8041. if (tagsQuery === undefined) {
  8042. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  8043. return list;
  8044. }
  8045. var listByTags = [];
  8046. for (var i in list) {
  8047. var item = list[i];
  8048. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  8049. listByTags.push(item);
  8050. }
  8051. }
  8052. return listByTags;
  8053. };
  8054. Scene.prototype.getMeshesByTags = function (tagsQuery) {
  8055. return this._getByTags(this.meshes, tagsQuery);
  8056. };
  8057. Scene.prototype.getCamerasByTags = function (tagsQuery) {
  8058. return this._getByTags(this.cameras, tagsQuery);
  8059. };
  8060. Scene.prototype.getLightsByTags = function (tagsQuery) {
  8061. return this._getByTags(this.lights, tagsQuery);
  8062. };
  8063. Scene.prototype.getMaterialByTags = function (tagsQuery) {
  8064. return this._getByTags(this.materials, tagsQuery).concat(this._getByTags(this.multiMaterials, tagsQuery));
  8065. };
  8066. Scene.FOGMODE_NONE = 0;
  8067. Scene.FOGMODE_EXP = 1;
  8068. Scene.FOGMODE_EXP2 = 2;
  8069. Scene.FOGMODE_LINEAR = 3;
  8070. Scene.MinDeltaTime = 1.0;
  8071. Scene.MaxDeltaTime = 1000.0;
  8072. return Scene;
  8073. })();
  8074. BABYLON.Scene = Scene;
  8075. })(BABYLON || (BABYLON = {}));
  8076. //# sourceMappingURL=babylon.scene.js.map
  8077. var BABYLON;
  8078. (function (BABYLON) {
  8079. var VertexBuffer = (function () {
  8080. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  8081. if (engine instanceof BABYLON.Mesh) {
  8082. this._engine = engine.getScene().getEngine();
  8083. } else {
  8084. this._engine = engine;
  8085. }
  8086. this._updatable = updatable;
  8087. this._data = data;
  8088. if (!postponeInternalCreation) {
  8089. this.create();
  8090. }
  8091. this._kind = kind;
  8092. if (stride) {
  8093. this._strideSize = stride;
  8094. return;
  8095. }
  8096. switch (kind) {
  8097. case VertexBuffer.PositionKind:
  8098. this._strideSize = 3;
  8099. break;
  8100. case VertexBuffer.NormalKind:
  8101. this._strideSize = 3;
  8102. break;
  8103. case VertexBuffer.UVKind:
  8104. this._strideSize = 2;
  8105. break;
  8106. case VertexBuffer.UV2Kind:
  8107. this._strideSize = 2;
  8108. break;
  8109. case VertexBuffer.ColorKind:
  8110. this._strideSize = 4;
  8111. break;
  8112. case VertexBuffer.MatricesIndicesKind:
  8113. this._strideSize = 4;
  8114. break;
  8115. case VertexBuffer.MatricesWeightsKind:
  8116. this._strideSize = 4;
  8117. break;
  8118. }
  8119. }
  8120. // Properties
  8121. VertexBuffer.prototype.isUpdatable = function () {
  8122. return this._updatable;
  8123. };
  8124. VertexBuffer.prototype.getData = function () {
  8125. return this._data;
  8126. };
  8127. VertexBuffer.prototype.getBuffer = function () {
  8128. return this._buffer;
  8129. };
  8130. VertexBuffer.prototype.getStrideSize = function () {
  8131. return this._strideSize;
  8132. };
  8133. // Methods
  8134. VertexBuffer.prototype.create = function (data) {
  8135. if (!data && this._buffer) {
  8136. return;
  8137. }
  8138. data = data || this._data;
  8139. if (!this._buffer) {
  8140. if (this._updatable) {
  8141. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  8142. } else {
  8143. this._buffer = this._engine.createVertexBuffer(data);
  8144. }
  8145. }
  8146. if (this._updatable) {
  8147. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  8148. this._data = data;
  8149. }
  8150. };
  8151. VertexBuffer.prototype.update = function (data) {
  8152. this.create(data);
  8153. };
  8154. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  8155. if (!this._buffer) {
  8156. return;
  8157. }
  8158. if (this._updatable) {
  8159. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  8160. this._data = null;
  8161. }
  8162. };
  8163. VertexBuffer.prototype.dispose = function () {
  8164. if (!this._buffer) {
  8165. return;
  8166. }
  8167. if (this._engine._releaseBuffer(this._buffer)) {
  8168. this._buffer = null;
  8169. }
  8170. };
  8171. Object.defineProperty(VertexBuffer, "PositionKind", {
  8172. get: function () {
  8173. return VertexBuffer._PositionKind;
  8174. },
  8175. enumerable: true,
  8176. configurable: true
  8177. });
  8178. Object.defineProperty(VertexBuffer, "NormalKind", {
  8179. get: function () {
  8180. return VertexBuffer._NormalKind;
  8181. },
  8182. enumerable: true,
  8183. configurable: true
  8184. });
  8185. Object.defineProperty(VertexBuffer, "UVKind", {
  8186. get: function () {
  8187. return VertexBuffer._UVKind;
  8188. },
  8189. enumerable: true,
  8190. configurable: true
  8191. });
  8192. Object.defineProperty(VertexBuffer, "UV2Kind", {
  8193. get: function () {
  8194. return VertexBuffer._UV2Kind;
  8195. },
  8196. enumerable: true,
  8197. configurable: true
  8198. });
  8199. Object.defineProperty(VertexBuffer, "ColorKind", {
  8200. get: function () {
  8201. return VertexBuffer._ColorKind;
  8202. },
  8203. enumerable: true,
  8204. configurable: true
  8205. });
  8206. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  8207. get: function () {
  8208. return VertexBuffer._MatricesIndicesKind;
  8209. },
  8210. enumerable: true,
  8211. configurable: true
  8212. });
  8213. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  8214. get: function () {
  8215. return VertexBuffer._MatricesWeightsKind;
  8216. },
  8217. enumerable: true,
  8218. configurable: true
  8219. });
  8220. VertexBuffer._PositionKind = "position";
  8221. VertexBuffer._NormalKind = "normal";
  8222. VertexBuffer._UVKind = "uv";
  8223. VertexBuffer._UV2Kind = "uv2";
  8224. VertexBuffer._ColorKind = "color";
  8225. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  8226. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  8227. return VertexBuffer;
  8228. })();
  8229. BABYLON.VertexBuffer = VertexBuffer;
  8230. })(BABYLON || (BABYLON = {}));
  8231. //# sourceMappingURL=babylon.vertexBuffer.js.map
  8232. var BABYLON;
  8233. (function (BABYLON) {
  8234. var AbstractMesh = (function (_super) {
  8235. __extends(AbstractMesh, _super);
  8236. function AbstractMesh(name, scene) {
  8237. _super.call(this, name, scene);
  8238. // Properties
  8239. this.position = new BABYLON.Vector3(0, 0, 0);
  8240. this.rotation = new BABYLON.Vector3(0, 0, 0);
  8241. this.scaling = new BABYLON.Vector3(1, 1, 1);
  8242. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  8243. this.visibility = 1.0;
  8244. this.alphaIndex = Number.MAX_VALUE;
  8245. this.infiniteDistance = false;
  8246. this.isVisible = true;
  8247. this.isPickable = true;
  8248. this.showBoundingBox = false;
  8249. this.showSubMeshesBoundingBox = false;
  8250. this.onDispose = null;
  8251. this.checkCollisions = false;
  8252. this.isBlocker = false;
  8253. this.renderingGroupId = 0;
  8254. this.receiveShadows = false;
  8255. this.renderOutline = false;
  8256. this.outlineColor = BABYLON.Color3.Red();
  8257. this.outlineWidth = 0.02;
  8258. this.renderOverlay = false;
  8259. this.overlayColor = BABYLON.Color3.Red();
  8260. this.overlayAlpha = 0.5;
  8261. this.hasVertexAlpha = false;
  8262. this.useVertexColors = true;
  8263. this.applyFog = true;
  8264. this.useOctreeForRenderingSelection = true;
  8265. this.useOctreeForPicking = true;
  8266. this.useOctreeForCollisions = true;
  8267. this.layerMask = 0xFFFFFFFF;
  8268. // Physics
  8269. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  8270. // Collisions
  8271. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  8272. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  8273. this._collider = new BABYLON.Collider();
  8274. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8275. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8276. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8277. // Cache
  8278. this._localScaling = BABYLON.Matrix.Zero();
  8279. this._localRotation = BABYLON.Matrix.Zero();
  8280. this._localTranslation = BABYLON.Matrix.Zero();
  8281. this._localBillboard = BABYLON.Matrix.Zero();
  8282. this._localPivotScaling = BABYLON.Matrix.Zero();
  8283. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  8284. this._localWorld = BABYLON.Matrix.Zero();
  8285. this._worldMatrix = BABYLON.Matrix.Zero();
  8286. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  8287. this._absolutePosition = BABYLON.Vector3.Zero();
  8288. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  8289. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  8290. this._isDirty = false;
  8291. this._pivotMatrix = BABYLON.Matrix.Identity();
  8292. this._isDisposed = false;
  8293. this._renderId = 0;
  8294. this._intersectionsInProgress = new Array();
  8295. this._onAfterWorldMatrixUpdate = new Array();
  8296. scene.meshes.push(this);
  8297. }
  8298. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  8299. get: function () {
  8300. return AbstractMesh._BILLBOARDMODE_NONE;
  8301. },
  8302. enumerable: true,
  8303. configurable: true
  8304. });
  8305. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  8306. get: function () {
  8307. return AbstractMesh._BILLBOARDMODE_X;
  8308. },
  8309. enumerable: true,
  8310. configurable: true
  8311. });
  8312. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  8313. get: function () {
  8314. return AbstractMesh._BILLBOARDMODE_Y;
  8315. },
  8316. enumerable: true,
  8317. configurable: true
  8318. });
  8319. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  8320. get: function () {
  8321. return AbstractMesh._BILLBOARDMODE_Z;
  8322. },
  8323. enumerable: true,
  8324. configurable: true
  8325. });
  8326. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  8327. get: function () {
  8328. return AbstractMesh._BILLBOARDMODE_ALL;
  8329. },
  8330. enumerable: true,
  8331. configurable: true
  8332. });
  8333. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  8334. // Methods
  8335. get: function () {
  8336. return false;
  8337. },
  8338. enumerable: true,
  8339. configurable: true
  8340. });
  8341. AbstractMesh.prototype.getLOD = function (camera) {
  8342. return this;
  8343. };
  8344. AbstractMesh.prototype.getTotalVertices = function () {
  8345. return 0;
  8346. };
  8347. AbstractMesh.prototype.getIndices = function () {
  8348. return null;
  8349. };
  8350. AbstractMesh.prototype.getVerticesData = function (kind) {
  8351. return null;
  8352. };
  8353. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  8354. return false;
  8355. };
  8356. AbstractMesh.prototype.getBoundingInfo = function () {
  8357. if (this._masterMesh) {
  8358. return this._masterMesh.getBoundingInfo();
  8359. }
  8360. if (!this._boundingInfo) {
  8361. this._updateBoundingInfo();
  8362. }
  8363. return this._boundingInfo;
  8364. };
  8365. AbstractMesh.prototype._preActivate = function () {
  8366. };
  8367. AbstractMesh.prototype._activate = function (renderId) {
  8368. this._renderId = renderId;
  8369. };
  8370. AbstractMesh.prototype.getWorldMatrix = function () {
  8371. if (this._masterMesh) {
  8372. return this._masterMesh.getWorldMatrix();
  8373. }
  8374. if (this._currentRenderId !== this.getScene().getRenderId()) {
  8375. this.computeWorldMatrix();
  8376. }
  8377. return this._worldMatrix;
  8378. };
  8379. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  8380. get: function () {
  8381. return this._worldMatrix;
  8382. },
  8383. enumerable: true,
  8384. configurable: true
  8385. });
  8386. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  8387. get: function () {
  8388. return this._absolutePosition;
  8389. },
  8390. enumerable: true,
  8391. configurable: true
  8392. });
  8393. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  8394. if (!this.rotationQuaternion) {
  8395. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  8396. this.rotation = BABYLON.Vector3.Zero();
  8397. }
  8398. if (!space || space == 0 /* LOCAL */) {
  8399. var rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  8400. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  8401. } else {
  8402. if (this.parent) {
  8403. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  8404. invertParentWorldMatrix.invert();
  8405. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  8406. }
  8407. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  8408. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  8409. }
  8410. };
  8411. AbstractMesh.prototype.translate = function (axis, distance, space) {
  8412. var displacementVector = axis.scale(distance);
  8413. if (!space || space == 0 /* LOCAL */) {
  8414. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  8415. this.setPositionWithLocalVector(tempV3);
  8416. } else {
  8417. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  8418. }
  8419. };
  8420. AbstractMesh.prototype.getAbsolutePosition = function () {
  8421. this.computeWorldMatrix();
  8422. return this._absolutePosition;
  8423. };
  8424. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  8425. if (!absolutePosition) {
  8426. return;
  8427. }
  8428. var absolutePositionX;
  8429. var absolutePositionY;
  8430. var absolutePositionZ;
  8431. if (absolutePosition.x === undefined) {
  8432. if (arguments.length < 3) {
  8433. return;
  8434. }
  8435. absolutePositionX = arguments[0];
  8436. absolutePositionY = arguments[1];
  8437. absolutePositionZ = arguments[2];
  8438. } else {
  8439. absolutePositionX = absolutePosition.x;
  8440. absolutePositionY = absolutePosition.y;
  8441. absolutePositionZ = absolutePosition.z;
  8442. }
  8443. if (this.parent) {
  8444. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  8445. invertParentWorldMatrix.invert();
  8446. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  8447. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  8448. } else {
  8449. this.position.x = absolutePositionX;
  8450. this.position.y = absolutePositionY;
  8451. this.position.z = absolutePositionZ;
  8452. }
  8453. };
  8454. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  8455. this._pivotMatrix = matrix;
  8456. this._cache.pivotMatrixUpdated = true;
  8457. };
  8458. AbstractMesh.prototype.getPivotMatrix = function () {
  8459. return this._pivotMatrix;
  8460. };
  8461. AbstractMesh.prototype._isSynchronized = function () {
  8462. if (this._isDirty) {
  8463. return false;
  8464. }
  8465. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  8466. return false;
  8467. if (this._cache.pivotMatrixUpdated) {
  8468. return false;
  8469. }
  8470. if (this.infiniteDistance) {
  8471. return false;
  8472. }
  8473. if (!this._cache.position.equals(this.position))
  8474. return false;
  8475. if (this.rotationQuaternion) {
  8476. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  8477. return false;
  8478. } else {
  8479. if (!this._cache.rotation.equals(this.rotation))
  8480. return false;
  8481. }
  8482. if (!this._cache.scaling.equals(this.scaling))
  8483. return false;
  8484. return true;
  8485. };
  8486. AbstractMesh.prototype._initCache = function () {
  8487. _super.prototype._initCache.call(this);
  8488. this._cache.localMatrixUpdated = false;
  8489. this._cache.position = BABYLON.Vector3.Zero();
  8490. this._cache.scaling = BABYLON.Vector3.Zero();
  8491. this._cache.rotation = BABYLON.Vector3.Zero();
  8492. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  8493. };
  8494. AbstractMesh.prototype.markAsDirty = function (property) {
  8495. if (property === "rotation") {
  8496. this.rotationQuaternion = null;
  8497. }
  8498. this._currentRenderId = Number.MAX_VALUE;
  8499. this._isDirty = true;
  8500. };
  8501. AbstractMesh.prototype._updateBoundingInfo = function () {
  8502. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  8503. this._boundingInfo._update(this.worldMatrixFromCache);
  8504. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  8505. };
  8506. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  8507. if (!this.subMeshes) {
  8508. return;
  8509. }
  8510. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  8511. var subMesh = this.subMeshes[subIndex];
  8512. subMesh.updateBoundingInfo(matrix);
  8513. }
  8514. };
  8515. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  8516. if (!force && (this._currentRenderId == this.getScene().getRenderId() || this.isSynchronized(true))) {
  8517. return this._worldMatrix;
  8518. }
  8519. this._cache.position.copyFrom(this.position);
  8520. this._cache.scaling.copyFrom(this.scaling);
  8521. this._cache.pivotMatrixUpdated = false;
  8522. this._currentRenderId = this.getScene().getRenderId();
  8523. this._isDirty = false;
  8524. // Scaling
  8525. BABYLON.Matrix.ScalingToRef(this.scaling.x, this.scaling.y, this.scaling.z, this._localScaling);
  8526. // Rotation
  8527. if (this.rotationQuaternion) {
  8528. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  8529. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  8530. } else {
  8531. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  8532. this._cache.rotation.copyFrom(this.rotation);
  8533. }
  8534. // Translation
  8535. if (this.infiniteDistance && !this.parent) {
  8536. var camera = this.getScene().activeCamera;
  8537. var cameraWorldMatrix = camera.getWorldMatrix();
  8538. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  8539. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  8540. } else {
  8541. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  8542. }
  8543. // Composing transformations
  8544. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  8545. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  8546. // Billboarding
  8547. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  8548. var localPosition = this.position.clone();
  8549. var zero = this.getScene().activeCamera.position.clone();
  8550. if (this.parent && this.parent.position) {
  8551. localPosition.addInPlace(this.parent.position);
  8552. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  8553. }
  8554. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) === AbstractMesh.BILLBOARDMODE_ALL) {
  8555. zero = this.getScene().activeCamera.position;
  8556. } else {
  8557. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X)
  8558. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  8559. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y)
  8560. zero.y = localPosition.y + 0.001;
  8561. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z)
  8562. zero.z = localPosition.z + 0.001;
  8563. }
  8564. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  8565. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  8566. this._localBillboard.invert();
  8567. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  8568. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  8569. }
  8570. // Local world
  8571. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  8572. // Parent
  8573. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  8574. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  8575. } else {
  8576. this._worldMatrix.copyFrom(this._localWorld);
  8577. }
  8578. // Bounding info
  8579. this._updateBoundingInfo();
  8580. // Absolute position
  8581. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  8582. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  8583. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  8584. }
  8585. return this._worldMatrix;
  8586. };
  8587. /**
  8588. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  8589. * @param func: callback function to add
  8590. */
  8591. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  8592. this._onAfterWorldMatrixUpdate.push(func);
  8593. };
  8594. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  8595. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  8596. if (index > -1) {
  8597. this._onAfterWorldMatrixUpdate.splice(index, 1);
  8598. }
  8599. };
  8600. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  8601. this.computeWorldMatrix();
  8602. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  8603. };
  8604. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  8605. this.computeWorldMatrix();
  8606. var invLocalWorldMatrix = this._localWorld.clone();
  8607. invLocalWorldMatrix.invert();
  8608. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  8609. };
  8610. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  8611. this.computeWorldMatrix();
  8612. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  8613. };
  8614. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  8615. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  8616. /// <param name="targetPoint" type="BABYLON.Vector3">The position (must be in same space as current mesh) to look at</param>
  8617. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  8618. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  8619. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  8620. /// <returns>Mesh oriented towards targetMesh</returns>
  8621. yawCor = yawCor || 0; // default to zero if undefined
  8622. pitchCor = pitchCor || 0;
  8623. rollCor = rollCor || 0;
  8624. var dv = targetPoint.subtract(this.position);
  8625. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  8626. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  8627. var pitch = Math.atan2(dv.y, len);
  8628. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  8629. };
  8630. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  8631. if (!this._boundingInfo.isInFrustum(frustumPlanes)) {
  8632. return false;
  8633. }
  8634. return true;
  8635. };
  8636. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  8637. if (!camera) {
  8638. camera = this.getScene().activeCamera;
  8639. }
  8640. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  8641. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  8642. return false;
  8643. }
  8644. return true;
  8645. };
  8646. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  8647. if (!this._boundingInfo || !mesh._boundingInfo) {
  8648. return false;
  8649. }
  8650. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  8651. };
  8652. AbstractMesh.prototype.intersectsPoint = function (point) {
  8653. if (!this._boundingInfo) {
  8654. return false;
  8655. }
  8656. return this._boundingInfo.intersectsPoint(point);
  8657. };
  8658. // Physics
  8659. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  8660. var physicsEngine = this.getScene().getPhysicsEngine();
  8661. if (!physicsEngine) {
  8662. return;
  8663. }
  8664. if (impostor.impostor) {
  8665. // Old API
  8666. options = impostor;
  8667. impostor = impostor.impostor;
  8668. }
  8669. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  8670. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  8671. physicsEngine._unregisterMesh(this);
  8672. return;
  8673. }
  8674. options.mass = options.mass || 0;
  8675. options.friction = options.friction || 0.2;
  8676. options.restitution = options.restitution || 0.2;
  8677. this._physicImpostor = impostor;
  8678. this._physicsMass = options.mass;
  8679. this._physicsFriction = options.friction;
  8680. this._physicRestitution = options.restitution;
  8681. return physicsEngine._registerMesh(this, impostor, options);
  8682. };
  8683. AbstractMesh.prototype.getPhysicsImpostor = function () {
  8684. if (!this._physicImpostor) {
  8685. return BABYLON.PhysicsEngine.NoImpostor;
  8686. }
  8687. return this._physicImpostor;
  8688. };
  8689. AbstractMesh.prototype.getPhysicsMass = function () {
  8690. if (!this._physicsMass) {
  8691. return 0;
  8692. }
  8693. return this._physicsMass;
  8694. };
  8695. AbstractMesh.prototype.getPhysicsFriction = function () {
  8696. if (!this._physicsFriction) {
  8697. return 0;
  8698. }
  8699. return this._physicsFriction;
  8700. };
  8701. AbstractMesh.prototype.getPhysicsRestitution = function () {
  8702. if (!this._physicRestitution) {
  8703. return 0;
  8704. }
  8705. return this._physicRestitution;
  8706. };
  8707. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  8708. if (!camera) {
  8709. camera = this.getScene().activeCamera;
  8710. }
  8711. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  8712. };
  8713. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  8714. if (!camera) {
  8715. camera = this.getScene().activeCamera;
  8716. }
  8717. return this.absolutePosition.subtract(camera.position).length();
  8718. };
  8719. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  8720. if (!this._physicImpostor) {
  8721. return;
  8722. }
  8723. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  8724. };
  8725. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  8726. if (!this._physicImpostor) {
  8727. return;
  8728. }
  8729. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  8730. };
  8731. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  8732. if (!this._physicImpostor) {
  8733. return;
  8734. }
  8735. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  8736. };
  8737. // Collisions
  8738. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  8739. var globalPosition = this.getAbsolutePosition();
  8740. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  8741. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  8742. this._collider.radius = this.ellipsoid;
  8743. this.getScene()._getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this._newPositionForCollisions, this);
  8744. this._newPositionForCollisions.subtractToRef(this._oldPositionForCollisions, this._diffPositionForCollisions);
  8745. if (this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  8746. this.position.addInPlace(this._diffPositionForCollisions);
  8747. }
  8748. };
  8749. // Submeshes octree
  8750. /**
  8751. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  8752. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  8753. */
  8754. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  8755. if (typeof maxCapacity === "undefined") { maxCapacity = 64; }
  8756. if (typeof maxDepth === "undefined") { maxDepth = 2; }
  8757. if (!this._submeshesOctree) {
  8758. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  8759. }
  8760. this.computeWorldMatrix(true);
  8761. // Update octree
  8762. var bbox = this.getBoundingInfo().boundingBox;
  8763. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  8764. return this._submeshesOctree;
  8765. };
  8766. // Collisions
  8767. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  8768. this._generatePointsArray();
  8769. // Transformation
  8770. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  8771. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  8772. subMesh._lastColliderWorldVertices = [];
  8773. subMesh._trianglePlanes = [];
  8774. var start = subMesh.verticesStart;
  8775. var end = (subMesh.verticesStart + subMesh.verticesCount);
  8776. for (var i = start; i < end; i++) {
  8777. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  8778. }
  8779. }
  8780. // Collide
  8781. collider._collide(subMesh, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart);
  8782. };
  8783. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  8784. var subMeshes;
  8785. var len;
  8786. // Octrees
  8787. if (this._submeshesOctree && this.useOctreeForCollisions) {
  8788. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  8789. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  8790. len = intersections.length;
  8791. subMeshes = intersections.data;
  8792. } else {
  8793. subMeshes = this.subMeshes;
  8794. len = subMeshes.length;
  8795. }
  8796. for (var index = 0; index < len; index++) {
  8797. var subMesh = subMeshes[index];
  8798. // Bounding test
  8799. if (len > 1 && !subMesh._checkCollision(collider))
  8800. continue;
  8801. this._collideForSubMesh(subMesh, transformMatrix, collider);
  8802. }
  8803. };
  8804. AbstractMesh.prototype._checkCollision = function (collider) {
  8805. // Bounding box test
  8806. if (!this._boundingInfo._checkCollision(collider))
  8807. return;
  8808. // Transformation matrix
  8809. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  8810. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  8811. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  8812. };
  8813. // Picking
  8814. AbstractMesh.prototype._generatePointsArray = function () {
  8815. return false;
  8816. };
  8817. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  8818. var pickingInfo = new BABYLON.PickingInfo();
  8819. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  8820. return pickingInfo;
  8821. }
  8822. if (!this._generatePointsArray()) {
  8823. return pickingInfo;
  8824. }
  8825. var intersectInfo = null;
  8826. // Octrees
  8827. var subMeshes;
  8828. var len;
  8829. if (this._submeshesOctree && this.useOctreeForPicking) {
  8830. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  8831. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  8832. len = intersections.length;
  8833. subMeshes = intersections.data;
  8834. } else {
  8835. subMeshes = this.subMeshes;
  8836. len = subMeshes.length;
  8837. }
  8838. for (var index = 0; index < len; index++) {
  8839. var subMesh = subMeshes[index];
  8840. // Bounding test
  8841. if (len > 1 && !subMesh.canIntersects(ray))
  8842. continue;
  8843. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  8844. if (currentIntersectInfo) {
  8845. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  8846. intersectInfo = currentIntersectInfo;
  8847. if (fastCheck) {
  8848. break;
  8849. }
  8850. }
  8851. }
  8852. }
  8853. if (intersectInfo) {
  8854. // Get picked point
  8855. var world = this.getWorldMatrix();
  8856. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  8857. var direction = ray.direction.clone();
  8858. direction.normalize();
  8859. direction = direction.scale(intersectInfo.distance);
  8860. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  8861. var pickedPoint = worldOrigin.add(worldDirection);
  8862. // Return result
  8863. pickingInfo.hit = true;
  8864. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  8865. pickingInfo.pickedPoint = pickedPoint;
  8866. pickingInfo.pickedMesh = this;
  8867. pickingInfo.bu = intersectInfo.bu;
  8868. pickingInfo.bv = intersectInfo.bv;
  8869. pickingInfo.faceId = intersectInfo.faceId;
  8870. return pickingInfo;
  8871. }
  8872. return pickingInfo;
  8873. };
  8874. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  8875. return null;
  8876. };
  8877. AbstractMesh.prototype.releaseSubMeshes = function () {
  8878. if (this.subMeshes) {
  8879. while (this.subMeshes.length) {
  8880. this.subMeshes[0].dispose();
  8881. }
  8882. } else {
  8883. this.subMeshes = new Array();
  8884. }
  8885. };
  8886. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  8887. // Physics
  8888. if (this.getPhysicsImpostor() != BABYLON.PhysicsEngine.NoImpostor) {
  8889. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  8890. }
  8891. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  8892. var other = this._intersectionsInProgress[index];
  8893. var pos = other._intersectionsInProgress.indexOf(this);
  8894. other._intersectionsInProgress.splice(pos, 1);
  8895. }
  8896. this._intersectionsInProgress = [];
  8897. // SubMeshes
  8898. this.releaseSubMeshes();
  8899. // Remove from scene
  8900. var index = this.getScene().meshes.indexOf(this);
  8901. if (index != -1) {
  8902. // Remove from the scene if mesh found
  8903. this.getScene().meshes.splice(index, 1);
  8904. }
  8905. if (!doNotRecurse) {
  8906. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  8907. if (this.getScene().particleSystems[index].emitter == this) {
  8908. this.getScene().particleSystems[index].dispose();
  8909. index--;
  8910. }
  8911. }
  8912. // Children
  8913. var objects = this.getScene().meshes.slice(0);
  8914. for (index = 0; index < objects.length; index++) {
  8915. if (objects[index].parent == this) {
  8916. objects[index].dispose();
  8917. }
  8918. }
  8919. } else {
  8920. for (index = 0; index < this.getScene().meshes.length; index++) {
  8921. var obj = this.getScene().meshes[index];
  8922. if (obj.parent === this) {
  8923. obj.parent = null;
  8924. obj.computeWorldMatrix(true);
  8925. }
  8926. }
  8927. }
  8928. this._onAfterWorldMatrixUpdate = [];
  8929. this._isDisposed = true;
  8930. // Callback
  8931. if (this.onDispose) {
  8932. this.onDispose();
  8933. }
  8934. };
  8935. AbstractMesh._BILLBOARDMODE_NONE = 0;
  8936. AbstractMesh._BILLBOARDMODE_X = 1;
  8937. AbstractMesh._BILLBOARDMODE_Y = 2;
  8938. AbstractMesh._BILLBOARDMODE_Z = 4;
  8939. AbstractMesh._BILLBOARDMODE_ALL = 7;
  8940. return AbstractMesh;
  8941. })(BABYLON.Node);
  8942. BABYLON.AbstractMesh = AbstractMesh;
  8943. })(BABYLON || (BABYLON = {}));
  8944. //# sourceMappingURL=babylon.abstractMesh.js.map
  8945. var BABYLON;
  8946. (function (BABYLON) {
  8947. var _InstancesBatch = (function () {
  8948. function _InstancesBatch() {
  8949. this.mustReturn = false;
  8950. this.visibleInstances = new Array();
  8951. this.renderSelf = new Array();
  8952. }
  8953. return _InstancesBatch;
  8954. })();
  8955. BABYLON._InstancesBatch = _InstancesBatch;
  8956. var Mesh = (function (_super) {
  8957. __extends(Mesh, _super);
  8958. function Mesh(name, scene) {
  8959. _super.call(this, name, scene);
  8960. // Members
  8961. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  8962. this.instances = new Array();
  8963. this._LODLevels = new Array();
  8964. this._onBeforeRenderCallbacks = new Array();
  8965. this._onAfterRenderCallbacks = new Array();
  8966. this._visibleInstances = {};
  8967. this._renderIdForInstances = new Array();
  8968. this._batchCache = new _InstancesBatch();
  8969. this._instancesBufferSize = 32 * 16 * 4;
  8970. }
  8971. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  8972. // Methods
  8973. get: function () {
  8974. return this._LODLevels.length > 0;
  8975. },
  8976. enumerable: true,
  8977. configurable: true
  8978. });
  8979. Mesh.prototype._sortLODLevels = function () {
  8980. this._LODLevels.sort(function (a, b) {
  8981. if (a.distance < b.distance) {
  8982. return 1;
  8983. }
  8984. if (a.distance > b.distance) {
  8985. return -1;
  8986. }
  8987. return 0;
  8988. });
  8989. };
  8990. Mesh.prototype.addLODLevel = function (distance, mesh) {
  8991. if (mesh && mesh._masterMesh) {
  8992. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  8993. return this;
  8994. }
  8995. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  8996. this._LODLevels.push(level);
  8997. if (mesh) {
  8998. mesh._masterMesh = this;
  8999. }
  9000. this._sortLODLevels();
  9001. return this;
  9002. };
  9003. Mesh.prototype.removeLODLevel = function (mesh) {
  9004. for (var index = 0; index < this._LODLevels.length; index++) {
  9005. if (this._LODLevels[index].mesh === mesh) {
  9006. this._LODLevels.splice(index, 1);
  9007. if (mesh) {
  9008. mesh._masterMesh = null;
  9009. }
  9010. }
  9011. }
  9012. this._sortLODLevels();
  9013. return this;
  9014. };
  9015. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  9016. if (!this._LODLevels || this._LODLevels.length === 0) {
  9017. return this;
  9018. }
  9019. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  9020. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  9021. return this;
  9022. }
  9023. for (var index = 0; index < this._LODLevels.length; index++) {
  9024. var level = this._LODLevels[index];
  9025. if (level.distance < distanceToCamera) {
  9026. if (level.mesh) {
  9027. level.mesh._preActivate();
  9028. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  9029. }
  9030. return level.mesh;
  9031. }
  9032. }
  9033. return this;
  9034. };
  9035. Object.defineProperty(Mesh.prototype, "geometry", {
  9036. get: function () {
  9037. return this._geometry;
  9038. },
  9039. enumerable: true,
  9040. configurable: true
  9041. });
  9042. Mesh.prototype.getTotalVertices = function () {
  9043. if (!this._geometry) {
  9044. return 0;
  9045. }
  9046. return this._geometry.getTotalVertices();
  9047. };
  9048. Mesh.prototype.getVerticesData = function (kind) {
  9049. if (!this._geometry) {
  9050. return null;
  9051. }
  9052. return this._geometry.getVerticesData(kind);
  9053. };
  9054. Mesh.prototype.getVertexBuffer = function (kind) {
  9055. if (!this._geometry) {
  9056. return undefined;
  9057. }
  9058. return this._geometry.getVertexBuffer(kind);
  9059. };
  9060. Mesh.prototype.isVerticesDataPresent = function (kind) {
  9061. if (!this._geometry) {
  9062. if (this._delayInfo) {
  9063. return this._delayInfo.indexOf(kind) !== -1;
  9064. }
  9065. return false;
  9066. }
  9067. return this._geometry.isVerticesDataPresent(kind);
  9068. };
  9069. Mesh.prototype.getVerticesDataKinds = function () {
  9070. if (!this._geometry) {
  9071. var result = [];
  9072. if (this._delayInfo) {
  9073. for (var kind in this._delayInfo) {
  9074. result.push(kind);
  9075. }
  9076. }
  9077. return result;
  9078. }
  9079. return this._geometry.getVerticesDataKinds();
  9080. };
  9081. Mesh.prototype.getTotalIndices = function () {
  9082. if (!this._geometry) {
  9083. return 0;
  9084. }
  9085. return this._geometry.getTotalIndices();
  9086. };
  9087. Mesh.prototype.getIndices = function () {
  9088. if (!this._geometry) {
  9089. return [];
  9090. }
  9091. return this._geometry.getIndices();
  9092. };
  9093. Object.defineProperty(Mesh.prototype, "isBlocked", {
  9094. get: function () {
  9095. return this._masterMesh !== null && this._masterMesh !== undefined;
  9096. },
  9097. enumerable: true,
  9098. configurable: true
  9099. });
  9100. Mesh.prototype.isReady = function () {
  9101. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  9102. return false;
  9103. }
  9104. return _super.prototype.isReady.call(this);
  9105. };
  9106. Mesh.prototype.isDisposed = function () {
  9107. return this._isDisposed;
  9108. };
  9109. // Methods
  9110. Mesh.prototype._preActivate = function () {
  9111. var sceneRenderId = this.getScene().getRenderId();
  9112. if (this._preActivateId == sceneRenderId) {
  9113. return;
  9114. }
  9115. this._preActivateId = sceneRenderId;
  9116. this._visibleInstances = null;
  9117. };
  9118. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  9119. if (!this._visibleInstances) {
  9120. this._visibleInstances = {};
  9121. this._visibleInstances.defaultRenderId = renderId;
  9122. this._visibleInstances.selfDefaultRenderId = this._renderId;
  9123. }
  9124. if (!this._visibleInstances[renderId]) {
  9125. this._visibleInstances[renderId] = new Array();
  9126. }
  9127. this._visibleInstances[renderId].push(instance);
  9128. };
  9129. Mesh.prototype.refreshBoundingInfo = function () {
  9130. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  9131. if (data) {
  9132. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  9133. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  9134. }
  9135. if (this.subMeshes) {
  9136. for (var index = 0; index < this.subMeshes.length; index++) {
  9137. this.subMeshes[index].refreshBoundingInfo();
  9138. }
  9139. }
  9140. this._updateBoundingInfo();
  9141. };
  9142. Mesh.prototype._createGlobalSubMesh = function () {
  9143. var totalVertices = this.getTotalVertices();
  9144. if (!totalVertices || !this.getIndices()) {
  9145. return null;
  9146. }
  9147. this.releaseSubMeshes();
  9148. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  9149. };
  9150. Mesh.prototype.subdivide = function (count) {
  9151. if (count < 1) {
  9152. return;
  9153. }
  9154. var totalIndices = this.getTotalIndices();
  9155. var subdivisionSize = (totalIndices / count) | 0;
  9156. var offset = 0;
  9157. while (subdivisionSize % 3 != 0) {
  9158. subdivisionSize++;
  9159. }
  9160. this.releaseSubMeshes();
  9161. for (var index = 0; index < count; index++) {
  9162. if (offset >= totalIndices) {
  9163. break;
  9164. }
  9165. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  9166. offset += subdivisionSize;
  9167. }
  9168. this.synchronizeInstances();
  9169. };
  9170. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  9171. if (kind instanceof Array) {
  9172. var temp = data;
  9173. data = kind;
  9174. kind = temp;
  9175. BABYLON.Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  9176. }
  9177. if (!this._geometry) {
  9178. var vertexData = new BABYLON.VertexData();
  9179. vertexData.set(data, kind);
  9180. var scene = this.getScene();
  9181. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  9182. } else {
  9183. this._geometry.setVerticesData(kind, data, updatable, stride);
  9184. }
  9185. };
  9186. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  9187. if (!this._geometry) {
  9188. return;
  9189. }
  9190. if (!makeItUnique) {
  9191. this._geometry.updateVerticesData(kind, data, updateExtends);
  9192. } else {
  9193. this.makeGeometryUnique();
  9194. this.updateVerticesData(kind, data, updateExtends, false);
  9195. }
  9196. };
  9197. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  9198. if (!this._geometry) {
  9199. return;
  9200. }
  9201. if (!makeItUnique) {
  9202. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  9203. } else {
  9204. this.makeGeometryUnique();
  9205. this.updateVerticesDataDirectly(kind, data, offset, false);
  9206. }
  9207. };
  9208. Mesh.prototype.makeGeometryUnique = function () {
  9209. if (!this._geometry) {
  9210. return;
  9211. }
  9212. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  9213. geometry.applyToMesh(this);
  9214. };
  9215. Mesh.prototype.setIndices = function (indices, totalVertices) {
  9216. if (!this._geometry) {
  9217. var vertexData = new BABYLON.VertexData();
  9218. vertexData.indices = indices;
  9219. var scene = this.getScene();
  9220. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  9221. } else {
  9222. this._geometry.setIndices(indices, totalVertices);
  9223. }
  9224. };
  9225. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  9226. var engine = this.getScene().getEngine();
  9227. // Wireframe
  9228. var indexToBind;
  9229. switch (fillMode) {
  9230. case BABYLON.Material.PointFillMode:
  9231. indexToBind = null;
  9232. break;
  9233. case BABYLON.Material.WireFrameFillMode:
  9234. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  9235. break;
  9236. default:
  9237. case BABYLON.Material.TriangleFillMode:
  9238. indexToBind = this._geometry.getIndexBuffer();
  9239. break;
  9240. }
  9241. // VBOs
  9242. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  9243. };
  9244. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  9245. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  9246. return;
  9247. }
  9248. var engine = this.getScene().getEngine();
  9249. switch (fillMode) {
  9250. case BABYLON.Material.PointFillMode:
  9251. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  9252. break;
  9253. case BABYLON.Material.WireFrameFillMode:
  9254. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  9255. break;
  9256. default:
  9257. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  9258. }
  9259. };
  9260. Mesh.prototype.registerBeforeRender = function (func) {
  9261. this._onBeforeRenderCallbacks.push(func);
  9262. };
  9263. Mesh.prototype.unregisterBeforeRender = function (func) {
  9264. var index = this._onBeforeRenderCallbacks.indexOf(func);
  9265. if (index > -1) {
  9266. this._onBeforeRenderCallbacks.splice(index, 1);
  9267. }
  9268. };
  9269. Mesh.prototype.registerAfterRender = function (func) {
  9270. this._onAfterRenderCallbacks.push(func);
  9271. };
  9272. Mesh.prototype.unregisterAfterRender = function (func) {
  9273. var index = this._onAfterRenderCallbacks.indexOf(func);
  9274. if (index > -1) {
  9275. this._onAfterRenderCallbacks.splice(index, 1);
  9276. }
  9277. };
  9278. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  9279. var scene = this.getScene();
  9280. this._batchCache.mustReturn = false;
  9281. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  9282. this._batchCache.visibleInstances[subMeshId] = null;
  9283. if (this._visibleInstances) {
  9284. var currentRenderId = scene.getRenderId();
  9285. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  9286. var selfRenderId = this._renderId;
  9287. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  9288. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  9289. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  9290. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  9291. }
  9292. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  9293. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  9294. this._batchCache.mustReturn = true;
  9295. return this._batchCache;
  9296. }
  9297. if (currentRenderId !== selfRenderId) {
  9298. this._batchCache.renderSelf[subMeshId] = false;
  9299. }
  9300. }
  9301. this._renderIdForInstances[subMeshId] = currentRenderId;
  9302. }
  9303. return this._batchCache;
  9304. };
  9305. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  9306. var visibleInstances = batch.visibleInstances[subMesh._id];
  9307. var matricesCount = visibleInstances.length + 1;
  9308. var bufferSize = matricesCount * 16 * 4;
  9309. while (this._instancesBufferSize < bufferSize) {
  9310. this._instancesBufferSize *= 2;
  9311. }
  9312. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  9313. if (this._worldMatricesInstancesBuffer) {
  9314. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  9315. }
  9316. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  9317. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  9318. }
  9319. var offset = 0;
  9320. var instancesCount = 0;
  9321. var world = this.getWorldMatrix();
  9322. if (batch.renderSelf[subMesh._id]) {
  9323. world.copyToArray(this._worldMatricesInstancesArray, offset);
  9324. offset += 16;
  9325. instancesCount++;
  9326. }
  9327. if (visibleInstances) {
  9328. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  9329. var instance = visibleInstances[instanceIndex];
  9330. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  9331. offset += 16;
  9332. instancesCount++;
  9333. }
  9334. }
  9335. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  9336. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  9337. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  9338. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  9339. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  9340. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  9341. this._draw(subMesh, fillMode, instancesCount);
  9342. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  9343. };
  9344. Mesh.prototype.render = function (subMesh) {
  9345. var scene = this.getScene();
  9346. // Managing instances
  9347. var batch = this._getInstancesRenderList(subMesh._id);
  9348. if (batch.mustReturn) {
  9349. return;
  9350. }
  9351. // Checking geometry state
  9352. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  9353. return;
  9354. }
  9355. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  9356. this._onBeforeRenderCallbacks[callbackIndex]();
  9357. }
  9358. var engine = scene.getEngine();
  9359. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  9360. // Material
  9361. var effectiveMaterial = subMesh.getMaterial();
  9362. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  9363. return;
  9364. }
  9365. // Outline - step 1
  9366. var savedDepthWrite = engine.getDepthWrite();
  9367. if (this.renderOutline) {
  9368. engine.setDepthWrite(false);
  9369. scene.getOutlineRenderer().render(subMesh, batch);
  9370. engine.setDepthWrite(savedDepthWrite);
  9371. }
  9372. effectiveMaterial._preBind();
  9373. var effect = effectiveMaterial.getEffect();
  9374. // Bind
  9375. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  9376. this._bind(subMesh, effect, fillMode);
  9377. var world = this.getWorldMatrix();
  9378. effectiveMaterial.bind(world, this);
  9379. // Instances rendering
  9380. if (hardwareInstancedRendering) {
  9381. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  9382. } else {
  9383. if (batch.renderSelf[subMesh._id]) {
  9384. // Draw
  9385. this._draw(subMesh, fillMode);
  9386. }
  9387. if (batch.visibleInstances[subMesh._id]) {
  9388. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  9389. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  9390. // World
  9391. world = instance.getWorldMatrix();
  9392. effectiveMaterial.bindOnlyWorldMatrix(world);
  9393. // Draw
  9394. this._draw(subMesh, fillMode);
  9395. }
  9396. }
  9397. }
  9398. // Unbind
  9399. effectiveMaterial.unbind();
  9400. // Outline - step 2
  9401. if (this.renderOutline && savedDepthWrite) {
  9402. engine.setDepthWrite(true);
  9403. engine.setColorWrite(false);
  9404. scene.getOutlineRenderer().render(subMesh, batch);
  9405. engine.setColorWrite(true);
  9406. }
  9407. // Overlay
  9408. if (this.renderOverlay) {
  9409. var currentMode = engine.getAlphaMode();
  9410. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  9411. scene.getOutlineRenderer().render(subMesh, batch, true);
  9412. engine.setAlphaMode(currentMode);
  9413. }
  9414. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  9415. this._onAfterRenderCallbacks[callbackIndex]();
  9416. }
  9417. };
  9418. Mesh.prototype.getEmittedParticleSystems = function () {
  9419. var results = new Array();
  9420. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  9421. var particleSystem = this.getScene().particleSystems[index];
  9422. if (particleSystem.emitter === this) {
  9423. results.push(particleSystem);
  9424. }
  9425. }
  9426. return results;
  9427. };
  9428. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  9429. var results = new Array();
  9430. var descendants = this.getDescendants();
  9431. descendants.push(this);
  9432. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  9433. var particleSystem = this.getScene().particleSystems[index];
  9434. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  9435. results.push(particleSystem);
  9436. }
  9437. }
  9438. return results;
  9439. };
  9440. Mesh.prototype.getChildren = function () {
  9441. var results = [];
  9442. for (var index = 0; index < this.getScene().meshes.length; index++) {
  9443. var mesh = this.getScene().meshes[index];
  9444. if (mesh.parent == this) {
  9445. results.push(mesh);
  9446. }
  9447. }
  9448. return results;
  9449. };
  9450. Mesh.prototype._checkDelayState = function () {
  9451. var _this = this;
  9452. var that = this;
  9453. var scene = this.getScene();
  9454. if (this._geometry) {
  9455. this._geometry.load(scene);
  9456. } else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  9457. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  9458. scene._addPendingData(that);
  9459. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1) ? true : false;
  9460. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  9461. if (data instanceof ArrayBuffer) {
  9462. _this._delayLoadingFunction(data, _this);
  9463. } else {
  9464. _this._delayLoadingFunction(JSON.parse(data), _this);
  9465. }
  9466. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  9467. scene._removePendingData(_this);
  9468. }, function () {
  9469. }, scene.database, getBinaryData);
  9470. }
  9471. };
  9472. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  9473. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  9474. return false;
  9475. }
  9476. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  9477. return false;
  9478. }
  9479. this._checkDelayState();
  9480. return true;
  9481. };
  9482. Mesh.prototype.setMaterialByID = function (id) {
  9483. var materials = this.getScene().materials;
  9484. for (var index = 0; index < materials.length; index++) {
  9485. if (materials[index].id == id) {
  9486. this.material = materials[index];
  9487. return;
  9488. }
  9489. }
  9490. // Multi
  9491. var multiMaterials = this.getScene().multiMaterials;
  9492. for (index = 0; index < multiMaterials.length; index++) {
  9493. if (multiMaterials[index].id == id) {
  9494. this.material = multiMaterials[index];
  9495. return;
  9496. }
  9497. }
  9498. };
  9499. Mesh.prototype.getAnimatables = function () {
  9500. var results = [];
  9501. if (this.material) {
  9502. results.push(this.material);
  9503. }
  9504. if (this.skeleton) {
  9505. results.push(this.skeleton);
  9506. }
  9507. return results;
  9508. };
  9509. // Geometry
  9510. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  9511. // Position
  9512. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  9513. return;
  9514. }
  9515. this._resetPointsArrayCache();
  9516. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  9517. var temp = [];
  9518. for (var index = 0; index < data.length; index += 3) {
  9519. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  9520. }
  9521. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  9522. // Normals
  9523. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  9524. return;
  9525. }
  9526. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  9527. for (index = 0; index < data.length; index += 3) {
  9528. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  9529. }
  9530. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  9531. };
  9532. // Cache
  9533. Mesh.prototype._resetPointsArrayCache = function () {
  9534. this._positions = null;
  9535. };
  9536. Mesh.prototype._generatePointsArray = function () {
  9537. if (this._positions)
  9538. return true;
  9539. this._positions = [];
  9540. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  9541. if (!data) {
  9542. return false;
  9543. }
  9544. for (var index = 0; index < data.length; index += 3) {
  9545. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  9546. }
  9547. return true;
  9548. };
  9549. // Clone
  9550. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  9551. var result = new BABYLON.Mesh(name, this.getScene());
  9552. // Geometry
  9553. if (this._geometry) {
  9554. this._geometry.applyToMesh(result);
  9555. }
  9556. // Deep copy
  9557. BABYLON.Tools.DeepCopy(this, result, ["name", "material", "skeleton"], []);
  9558. // Material
  9559. result.material = this.material;
  9560. // Parent
  9561. if (newParent) {
  9562. result.parent = newParent;
  9563. }
  9564. if (!doNotCloneChildren) {
  9565. for (var index = 0; index < this.getScene().meshes.length; index++) {
  9566. var mesh = this.getScene().meshes[index];
  9567. if (mesh.parent == this) {
  9568. mesh.clone(mesh.name, result);
  9569. }
  9570. }
  9571. }
  9572. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  9573. var system = this.getScene().particleSystems[index];
  9574. if (system.emitter == this) {
  9575. system.clone(system.name, result);
  9576. }
  9577. }
  9578. result.computeWorldMatrix(true);
  9579. return result;
  9580. };
  9581. // Dispose
  9582. Mesh.prototype.dispose = function (doNotRecurse) {
  9583. if (this._geometry) {
  9584. this._geometry.releaseForMesh(this, true);
  9585. }
  9586. // Instances
  9587. if (this._worldMatricesInstancesBuffer) {
  9588. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  9589. this._worldMatricesInstancesBuffer = null;
  9590. }
  9591. while (this.instances.length) {
  9592. this.instances[0].dispose();
  9593. }
  9594. _super.prototype.dispose.call(this, doNotRecurse);
  9595. };
  9596. // Geometric tools
  9597. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight) {
  9598. var _this = this;
  9599. var scene = this.getScene();
  9600. var onload = function (img) {
  9601. // Getting height map data
  9602. var canvas = document.createElement("canvas");
  9603. var context = canvas.getContext("2d");
  9604. var heightMapWidth = img.width;
  9605. var heightMapHeight = img.height;
  9606. canvas.width = heightMapWidth;
  9607. canvas.height = heightMapHeight;
  9608. context.drawImage(img, 0, 0);
  9609. // Create VertexData from map data
  9610. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  9611. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  9612. };
  9613. BABYLON.Tools.LoadImage(url, onload, function () {
  9614. }, scene.database);
  9615. };
  9616. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  9617. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  9618. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  9619. return;
  9620. }
  9621. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  9622. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  9623. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  9624. var position = BABYLON.Vector3.Zero();
  9625. var normal = BABYLON.Vector3.Zero();
  9626. var uv = BABYLON.Vector2.Zero();
  9627. for (var index = 0; index < positions.length; index += 3) {
  9628. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  9629. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  9630. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  9631. // Compute height
  9632. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  9633. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  9634. var pos = (u + v * heightMapWidth) * 4;
  9635. var r = buffer[pos] / 255.0;
  9636. var g = buffer[pos + 1] / 255.0;
  9637. var b = buffer[pos + 2] / 255.0;
  9638. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  9639. normal.normalize();
  9640. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  9641. position = position.add(normal);
  9642. position.toArray(positions, index);
  9643. }
  9644. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  9645. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  9646. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  9647. };
  9648. Mesh.prototype.convertToFlatShadedMesh = function () {
  9649. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  9650. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  9651. var kinds = this.getVerticesDataKinds();
  9652. var vbs = [];
  9653. var data = [];
  9654. var newdata = [];
  9655. var updatableNormals = false;
  9656. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  9657. var kind = kinds[kindIndex];
  9658. var vertexBuffer = this.getVertexBuffer(kind);
  9659. if (kind === BABYLON.VertexBuffer.NormalKind) {
  9660. updatableNormals = vertexBuffer.isUpdatable();
  9661. kinds.splice(kindIndex, 1);
  9662. kindIndex--;
  9663. continue;
  9664. }
  9665. vbs[kind] = vertexBuffer;
  9666. data[kind] = vbs[kind].getData();
  9667. newdata[kind] = [];
  9668. }
  9669. // Save previous submeshes
  9670. var previousSubmeshes = this.subMeshes.slice(0);
  9671. var indices = this.getIndices();
  9672. var totalIndices = this.getTotalIndices();
  9673. for (index = 0; index < totalIndices; index++) {
  9674. var vertexIndex = indices[index];
  9675. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  9676. kind = kinds[kindIndex];
  9677. var stride = vbs[kind].getStrideSize();
  9678. for (var offset = 0; offset < stride; offset++) {
  9679. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  9680. }
  9681. }
  9682. }
  9683. // Updating faces & normal
  9684. var normals = [];
  9685. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  9686. for (var index = 0; index < totalIndices; index += 3) {
  9687. indices[index] = index;
  9688. indices[index + 1] = index + 1;
  9689. indices[index + 2] = index + 2;
  9690. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  9691. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  9692. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  9693. var p1p2 = p1.subtract(p2);
  9694. var p3p2 = p3.subtract(p2);
  9695. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  9696. for (var localIndex = 0; localIndex < 3; localIndex++) {
  9697. normals.push(normal.x);
  9698. normals.push(normal.y);
  9699. normals.push(normal.z);
  9700. }
  9701. }
  9702. this.setIndices(indices);
  9703. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  9704. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  9705. kind = kinds[kindIndex];
  9706. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  9707. }
  9708. // Updating submeshes
  9709. this.releaseSubMeshes();
  9710. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  9711. var previousOne = previousSubmeshes[submeshIndex];
  9712. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  9713. }
  9714. this.synchronizeInstances();
  9715. };
  9716. // Instances
  9717. Mesh.prototype.createInstance = function (name) {
  9718. return new BABYLON.InstancedMesh(name, this);
  9719. };
  9720. Mesh.prototype.synchronizeInstances = function () {
  9721. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  9722. var instance = this.instances[instanceIndex];
  9723. instance._syncSubMeshes();
  9724. }
  9725. };
  9726. // Statics
  9727. Mesh.CreateBox = function (name, size, scene, updatable) {
  9728. var box = new BABYLON.Mesh(name, scene);
  9729. var vertexData = BABYLON.VertexData.CreateBox(size);
  9730. vertexData.applyToMesh(box, updatable);
  9731. return box;
  9732. };
  9733. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable) {
  9734. var sphere = new BABYLON.Mesh(name, scene);
  9735. var vertexData = BABYLON.VertexData.CreateSphere(segments, diameter);
  9736. vertexData.applyToMesh(sphere, updatable);
  9737. return sphere;
  9738. };
  9739. // Cylinder and cone (Code inspired by SharpDX.org)
  9740. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable) {
  9741. // subdivisions is a new parameter, we need to support old signature
  9742. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  9743. if (scene !== undefined) {
  9744. updatable = scene;
  9745. }
  9746. scene = subdivisions;
  9747. subdivisions = 1;
  9748. }
  9749. var cylinder = new BABYLON.Mesh(name, scene);
  9750. var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions);
  9751. vertexData.applyToMesh(cylinder, updatable);
  9752. return cylinder;
  9753. };
  9754. // Torus (Code from SharpDX.org)
  9755. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable) {
  9756. var torus = new BABYLON.Mesh(name, scene);
  9757. var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation);
  9758. vertexData.applyToMesh(torus, updatable);
  9759. return torus;
  9760. };
  9761. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable) {
  9762. var torusKnot = new BABYLON.Mesh(name, scene);
  9763. var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q);
  9764. vertexData.applyToMesh(torusKnot, updatable);
  9765. return torusKnot;
  9766. };
  9767. // Lines
  9768. Mesh.CreateLines = function (name, points, scene, updatable) {
  9769. var lines = new BABYLON.LinesMesh(name, scene, updatable);
  9770. var vertexData = BABYLON.VertexData.CreateLines(points);
  9771. vertexData.applyToMesh(lines, updatable);
  9772. return lines;
  9773. };
  9774. // Plane & ground
  9775. Mesh.CreatePlane = function (name, size, scene, updatable) {
  9776. var plane = new BABYLON.Mesh(name, scene);
  9777. var vertexData = BABYLON.VertexData.CreatePlane(size);
  9778. vertexData.applyToMesh(plane, updatable);
  9779. return plane;
  9780. };
  9781. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  9782. var ground = new BABYLON.GroundMesh(name, scene);
  9783. ground._setReady(false);
  9784. ground._subdivisions = subdivisions;
  9785. var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
  9786. vertexData.applyToMesh(ground, updatable);
  9787. ground._setReady(true);
  9788. return ground;
  9789. };
  9790. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  9791. var tiledGround = new BABYLON.Mesh(name, scene);
  9792. var vertexData = BABYLON.VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  9793. vertexData.applyToMesh(tiledGround, updatable);
  9794. return tiledGround;
  9795. };
  9796. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable) {
  9797. var ground = new BABYLON.GroundMesh(name, scene);
  9798. ground._subdivisions = subdivisions;
  9799. ground._setReady(false);
  9800. var onload = function (img) {
  9801. // Getting height map data
  9802. var canvas = document.createElement("canvas");
  9803. var context = canvas.getContext("2d");
  9804. var heightMapWidth = img.width;
  9805. var heightMapHeight = img.height;
  9806. canvas.width = heightMapWidth;
  9807. canvas.height = heightMapHeight;
  9808. context.drawImage(img, 0, 0);
  9809. // Create VertexData from map data
  9810. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  9811. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  9812. vertexData.applyToMesh(ground, updatable);
  9813. ground._setReady(true);
  9814. };
  9815. BABYLON.Tools.LoadImage(url, onload, function () {
  9816. }, scene.database);
  9817. return ground;
  9818. };
  9819. // Tools
  9820. Mesh.MinMax = function (meshes) {
  9821. var minVector = null;
  9822. var maxVector = null;
  9823. for (var i in meshes) {
  9824. var mesh = meshes[i];
  9825. var boundingBox = mesh.getBoundingInfo().boundingBox;
  9826. if (!minVector) {
  9827. minVector = boundingBox.minimumWorld;
  9828. maxVector = boundingBox.maximumWorld;
  9829. continue;
  9830. }
  9831. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  9832. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  9833. }
  9834. return {
  9835. min: minVector,
  9836. max: maxVector
  9837. };
  9838. };
  9839. Mesh.Center = function (meshesOrMinMaxVector) {
  9840. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  9841. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  9842. };
  9843. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices) {
  9844. if (typeof disposeSource === "undefined") { disposeSource = true; }
  9845. var source = meshes[0];
  9846. var material = source.material;
  9847. var scene = source.getScene();
  9848. if (!allow32BitsIndices) {
  9849. var totalVertices = 0;
  9850. for (var index = 0; index < meshes.length; index++) {
  9851. totalVertices += meshes[index].getTotalVertices();
  9852. if (totalVertices > 65536) {
  9853. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  9854. return null;
  9855. }
  9856. }
  9857. }
  9858. // Merge
  9859. var vertexData = BABYLON.VertexData.ExtractFromMesh(source);
  9860. vertexData.transform(source.getWorldMatrix());
  9861. for (index = 1; index < meshes.length; index++) {
  9862. var otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index]);
  9863. otherVertexData.transform(meshes[index].getWorldMatrix());
  9864. vertexData.merge(otherVertexData);
  9865. }
  9866. var newMesh = new Mesh(source.name + "_merged", scene);
  9867. vertexData.applyToMesh(newMesh);
  9868. // Setting properties
  9869. newMesh.material = material;
  9870. newMesh.checkCollisions = source.checkCollisions;
  9871. // Cleaning
  9872. if (disposeSource) {
  9873. for (index = 0; index < meshes.length; index++) {
  9874. meshes[index].dispose();
  9875. }
  9876. }
  9877. return newMesh;
  9878. };
  9879. return Mesh;
  9880. })(BABYLON.AbstractMesh);
  9881. BABYLON.Mesh = Mesh;
  9882. })(BABYLON || (BABYLON = {}));
  9883. //# sourceMappingURL=babylon.mesh.js.map
  9884. var BABYLON;
  9885. (function (BABYLON) {
  9886. var GroundMesh = (function (_super) {
  9887. __extends(GroundMesh, _super);
  9888. function GroundMesh(name, scene) {
  9889. _super.call(this, name, scene);
  9890. this.generateOctree = false;
  9891. this._worldInverse = new BABYLON.Matrix();
  9892. }
  9893. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  9894. get: function () {
  9895. return this._subdivisions;
  9896. },
  9897. enumerable: true,
  9898. configurable: true
  9899. });
  9900. GroundMesh.prototype.optimize = function (chunksCount) {
  9901. this.subdivide(this._subdivisions);
  9902. this.createOrUpdateSubmeshesOctree(32);
  9903. };
  9904. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  9905. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  9906. this.getWorldMatrix().invertToRef(this._worldInverse);
  9907. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  9908. var pickInfo = this.intersects(ray);
  9909. if (pickInfo.hit) {
  9910. return pickInfo.pickedPoint.y;
  9911. }
  9912. return 0;
  9913. };
  9914. return GroundMesh;
  9915. })(BABYLON.Mesh);
  9916. BABYLON.GroundMesh = GroundMesh;
  9917. })(BABYLON || (BABYLON = {}));
  9918. //# sourceMappingURL=babylon.groundMesh.js.map
  9919. var BABYLON;
  9920. (function (BABYLON) {
  9921. var InstancedMesh = (function (_super) {
  9922. __extends(InstancedMesh, _super);
  9923. function InstancedMesh(name, source) {
  9924. _super.call(this, name, source.getScene());
  9925. source.instances.push(this);
  9926. this._sourceMesh = source;
  9927. this.position.copyFrom(source.position);
  9928. this.rotation.copyFrom(source.rotation);
  9929. this.scaling.copyFrom(source.scaling);
  9930. if (source.rotationQuaternion) {
  9931. this.rotationQuaternion = source.rotationQuaternion.clone();
  9932. }
  9933. this.infiniteDistance = source.infiniteDistance;
  9934. this.setPivotMatrix(source.getPivotMatrix());
  9935. this.refreshBoundingInfo();
  9936. this._syncSubMeshes();
  9937. }
  9938. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  9939. // Methods
  9940. get: function () {
  9941. return this._sourceMesh.receiveShadows;
  9942. },
  9943. enumerable: true,
  9944. configurable: true
  9945. });
  9946. Object.defineProperty(InstancedMesh.prototype, "material", {
  9947. get: function () {
  9948. return this._sourceMesh.material;
  9949. },
  9950. enumerable: true,
  9951. configurable: true
  9952. });
  9953. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  9954. get: function () {
  9955. return this._sourceMesh.visibility;
  9956. },
  9957. enumerable: true,
  9958. configurable: true
  9959. });
  9960. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  9961. get: function () {
  9962. return this._sourceMesh.skeleton;
  9963. },
  9964. enumerable: true,
  9965. configurable: true
  9966. });
  9967. InstancedMesh.prototype.getTotalVertices = function () {
  9968. return this._sourceMesh.getTotalVertices();
  9969. };
  9970. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  9971. get: function () {
  9972. return this._sourceMesh;
  9973. },
  9974. enumerable: true,
  9975. configurable: true
  9976. });
  9977. InstancedMesh.prototype.getVerticesData = function (kind) {
  9978. return this._sourceMesh.getVerticesData(kind);
  9979. };
  9980. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  9981. return this._sourceMesh.isVerticesDataPresent(kind);
  9982. };
  9983. InstancedMesh.prototype.getIndices = function () {
  9984. return this._sourceMesh.getIndices();
  9985. };
  9986. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  9987. get: function () {
  9988. return this._sourceMesh._positions;
  9989. },
  9990. enumerable: true,
  9991. configurable: true
  9992. });
  9993. InstancedMesh.prototype.refreshBoundingInfo = function () {
  9994. var data = this._sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  9995. if (data) {
  9996. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._sourceMesh.getTotalVertices());
  9997. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  9998. }
  9999. this._updateBoundingInfo();
  10000. };
  10001. InstancedMesh.prototype._preActivate = function () {
  10002. if (this._currentLOD) {
  10003. this._currentLOD._preActivate();
  10004. }
  10005. };
  10006. InstancedMesh.prototype._activate = function (renderId) {
  10007. if (this._currentLOD) {
  10008. this._currentLOD._registerInstanceForRenderId(this, renderId);
  10009. }
  10010. };
  10011. InstancedMesh.prototype.getLOD = function (camera) {
  10012. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  10013. return this._currentLOD;
  10014. };
  10015. InstancedMesh.prototype._syncSubMeshes = function () {
  10016. this.releaseSubMeshes();
  10017. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  10018. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  10019. }
  10020. };
  10021. InstancedMesh.prototype._generatePointsArray = function () {
  10022. return this._sourceMesh._generatePointsArray();
  10023. };
  10024. // Clone
  10025. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  10026. var result = this._sourceMesh.createInstance(name);
  10027. // Deep copy
  10028. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  10029. // Bounding info
  10030. this.refreshBoundingInfo();
  10031. // Parent
  10032. if (newParent) {
  10033. result.parent = newParent;
  10034. }
  10035. if (!doNotCloneChildren) {
  10036. for (var index = 0; index < this.getScene().meshes.length; index++) {
  10037. var mesh = this.getScene().meshes[index];
  10038. if (mesh.parent == this) {
  10039. mesh.clone(mesh.name, result);
  10040. }
  10041. }
  10042. }
  10043. result.computeWorldMatrix(true);
  10044. return result;
  10045. };
  10046. // Dispoe
  10047. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  10048. // Remove from mesh
  10049. var index = this._sourceMesh.instances.indexOf(this);
  10050. this._sourceMesh.instances.splice(index, 1);
  10051. _super.prototype.dispose.call(this, doNotRecurse);
  10052. };
  10053. return InstancedMesh;
  10054. })(BABYLON.AbstractMesh);
  10055. BABYLON.InstancedMesh = InstancedMesh;
  10056. })(BABYLON || (BABYLON = {}));
  10057. //# sourceMappingURL=babylon.instancedMesh.js.map
  10058. var BABYLON;
  10059. (function (BABYLON) {
  10060. var SubMesh = (function () {
  10061. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  10062. if (typeof createBoundingBox === "undefined") { createBoundingBox = true; }
  10063. this.materialIndex = materialIndex;
  10064. this.verticesStart = verticesStart;
  10065. this.verticesCount = verticesCount;
  10066. this.indexStart = indexStart;
  10067. this.indexCount = indexCount;
  10068. this._renderId = 0;
  10069. this._mesh = mesh;
  10070. this._renderingMesh = renderingMesh || mesh;
  10071. mesh.subMeshes.push(this);
  10072. this._id = mesh.subMeshes.length - 1;
  10073. if (createBoundingBox) {
  10074. this.refreshBoundingInfo();
  10075. }
  10076. }
  10077. SubMesh.prototype.getBoundingInfo = function () {
  10078. return this._boundingInfo;
  10079. };
  10080. SubMesh.prototype.getMesh = function () {
  10081. return this._mesh;
  10082. };
  10083. SubMesh.prototype.getRenderingMesh = function () {
  10084. return this._renderingMesh;
  10085. };
  10086. SubMesh.prototype.getMaterial = function () {
  10087. var rootMaterial = this._renderingMesh.material;
  10088. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  10089. var multiMaterial = rootMaterial;
  10090. return multiMaterial.getSubMaterial(this.materialIndex);
  10091. }
  10092. if (!rootMaterial) {
  10093. return this._mesh.getScene().defaultMaterial;
  10094. }
  10095. return rootMaterial;
  10096. };
  10097. // Methods
  10098. SubMesh.prototype.refreshBoundingInfo = function () {
  10099. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  10100. if (!data) {
  10101. this._boundingInfo = this._mesh._boundingInfo;
  10102. return;
  10103. }
  10104. var indices = this._renderingMesh.getIndices();
  10105. var extend;
  10106. if (this.indexStart === 0 && this.indexCount === indices.length) {
  10107. extend = BABYLON.Tools.ExtractMinAndMax(data, this.verticesStart, this.verticesCount);
  10108. } else {
  10109. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  10110. }
  10111. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  10112. };
  10113. SubMesh.prototype._checkCollision = function (collider) {
  10114. return this._boundingInfo._checkCollision(collider);
  10115. };
  10116. SubMesh.prototype.updateBoundingInfo = function (world) {
  10117. if (!this._boundingInfo) {
  10118. this.refreshBoundingInfo();
  10119. }
  10120. this._boundingInfo._update(world);
  10121. };
  10122. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  10123. return this._boundingInfo.isInFrustum(frustumPlanes);
  10124. };
  10125. SubMesh.prototype.render = function () {
  10126. this._renderingMesh.render(this);
  10127. };
  10128. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  10129. if (!this._linesIndexBuffer) {
  10130. var linesIndices = [];
  10131. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  10132. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  10133. }
  10134. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  10135. this.linesIndexCount = linesIndices.length;
  10136. }
  10137. return this._linesIndexBuffer;
  10138. };
  10139. SubMesh.prototype.canIntersects = function (ray) {
  10140. return ray.intersectsBox(this._boundingInfo.boundingBox);
  10141. };
  10142. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  10143. var intersectInfo = null;
  10144. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  10145. var p0 = positions[indices[index]];
  10146. var p1 = positions[indices[index + 1]];
  10147. var p2 = positions[indices[index + 2]];
  10148. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  10149. if (currentIntersectInfo) {
  10150. if (currentIntersectInfo.distance < 0) {
  10151. continue;
  10152. }
  10153. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  10154. intersectInfo = currentIntersectInfo;
  10155. intersectInfo.faceId = index / 3;
  10156. if (fastCheck) {
  10157. break;
  10158. }
  10159. }
  10160. }
  10161. }
  10162. return intersectInfo;
  10163. };
  10164. // Clone
  10165. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  10166. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  10167. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  10168. return result;
  10169. };
  10170. // Dispose
  10171. SubMesh.prototype.dispose = function () {
  10172. if (this._linesIndexBuffer) {
  10173. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  10174. this._linesIndexBuffer = null;
  10175. }
  10176. // Remove from mesh
  10177. var index = this._mesh.subMeshes.indexOf(this);
  10178. this._mesh.subMeshes.splice(index, 1);
  10179. };
  10180. // Statics
  10181. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  10182. var minVertexIndex = Number.MAX_VALUE;
  10183. var maxVertexIndex = -Number.MAX_VALUE;
  10184. renderingMesh = renderingMesh || mesh;
  10185. var indices = renderingMesh.getIndices();
  10186. for (var index = startIndex; index < startIndex + indexCount; index++) {
  10187. var vertexIndex = indices[index];
  10188. if (vertexIndex < minVertexIndex)
  10189. minVertexIndex = vertexIndex;
  10190. if (vertexIndex > maxVertexIndex)
  10191. maxVertexIndex = vertexIndex;
  10192. }
  10193. return new BABYLON.SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  10194. };
  10195. return SubMesh;
  10196. })();
  10197. BABYLON.SubMesh = SubMesh;
  10198. })(BABYLON || (BABYLON = {}));
  10199. //# sourceMappingURL=babylon.subMesh.js.map
  10200. var BABYLON;
  10201. (function (BABYLON) {
  10202. var BaseTexture = (function () {
  10203. function BaseTexture(scene) {
  10204. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  10205. this.hasAlpha = false;
  10206. this.getAlphaFromRGB = false;
  10207. this.level = 1;
  10208. this.isCube = false;
  10209. this.isRenderTarget = false;
  10210. this.animations = new Array();
  10211. this.coordinatesIndex = 0;
  10212. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  10213. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  10214. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  10215. this.anisotropicFilteringLevel = 4;
  10216. this._scene = scene;
  10217. this._scene.textures.push(this);
  10218. }
  10219. BaseTexture.prototype.getScene = function () {
  10220. return this._scene;
  10221. };
  10222. BaseTexture.prototype.getTextureMatrix = function () {
  10223. return null;
  10224. };
  10225. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  10226. return null;
  10227. };
  10228. BaseTexture.prototype.getInternalTexture = function () {
  10229. return this._texture;
  10230. };
  10231. BaseTexture.prototype.isReady = function () {
  10232. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  10233. return true;
  10234. }
  10235. if (this._texture) {
  10236. return this._texture.isReady;
  10237. }
  10238. return false;
  10239. };
  10240. BaseTexture.prototype.getSize = function () {
  10241. if (this._texture._width) {
  10242. return { width: this._texture._width, height: this._texture._height };
  10243. }
  10244. if (this._texture._size) {
  10245. return { width: this._texture._size, height: this._texture._size };
  10246. }
  10247. return { width: 0, height: 0 };
  10248. };
  10249. BaseTexture.prototype.getBaseSize = function () {
  10250. if (!this.isReady())
  10251. return { width: 0, height: 0 };
  10252. if (this._texture._size) {
  10253. return { width: this._texture._size, height: this._texture._size };
  10254. }
  10255. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  10256. };
  10257. BaseTexture.prototype.scale = function (ratio) {
  10258. };
  10259. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  10260. get: function () {
  10261. return false;
  10262. },
  10263. enumerable: true,
  10264. configurable: true
  10265. });
  10266. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  10267. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  10268. for (var index = 0; index < texturesCache.length; index++) {
  10269. var texturesCacheEntry = texturesCache[index];
  10270. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  10271. texturesCache.splice(index, 1);
  10272. return;
  10273. }
  10274. }
  10275. };
  10276. BaseTexture.prototype._getFromCache = function (url, noMipmap) {
  10277. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  10278. for (var index = 0; index < texturesCache.length; index++) {
  10279. var texturesCacheEntry = texturesCache[index];
  10280. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  10281. texturesCacheEntry.references++;
  10282. return texturesCacheEntry;
  10283. }
  10284. }
  10285. return null;
  10286. };
  10287. BaseTexture.prototype.delayLoad = function () {
  10288. };
  10289. BaseTexture.prototype.releaseInternalTexture = function () {
  10290. if (!this._texture) {
  10291. return;
  10292. }
  10293. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  10294. this._texture.references--;
  10295. // Final reference ?
  10296. if (this._texture.references === 0) {
  10297. var index = texturesCache.indexOf(this._texture);
  10298. texturesCache.splice(index, 1);
  10299. this._scene.getEngine()._releaseTexture(this._texture);
  10300. delete this._texture;
  10301. }
  10302. };
  10303. BaseTexture.prototype.clone = function () {
  10304. return null;
  10305. };
  10306. BaseTexture.prototype.dispose = function () {
  10307. // Remove from scene
  10308. var index = this._scene.textures.indexOf(this);
  10309. if (index >= 0) {
  10310. this._scene.textures.splice(index, 1);
  10311. }
  10312. if (this._texture === undefined) {
  10313. return;
  10314. }
  10315. this.releaseInternalTexture();
  10316. // Callback
  10317. if (this.onDispose) {
  10318. this.onDispose();
  10319. }
  10320. };
  10321. return BaseTexture;
  10322. })();
  10323. BABYLON.BaseTexture = BaseTexture;
  10324. })(BABYLON || (BABYLON = {}));
  10325. //# sourceMappingURL=babylon.baseTexture.js.map
  10326. var BABYLON;
  10327. (function (BABYLON) {
  10328. var RenderingGroup = (function () {
  10329. function RenderingGroup(index, scene) {
  10330. this.index = index;
  10331. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  10332. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  10333. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  10334. this._scene = scene;
  10335. }
  10336. RenderingGroup.prototype.render = function (customRenderFunction) {
  10337. if (customRenderFunction) {
  10338. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  10339. return true;
  10340. }
  10341. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  10342. return false;
  10343. }
  10344. var engine = this._scene.getEngine();
  10345. // Opaque
  10346. var subIndex;
  10347. var submesh;
  10348. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  10349. submesh = this._opaqueSubMeshes.data[subIndex];
  10350. submesh.render();
  10351. }
  10352. // Alpha test
  10353. engine.setAlphaTesting(true);
  10354. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  10355. submesh = this._alphaTestSubMeshes.data[subIndex];
  10356. submesh.render();
  10357. }
  10358. engine.setAlphaTesting(false);
  10359. // Transparent
  10360. if (this._transparentSubMeshes.length) {
  10361. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  10362. submesh = this._transparentSubMeshes.data[subIndex];
  10363. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  10364. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.position).length();
  10365. }
  10366. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  10367. sortedArray.sort(function (a, b) {
  10368. // Alpha index first
  10369. if (a._alphaIndex > b._alphaIndex) {
  10370. return 1;
  10371. }
  10372. if (a._alphaIndex < b._alphaIndex) {
  10373. return -1;
  10374. }
  10375. // Then distance to camera
  10376. if (a._distanceToCamera < b._distanceToCamera) {
  10377. return 1;
  10378. }
  10379. if (a._distanceToCamera > b._distanceToCamera) {
  10380. return -1;
  10381. }
  10382. return 0;
  10383. });
  10384. // Rendering
  10385. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  10386. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  10387. submesh = sortedArray[subIndex];
  10388. submesh.render();
  10389. }
  10390. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  10391. }
  10392. return true;
  10393. };
  10394. RenderingGroup.prototype.prepare = function () {
  10395. this._opaqueSubMeshes.reset();
  10396. this._transparentSubMeshes.reset();
  10397. this._alphaTestSubMeshes.reset();
  10398. };
  10399. RenderingGroup.prototype.dispatch = function (subMesh) {
  10400. var material = subMesh.getMaterial();
  10401. var mesh = subMesh.getMesh();
  10402. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  10403. this._transparentSubMeshes.push(subMesh);
  10404. } else if (material.needAlphaTesting()) {
  10405. this._alphaTestSubMeshes.push(subMesh);
  10406. } else {
  10407. this._opaqueSubMeshes.push(subMesh); // Opaque
  10408. }
  10409. };
  10410. return RenderingGroup;
  10411. })();
  10412. BABYLON.RenderingGroup = RenderingGroup;
  10413. })(BABYLON || (BABYLON = {}));
  10414. //# sourceMappingURL=babylon.renderingGroup.js.map
  10415. var BABYLON;
  10416. (function (BABYLON) {
  10417. var RenderingManager = (function () {
  10418. function RenderingManager(scene) {
  10419. this._renderingGroups = new Array();
  10420. this._scene = scene;
  10421. }
  10422. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  10423. if (this._scene._activeParticleSystems.length === 0) {
  10424. return;
  10425. }
  10426. // Particles
  10427. var beforeParticlesDate = BABYLON.Tools.Now;
  10428. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  10429. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  10430. if (particleSystem.renderingGroupId !== index) {
  10431. continue;
  10432. }
  10433. this._clearDepthBuffer();
  10434. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  10435. this._scene._activeParticles += particleSystem.render();
  10436. }
  10437. }
  10438. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  10439. };
  10440. RenderingManager.prototype._renderSprites = function (index) {
  10441. if (this._scene.spriteManagers.length === 0) {
  10442. return;
  10443. }
  10444. // Sprites
  10445. var beforeSpritessDate = BABYLON.Tools.Now;
  10446. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  10447. var spriteManager = this._scene.spriteManagers[id];
  10448. if (spriteManager.renderingGroupId === index) {
  10449. this._clearDepthBuffer();
  10450. spriteManager.render();
  10451. }
  10452. }
  10453. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  10454. };
  10455. RenderingManager.prototype._clearDepthBuffer = function () {
  10456. if (this._depthBufferAlreadyCleaned) {
  10457. return;
  10458. }
  10459. this._scene.getEngine().clear(0, false, true);
  10460. this._depthBufferAlreadyCleaned = true;
  10461. };
  10462. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  10463. for (var index = 0; index < BABYLON.RenderingManager.MAX_RENDERINGGROUPS; index++) {
  10464. this._depthBufferAlreadyCleaned = false;
  10465. var renderingGroup = this._renderingGroups[index];
  10466. if (renderingGroup) {
  10467. this._clearDepthBuffer();
  10468. if (!renderingGroup.render(customRenderFunction)) {
  10469. this._renderingGroups.splice(index, 1);
  10470. }
  10471. }
  10472. this._renderSprites(index);
  10473. if (renderParticles) {
  10474. this._renderParticles(index, activeMeshes);
  10475. }
  10476. }
  10477. };
  10478. RenderingManager.prototype.reset = function () {
  10479. for (var index in this._renderingGroups) {
  10480. var renderingGroup = this._renderingGroups[index];
  10481. renderingGroup.prepare();
  10482. }
  10483. };
  10484. RenderingManager.prototype.dispatch = function (subMesh) {
  10485. var mesh = subMesh.getMesh();
  10486. var renderingGroupId = mesh.renderingGroupId || 0;
  10487. if (!this._renderingGroups[renderingGroupId]) {
  10488. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  10489. }
  10490. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  10491. };
  10492. RenderingManager.MAX_RENDERINGGROUPS = 4;
  10493. return RenderingManager;
  10494. })();
  10495. BABYLON.RenderingManager = RenderingManager;
  10496. })(BABYLON || (BABYLON = {}));
  10497. //# sourceMappingURL=babylon.renderingManager.js.map
  10498. var BABYLON;
  10499. (function (BABYLON) {
  10500. var Texture = (function (_super) {
  10501. __extends(Texture, _super);
  10502. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  10503. if (typeof samplingMode === "undefined") { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  10504. if (typeof onLoad === "undefined") { onLoad = null; }
  10505. if (typeof onError === "undefined") { onError = null; }
  10506. if (typeof buffer === "undefined") { buffer = null; }
  10507. if (typeof deleteBuffer === "undefined") { deleteBuffer = false; }
  10508. _super.call(this, scene);
  10509. this.uOffset = 0;
  10510. this.vOffset = 0;
  10511. this.uScale = 1.0;
  10512. this.vScale = 1.0;
  10513. this.uAng = 0;
  10514. this.vAng = 0;
  10515. this.wAng = 0;
  10516. this.name = url;
  10517. this.url = url;
  10518. this._noMipmap = noMipmap;
  10519. this._invertY = invertY;
  10520. this._samplingMode = samplingMode;
  10521. this._buffer = buffer;
  10522. this._deleteBuffer = deleteBuffer;
  10523. if (!url) {
  10524. return;
  10525. }
  10526. this._texture = this._getFromCache(url, noMipmap);
  10527. if (!this._texture) {
  10528. if (!scene.useDelayedTextureLoading) {
  10529. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  10530. if (deleteBuffer) {
  10531. delete this._buffer;
  10532. }
  10533. } else {
  10534. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  10535. }
  10536. }
  10537. }
  10538. Texture.prototype.delayLoad = function () {
  10539. if (this.delayLoadState != BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  10540. return;
  10541. }
  10542. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  10543. this._texture = this._getFromCache(this.url, this._noMipmap);
  10544. if (!this._texture) {
  10545. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  10546. if (this._deleteBuffer) {
  10547. delete this._buffer;
  10548. }
  10549. }
  10550. };
  10551. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  10552. x -= this.uOffset + 0.5;
  10553. y -= this.vOffset + 0.5;
  10554. z -= 0.5;
  10555. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  10556. t.x *= this.uScale;
  10557. t.y *= this.vScale;
  10558. t.x += 0.5;
  10559. t.y += 0.5;
  10560. t.z += 0.5;
  10561. };
  10562. Texture.prototype.getTextureMatrix = function () {
  10563. 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) {
  10564. return this._cachedTextureMatrix;
  10565. }
  10566. this._cachedUOffset = this.uOffset;
  10567. this._cachedVOffset = this.vOffset;
  10568. this._cachedUScale = this.uScale;
  10569. this._cachedVScale = this.vScale;
  10570. this._cachedUAng = this.uAng;
  10571. this._cachedVAng = this.vAng;
  10572. this._cachedWAng = this.wAng;
  10573. if (!this._cachedTextureMatrix) {
  10574. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  10575. this._rowGenerationMatrix = new BABYLON.Matrix();
  10576. this._t0 = BABYLON.Vector3.Zero();
  10577. this._t1 = BABYLON.Vector3.Zero();
  10578. this._t2 = BABYLON.Vector3.Zero();
  10579. }
  10580. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  10581. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  10582. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  10583. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  10584. this._t1.subtractInPlace(this._t0);
  10585. this._t2.subtractInPlace(this._t0);
  10586. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  10587. this._cachedTextureMatrix.m[0] = this._t1.x;
  10588. this._cachedTextureMatrix.m[1] = this._t1.y;
  10589. this._cachedTextureMatrix.m[2] = this._t1.z;
  10590. this._cachedTextureMatrix.m[4] = this._t2.x;
  10591. this._cachedTextureMatrix.m[5] = this._t2.y;
  10592. this._cachedTextureMatrix.m[6] = this._t2.z;
  10593. this._cachedTextureMatrix.m[8] = this._t0.x;
  10594. this._cachedTextureMatrix.m[9] = this._t0.y;
  10595. this._cachedTextureMatrix.m[10] = this._t0.z;
  10596. return this._cachedTextureMatrix;
  10597. };
  10598. Texture.prototype.getReflectionTextureMatrix = function () {
  10599. if (this.uOffset === this._cachedUOffset && this.vOffset === this._cachedVOffset && this.uScale === this._cachedUScale && this.vScale === this._cachedVScale && this.coordinatesMode === this._cachedCoordinatesMode) {
  10600. return this._cachedTextureMatrix;
  10601. }
  10602. if (!this._cachedTextureMatrix) {
  10603. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  10604. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  10605. }
  10606. this._cachedCoordinatesMode = this.coordinatesMode;
  10607. switch (this.coordinatesMode) {
  10608. case BABYLON.Texture.SPHERICAL_MODE:
  10609. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  10610. this._cachedTextureMatrix[0] = -0.5 * this.uScale;
  10611. this._cachedTextureMatrix[5] = -0.5 * this.vScale;
  10612. this._cachedTextureMatrix[12] = 0.5 + this.uOffset;
  10613. this._cachedTextureMatrix[13] = 0.5 + this.vOffset;
  10614. break;
  10615. case BABYLON.Texture.PLANAR_MODE:
  10616. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  10617. this._cachedTextureMatrix[0] = this.uScale;
  10618. this._cachedTextureMatrix[5] = this.vScale;
  10619. this._cachedTextureMatrix[12] = this.uOffset;
  10620. this._cachedTextureMatrix[13] = this.vOffset;
  10621. break;
  10622. case BABYLON.Texture.PROJECTION_MODE:
  10623. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  10624. this._projectionModeMatrix.m[0] = 0.5;
  10625. this._projectionModeMatrix.m[5] = -0.5;
  10626. this._projectionModeMatrix.m[10] = 0.0;
  10627. this._projectionModeMatrix.m[12] = 0.5;
  10628. this._projectionModeMatrix.m[13] = 0.5;
  10629. this._projectionModeMatrix.m[14] = 1.0;
  10630. this._projectionModeMatrix.m[15] = 1.0;
  10631. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  10632. break;
  10633. default:
  10634. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  10635. break;
  10636. }
  10637. return this._cachedTextureMatrix;
  10638. };
  10639. Texture.prototype.clone = function () {
  10640. var newTexture = new BABYLON.Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY);
  10641. // Base texture
  10642. newTexture.hasAlpha = this.hasAlpha;
  10643. newTexture.level = this.level;
  10644. newTexture.wrapU = this.wrapU;
  10645. newTexture.wrapV = this.wrapV;
  10646. newTexture.coordinatesIndex = this.coordinatesIndex;
  10647. newTexture.coordinatesMode = this.coordinatesMode;
  10648. // Texture
  10649. newTexture.uOffset = this.uOffset;
  10650. newTexture.vOffset = this.vOffset;
  10651. newTexture.uScale = this.uScale;
  10652. newTexture.vScale = this.vScale;
  10653. newTexture.uAng = this.uAng;
  10654. newTexture.vAng = this.vAng;
  10655. newTexture.wAng = this.wAng;
  10656. return newTexture;
  10657. };
  10658. // Statics
  10659. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  10660. if (typeof samplingMode === "undefined") { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  10661. if (typeof onLoad === "undefined") { onLoad = null; }
  10662. if (typeof onError === "undefined") { onError = null; }
  10663. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  10664. };
  10665. Texture.NEAREST_SAMPLINGMODE = 1;
  10666. Texture.BILINEAR_SAMPLINGMODE = 2;
  10667. Texture.TRILINEAR_SAMPLINGMODE = 3;
  10668. Texture.EXPLICIT_MODE = 0;
  10669. Texture.SPHERICAL_MODE = 1;
  10670. Texture.PLANAR_MODE = 2;
  10671. Texture.CUBIC_MODE = 3;
  10672. Texture.PROJECTION_MODE = 4;
  10673. Texture.SKYBOX_MODE = 5;
  10674. Texture.CLAMP_ADDRESSMODE = 0;
  10675. Texture.WRAP_ADDRESSMODE = 1;
  10676. Texture.MIRROR_ADDRESSMODE = 2;
  10677. return Texture;
  10678. })(BABYLON.BaseTexture);
  10679. BABYLON.Texture = Texture;
  10680. })(BABYLON || (BABYLON = {}));
  10681. //# sourceMappingURL=babylon.texture.js.map
  10682. var BABYLON;
  10683. (function (BABYLON) {
  10684. var CubeTexture = (function (_super) {
  10685. __extends(CubeTexture, _super);
  10686. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  10687. _super.call(this, scene);
  10688. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  10689. this.name = rootUrl;
  10690. this.url = rootUrl;
  10691. this._noMipmap = noMipmap;
  10692. this.hasAlpha = false;
  10693. this._texture = this._getFromCache(rootUrl, noMipmap);
  10694. if (!extensions) {
  10695. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  10696. }
  10697. this._extensions = extensions;
  10698. if (!this._texture) {
  10699. if (!scene.useDelayedTextureLoading) {
  10700. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  10701. } else {
  10702. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  10703. }
  10704. }
  10705. this.isCube = true;
  10706. this._textureMatrix = BABYLON.Matrix.Identity();
  10707. }
  10708. CubeTexture.prototype.clone = function () {
  10709. var newTexture = new BABYLON.CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  10710. // Base texture
  10711. newTexture.level = this.level;
  10712. newTexture.wrapU = this.wrapU;
  10713. newTexture.wrapV = this.wrapV;
  10714. newTexture.coordinatesIndex = this.coordinatesIndex;
  10715. newTexture.coordinatesMode = this.coordinatesMode;
  10716. return newTexture;
  10717. };
  10718. // Methods
  10719. CubeTexture.prototype.delayLoad = function () {
  10720. if (this.delayLoadState != BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  10721. return;
  10722. }
  10723. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  10724. this._texture = this._getFromCache(this.url, this._noMipmap);
  10725. if (!this._texture) {
  10726. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  10727. }
  10728. };
  10729. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  10730. return this._textureMatrix;
  10731. };
  10732. return CubeTexture;
  10733. })(BABYLON.BaseTexture);
  10734. BABYLON.CubeTexture = CubeTexture;
  10735. })(BABYLON || (BABYLON = {}));
  10736. //# sourceMappingURL=babylon.cubeTexture.js.map
  10737. var BABYLON;
  10738. (function (BABYLON) {
  10739. var RenderTargetTexture = (function (_super) {
  10740. __extends(RenderTargetTexture, _super);
  10741. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio) {
  10742. if (typeof doNotChangeAspectRatio === "undefined") { doNotChangeAspectRatio = true; }
  10743. _super.call(this, null, scene, !generateMipMaps);
  10744. this.renderList = new Array();
  10745. this.renderParticles = true;
  10746. this.renderSprites = false;
  10747. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  10748. this._currentRefreshId = -1;
  10749. this._refreshRate = 1;
  10750. this.name = name;
  10751. this.isRenderTarget = true;
  10752. this._size = size;
  10753. this._generateMipMaps = generateMipMaps;
  10754. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  10755. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  10756. // Rendering groups
  10757. this._renderingManager = new BABYLON.RenderingManager(scene);
  10758. }
  10759. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  10760. this._currentRefreshId = -1;
  10761. };
  10762. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  10763. get: function () {
  10764. return this._refreshRate;
  10765. },
  10766. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  10767. set: function (value) {
  10768. this._refreshRate = value;
  10769. this.resetRefreshCounter();
  10770. },
  10771. enumerable: true,
  10772. configurable: true
  10773. });
  10774. RenderTargetTexture.prototype._shouldRender = function () {
  10775. if (this._currentRefreshId === -1) {
  10776. this._currentRefreshId = 1;
  10777. return true;
  10778. }
  10779. if (this.refreshRate == this._currentRefreshId) {
  10780. this._currentRefreshId = 1;
  10781. return true;
  10782. }
  10783. this._currentRefreshId++;
  10784. return false;
  10785. };
  10786. RenderTargetTexture.prototype.isReady = function () {
  10787. if (!this.getScene().renderTargetsEnabled) {
  10788. return false;
  10789. }
  10790. return _super.prototype.isReady.call(this);
  10791. };
  10792. RenderTargetTexture.prototype.getRenderSize = function () {
  10793. return this._size;
  10794. };
  10795. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  10796. get: function () {
  10797. return true;
  10798. },
  10799. enumerable: true,
  10800. configurable: true
  10801. });
  10802. RenderTargetTexture.prototype.scale = function (ratio) {
  10803. var newSize = this._size * ratio;
  10804. this.resize(newSize, this._generateMipMaps);
  10805. };
  10806. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  10807. this.releaseInternalTexture();
  10808. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  10809. };
  10810. RenderTargetTexture.prototype.render = function (useCameraPostProcess) {
  10811. var scene = this.getScene();
  10812. var engine = scene.getEngine();
  10813. if (this._waitingRenderList) {
  10814. this.renderList = [];
  10815. for (var index = 0; index < this._waitingRenderList.length; index++) {
  10816. var id = this._waitingRenderList[index];
  10817. this.renderList.push(scene.getMeshByID(id));
  10818. }
  10819. delete this._waitingRenderList;
  10820. }
  10821. if (!this.renderList) {
  10822. return;
  10823. }
  10824. // Bind
  10825. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  10826. engine.bindFramebuffer(this._texture);
  10827. }
  10828. // Clear
  10829. engine.clear(scene.clearColor, true, true);
  10830. this._renderingManager.reset();
  10831. for (var meshIndex = 0; meshIndex < this.renderList.length; meshIndex++) {
  10832. var mesh = this.renderList[meshIndex];
  10833. if (mesh) {
  10834. if (!mesh.isReady() || (mesh.material && !mesh.material.isReady())) {
  10835. // Reset _currentRefreshId
  10836. this.resetRefreshCounter();
  10837. continue;
  10838. }
  10839. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) != 0)) {
  10840. mesh._activate(scene.getRenderId());
  10841. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  10842. var subMesh = mesh.subMeshes[subIndex];
  10843. scene._activeVertices += subMesh.indexCount;
  10844. this._renderingManager.dispatch(subMesh);
  10845. }
  10846. }
  10847. }
  10848. }
  10849. if (!this._doNotChangeAspectRatio) {
  10850. scene.updateTransformMatrix(true);
  10851. }
  10852. if (this.onBeforeRender) {
  10853. this.onBeforeRender();
  10854. }
  10855. // Render
  10856. this._renderingManager.render(this.customRenderFunction, this.renderList, this.renderParticles, this.renderSprites);
  10857. if (useCameraPostProcess) {
  10858. scene.postProcessManager._finalizeFrame(false, this._texture);
  10859. }
  10860. if (this.onAfterRender) {
  10861. this.onAfterRender();
  10862. }
  10863. // Unbind
  10864. engine.unBindFramebuffer(this._texture);
  10865. if (!this._doNotChangeAspectRatio) {
  10866. scene.updateTransformMatrix(true);
  10867. }
  10868. };
  10869. RenderTargetTexture.prototype.clone = function () {
  10870. var textureSize = this.getSize();
  10871. var newTexture = new BABYLON.RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  10872. // Base texture
  10873. newTexture.hasAlpha = this.hasAlpha;
  10874. newTexture.level = this.level;
  10875. // RenderTarget Texture
  10876. newTexture.coordinatesMode = this.coordinatesMode;
  10877. newTexture.renderList = this.renderList.slice(0);
  10878. return newTexture;
  10879. };
  10880. return RenderTargetTexture;
  10881. })(BABYLON.Texture);
  10882. BABYLON.RenderTargetTexture = RenderTargetTexture;
  10883. })(BABYLON || (BABYLON = {}));
  10884. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  10885. var BABYLON;
  10886. (function (BABYLON) {
  10887. var ProceduralTexture = (function (_super) {
  10888. __extends(ProceduralTexture, _super);
  10889. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps) {
  10890. if (typeof generateMipMaps === "undefined") { generateMipMaps = true; }
  10891. _super.call(this, null, scene, !generateMipMaps);
  10892. this._currentRefreshId = -1;
  10893. this._refreshRate = 1;
  10894. this._vertexDeclaration = [2];
  10895. this._vertexStrideSize = 2 * 4;
  10896. this._uniforms = new Array();
  10897. this._samplers = new Array();
  10898. this._textures = new Array();
  10899. this._floats = new Array();
  10900. this._floatsArrays = {};
  10901. this._colors3 = new Array();
  10902. this._colors4 = new Array();
  10903. this._vectors2 = new Array();
  10904. this._vectors3 = new Array();
  10905. this._matrices = new Array();
  10906. this._fallbackTextureUsed = false;
  10907. scene._proceduralTextures.push(this);
  10908. this.name = name;
  10909. this.isRenderTarget = true;
  10910. this._size = size;
  10911. this._generateMipMaps = generateMipMaps;
  10912. this.setFragment(fragment);
  10913. this._fallbackTexture = fallbackTexture;
  10914. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  10915. // VBO
  10916. var vertices = [];
  10917. vertices.push(1, 1);
  10918. vertices.push(-1, 1);
  10919. vertices.push(-1, -1);
  10920. vertices.push(1, -1);
  10921. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  10922. // Indices
  10923. var indices = [];
  10924. indices.push(0);
  10925. indices.push(1);
  10926. indices.push(2);
  10927. indices.push(0);
  10928. indices.push(2);
  10929. indices.push(3);
  10930. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  10931. }
  10932. ProceduralTexture.prototype.reset = function () {
  10933. if (this._effect === undefined) {
  10934. return;
  10935. }
  10936. var engine = this.getScene().getEngine();
  10937. engine._releaseEffect(this._effect);
  10938. };
  10939. ProceduralTexture.prototype.isReady = function () {
  10940. var _this = this;
  10941. var engine = this.getScene().getEngine();
  10942. var shaders;
  10943. if (!this._fragment) {
  10944. return false;
  10945. }
  10946. if (this._fallbackTextureUsed) {
  10947. return true;
  10948. }
  10949. if (this._fragment.fragmentElement !== undefined) {
  10950. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  10951. } else {
  10952. shaders = { vertex: "procedural", fragment: this._fragment };
  10953. }
  10954. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  10955. _this.releaseInternalTexture();
  10956. if (_this._fallbackTexture) {
  10957. _this._texture = _this._fallbackTexture._texture;
  10958. _this._texture.references++;
  10959. }
  10960. _this._fallbackTextureUsed = true;
  10961. });
  10962. return this._effect.isReady();
  10963. };
  10964. ProceduralTexture.prototype.resetRefreshCounter = function () {
  10965. this._currentRefreshId = -1;
  10966. };
  10967. ProceduralTexture.prototype.setFragment = function (fragment) {
  10968. this._fragment = fragment;
  10969. };
  10970. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  10971. get: function () {
  10972. return this._refreshRate;
  10973. },
  10974. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  10975. set: function (value) {
  10976. this._refreshRate = value;
  10977. this.resetRefreshCounter();
  10978. },
  10979. enumerable: true,
  10980. configurable: true
  10981. });
  10982. ProceduralTexture.prototype._shouldRender = function () {
  10983. if (!this.isReady() || !this._texture) {
  10984. return false;
  10985. }
  10986. if (this._fallbackTextureUsed) {
  10987. return false;
  10988. }
  10989. if (this._currentRefreshId === -1) {
  10990. this._currentRefreshId = 1;
  10991. return true;
  10992. }
  10993. if (this.refreshRate === this._currentRefreshId) {
  10994. this._currentRefreshId = 1;
  10995. return true;
  10996. }
  10997. this._currentRefreshId++;
  10998. return false;
  10999. };
  11000. ProceduralTexture.prototype.getRenderSize = function () {
  11001. return this._size;
  11002. };
  11003. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  11004. if (this._fallbackTextureUsed) {
  11005. return;
  11006. }
  11007. this.releaseInternalTexture();
  11008. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  11009. };
  11010. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  11011. if (this._uniforms.indexOf(uniformName) === -1) {
  11012. this._uniforms.push(uniformName);
  11013. }
  11014. };
  11015. ProceduralTexture.prototype.setTexture = function (name, texture) {
  11016. if (this._samplers.indexOf(name) === -1) {
  11017. this._samplers.push(name);
  11018. }
  11019. this._textures[name] = texture;
  11020. return this;
  11021. };
  11022. ProceduralTexture.prototype.setFloat = function (name, value) {
  11023. this._checkUniform(name);
  11024. this._floats[name] = value;
  11025. return this;
  11026. };
  11027. ProceduralTexture.prototype.setFloats = function (name, value) {
  11028. this._checkUniform(name);
  11029. this._floatsArrays[name] = value;
  11030. return this;
  11031. };
  11032. ProceduralTexture.prototype.setColor3 = function (name, value) {
  11033. this._checkUniform(name);
  11034. this._colors3[name] = value;
  11035. return this;
  11036. };
  11037. ProceduralTexture.prototype.setColor4 = function (name, value) {
  11038. this._checkUniform(name);
  11039. this._colors4[name] = value;
  11040. return this;
  11041. };
  11042. ProceduralTexture.prototype.setVector2 = function (name, value) {
  11043. this._checkUniform(name);
  11044. this._vectors2[name] = value;
  11045. return this;
  11046. };
  11047. ProceduralTexture.prototype.setVector3 = function (name, value) {
  11048. this._checkUniform(name);
  11049. this._vectors3[name] = value;
  11050. return this;
  11051. };
  11052. ProceduralTexture.prototype.setMatrix = function (name, value) {
  11053. this._checkUniform(name);
  11054. this._matrices[name] = value;
  11055. return this;
  11056. };
  11057. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  11058. var scene = this.getScene();
  11059. var engine = scene.getEngine();
  11060. engine.bindFramebuffer(this._texture);
  11061. // Clear
  11062. engine.clear(scene.clearColor, true, true);
  11063. // Render
  11064. engine.enableEffect(this._effect);
  11065. engine.setState(false);
  11066. for (var name in this._textures) {
  11067. this._effect.setTexture(name, this._textures[name]);
  11068. }
  11069. for (name in this._floats) {
  11070. this._effect.setFloat(name, this._floats[name]);
  11071. }
  11072. for (name in this._floatsArrays) {
  11073. this._effect.setArray(name, this._floatsArrays[name]);
  11074. }
  11075. for (name in this._colors3) {
  11076. this._effect.setColor3(name, this._colors3[name]);
  11077. }
  11078. for (name in this._colors4) {
  11079. var color = this._colors4[name];
  11080. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  11081. }
  11082. for (name in this._vectors2) {
  11083. this._effect.setVector2(name, this._vectors2[name]);
  11084. }
  11085. for (name in this._vectors3) {
  11086. this._effect.setVector3(name, this._vectors3[name]);
  11087. }
  11088. for (name in this._matrices) {
  11089. this._effect.setMatrix(name, this._matrices[name]);
  11090. }
  11091. // VBOs
  11092. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  11093. // Draw order
  11094. engine.draw(true, 0, 6);
  11095. // Unbind
  11096. engine.unBindFramebuffer(this._texture);
  11097. };
  11098. ProceduralTexture.prototype.clone = function () {
  11099. var textureSize = this.getSize();
  11100. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  11101. // Base texture
  11102. newTexture.hasAlpha = this.hasAlpha;
  11103. newTexture.level = this.level;
  11104. // RenderTarget Texture
  11105. newTexture.coordinatesMode = this.coordinatesMode;
  11106. return newTexture;
  11107. };
  11108. ProceduralTexture.prototype.dispose = function () {
  11109. var index = this.getScene()._proceduralTextures.indexOf(this);
  11110. if (index >= 0) {
  11111. this.getScene()._proceduralTextures.splice(index, 1);
  11112. }
  11113. _super.prototype.dispose.call(this);
  11114. };
  11115. return ProceduralTexture;
  11116. })(BABYLON.Texture);
  11117. BABYLON.ProceduralTexture = ProceduralTexture;
  11118. })(BABYLON || (BABYLON = {}));
  11119. //# sourceMappingURL=babylon.proceduralTexture.js.map
  11120. var BABYLON;
  11121. (function (BABYLON) {
  11122. var WoodProceduralTexture = (function (_super) {
  11123. __extends(WoodProceduralTexture, _super);
  11124. function WoodProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  11125. _super.call(this, name, size, "wood", scene, fallbackTexture, generateMipMaps);
  11126. this._ampScale = 100.0;
  11127. this._woodColor = new BABYLON.Color3(0.32, 0.17, 0.09);
  11128. this.updateShaderUniforms();
  11129. this.refreshRate = 0;
  11130. }
  11131. WoodProceduralTexture.prototype.updateShaderUniforms = function () {
  11132. this.setFloat("ampScale", this._ampScale);
  11133. this.setColor3("woodColor", this._woodColor);
  11134. };
  11135. Object.defineProperty(WoodProceduralTexture.prototype, "ampScale", {
  11136. get: function () {
  11137. return this._ampScale;
  11138. },
  11139. set: function (value) {
  11140. this._ampScale = value;
  11141. this.updateShaderUniforms();
  11142. },
  11143. enumerable: true,
  11144. configurable: true
  11145. });
  11146. Object.defineProperty(WoodProceduralTexture.prototype, "woodColor", {
  11147. get: function () {
  11148. return this._woodColor;
  11149. },
  11150. set: function (value) {
  11151. this._woodColor = value;
  11152. this.updateShaderUniforms();
  11153. },
  11154. enumerable: true,
  11155. configurable: true
  11156. });
  11157. return WoodProceduralTexture;
  11158. })(BABYLON.ProceduralTexture);
  11159. BABYLON.WoodProceduralTexture = WoodProceduralTexture;
  11160. var FireProceduralTexture = (function (_super) {
  11161. __extends(FireProceduralTexture, _super);
  11162. function FireProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  11163. _super.call(this, name, size, "fire", scene, fallbackTexture, generateMipMaps);
  11164. this._time = 0.0;
  11165. this._speed = new BABYLON.Vector2(0.5, 0.3);
  11166. this._shift = 1.6;
  11167. this._autoGenerateTime = true;
  11168. this._alphaThreshold = 0.5;
  11169. this._fireColors = FireProceduralTexture.RedFireColors;
  11170. this.updateShaderUniforms();
  11171. this.refreshRate = 1;
  11172. }
  11173. FireProceduralTexture.prototype.updateShaderUniforms = function () {
  11174. this.setFloat("time", this._time);
  11175. this.setVector2("speed", this._speed);
  11176. this.setFloat("shift", this._shift);
  11177. this.setColor3("c1", this._fireColors[0]);
  11178. this.setColor3("c2", this._fireColors[1]);
  11179. this.setColor3("c3", this._fireColors[2]);
  11180. this.setColor3("c4", this._fireColors[3]);
  11181. this.setColor3("c5", this._fireColors[4]);
  11182. this.setColor3("c6", this._fireColors[5]);
  11183. this.setFloat("alphaThreshold", this._alphaThreshold);
  11184. };
  11185. FireProceduralTexture.prototype.render = function (useCameraPostProcess) {
  11186. if (this._autoGenerateTime) {
  11187. this._time += this.getScene().getAnimationRatio() * 0.03;
  11188. this.updateShaderUniforms();
  11189. }
  11190. _super.prototype.render.call(this, useCameraPostProcess);
  11191. };
  11192. Object.defineProperty(FireProceduralTexture, "PurpleFireColors", {
  11193. get: function () {
  11194. return [
  11195. new BABYLON.Color3(0.5, 0.0, 1.0),
  11196. new BABYLON.Color3(0.9, 0.0, 1.0),
  11197. new BABYLON.Color3(0.2, 0.0, 1.0),
  11198. new BABYLON.Color3(1.0, 0.9, 1.0),
  11199. new BABYLON.Color3(0.1, 0.1, 1.0),
  11200. new BABYLON.Color3(0.9, 0.9, 1.0)
  11201. ];
  11202. },
  11203. enumerable: true,
  11204. configurable: true
  11205. });
  11206. Object.defineProperty(FireProceduralTexture, "GreenFireColors", {
  11207. get: function () {
  11208. return [
  11209. new BABYLON.Color3(0.5, 1.0, 0.0),
  11210. new BABYLON.Color3(0.5, 1.0, 0.0),
  11211. new BABYLON.Color3(0.3, 0.4, 0.0),
  11212. new BABYLON.Color3(0.5, 1.0, 0.0),
  11213. new BABYLON.Color3(0.2, 0.0, 0.0),
  11214. new BABYLON.Color3(0.5, 1.0, 0.0)
  11215. ];
  11216. },
  11217. enumerable: true,
  11218. configurable: true
  11219. });
  11220. Object.defineProperty(FireProceduralTexture, "RedFireColors", {
  11221. get: function () {
  11222. return [
  11223. new BABYLON.Color3(0.5, 0.0, 0.1),
  11224. new BABYLON.Color3(0.9, 0.0, 0.0),
  11225. new BABYLON.Color3(0.2, 0.0, 0.0),
  11226. new BABYLON.Color3(1.0, 0.9, 0.0),
  11227. new BABYLON.Color3(0.1, 0.1, 0.1),
  11228. new BABYLON.Color3(0.9, 0.9, 0.9)
  11229. ];
  11230. },
  11231. enumerable: true,
  11232. configurable: true
  11233. });
  11234. Object.defineProperty(FireProceduralTexture, "BlueFireColors", {
  11235. get: function () {
  11236. return [
  11237. new BABYLON.Color3(0.1, 0.0, 0.5),
  11238. new BABYLON.Color3(0.0, 0.0, 0.5),
  11239. new BABYLON.Color3(0.1, 0.0, 0.2),
  11240. new BABYLON.Color3(0.0, 0.0, 1.0),
  11241. new BABYLON.Color3(0.1, 0.2, 0.3),
  11242. new BABYLON.Color3(0.0, 0.2, 0.9)
  11243. ];
  11244. },
  11245. enumerable: true,
  11246. configurable: true
  11247. });
  11248. Object.defineProperty(FireProceduralTexture.prototype, "fireColors", {
  11249. get: function () {
  11250. return this._fireColors;
  11251. },
  11252. set: function (value) {
  11253. this._fireColors = value;
  11254. this.updateShaderUniforms();
  11255. },
  11256. enumerable: true,
  11257. configurable: true
  11258. });
  11259. Object.defineProperty(FireProceduralTexture.prototype, "time", {
  11260. get: function () {
  11261. return this._time;
  11262. },
  11263. set: function (value) {
  11264. this._time = value;
  11265. this.updateShaderUniforms();
  11266. },
  11267. enumerable: true,
  11268. configurable: true
  11269. });
  11270. Object.defineProperty(FireProceduralTexture.prototype, "speed", {
  11271. get: function () {
  11272. return this._speed;
  11273. },
  11274. set: function (value) {
  11275. this._speed = value;
  11276. this.updateShaderUniforms();
  11277. },
  11278. enumerable: true,
  11279. configurable: true
  11280. });
  11281. Object.defineProperty(FireProceduralTexture.prototype, "shift", {
  11282. get: function () {
  11283. return this._shift;
  11284. },
  11285. set: function (value) {
  11286. this._shift = value;
  11287. this.updateShaderUniforms();
  11288. },
  11289. enumerable: true,
  11290. configurable: true
  11291. });
  11292. Object.defineProperty(FireProceduralTexture.prototype, "alphaThreshold", {
  11293. get: function () {
  11294. return this._alphaThreshold;
  11295. },
  11296. set: function (value) {
  11297. this._alphaThreshold = value;
  11298. this.updateShaderUniforms();
  11299. },
  11300. enumerable: true,
  11301. configurable: true
  11302. });
  11303. return FireProceduralTexture;
  11304. })(BABYLON.ProceduralTexture);
  11305. BABYLON.FireProceduralTexture = FireProceduralTexture;
  11306. var CloudProceduralTexture = (function (_super) {
  11307. __extends(CloudProceduralTexture, _super);
  11308. function CloudProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  11309. _super.call(this, name, size, "cloud", scene, fallbackTexture, generateMipMaps);
  11310. this._skyColor = new BABYLON.Color3(0.15, 0.68, 1.0);
  11311. this._cloudColor = new BABYLON.Color3(1, 1, 1);
  11312. this.updateShaderUniforms();
  11313. this.refreshRate = 0;
  11314. }
  11315. CloudProceduralTexture.prototype.updateShaderUniforms = function () {
  11316. this.setColor3("skyColor", this._skyColor);
  11317. this.setColor3("cloudColor", this._cloudColor);
  11318. };
  11319. Object.defineProperty(CloudProceduralTexture.prototype, "skyColor", {
  11320. get: function () {
  11321. return this._skyColor;
  11322. },
  11323. set: function (value) {
  11324. this._skyColor = value;
  11325. this.updateShaderUniforms();
  11326. },
  11327. enumerable: true,
  11328. configurable: true
  11329. });
  11330. Object.defineProperty(CloudProceduralTexture.prototype, "cloudColor", {
  11331. get: function () {
  11332. return this._cloudColor;
  11333. },
  11334. set: function (value) {
  11335. this._cloudColor = value;
  11336. this.updateShaderUniforms();
  11337. },
  11338. enumerable: true,
  11339. configurable: true
  11340. });
  11341. return CloudProceduralTexture;
  11342. })(BABYLON.ProceduralTexture);
  11343. BABYLON.CloudProceduralTexture = CloudProceduralTexture;
  11344. var GrassProceduralTexture = (function (_super) {
  11345. __extends(GrassProceduralTexture, _super);
  11346. function GrassProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  11347. _super.call(this, name, size, "grass", scene, fallbackTexture, generateMipMaps);
  11348. this._herb1 = new BABYLON.Color3(0.29, 0.38, 0.02);
  11349. this._herb2 = new BABYLON.Color3(0.36, 0.49, 0.09);
  11350. this._herb3 = new BABYLON.Color3(0.51, 0.6, 0.28);
  11351. this._groundColor = new BABYLON.Color3(1, 1, 1);
  11352. this._grassColors = [
  11353. new BABYLON.Color3(0.29, 0.38, 0.02),
  11354. new BABYLON.Color3(0.36, 0.49, 0.09),
  11355. new BABYLON.Color3(0.51, 0.6, 0.28)
  11356. ];
  11357. this.updateShaderUniforms();
  11358. this.refreshRate = 0;
  11359. }
  11360. GrassProceduralTexture.prototype.updateShaderUniforms = function () {
  11361. this.setColor3("herb1Color", this._grassColors[0]);
  11362. this.setColor3("herb2Color", this._grassColors[1]);
  11363. this.setColor3("herb3Color", this._grassColors[2]);
  11364. this.setColor3("groundColor", this._groundColor);
  11365. };
  11366. Object.defineProperty(GrassProceduralTexture.prototype, "grassColors", {
  11367. get: function () {
  11368. return this._grassColors;
  11369. },
  11370. set: function (value) {
  11371. this._grassColors = value;
  11372. this.updateShaderUniforms();
  11373. },
  11374. enumerable: true,
  11375. configurable: true
  11376. });
  11377. Object.defineProperty(GrassProceduralTexture.prototype, "groundColor", {
  11378. get: function () {
  11379. return this._groundColor;
  11380. },
  11381. set: function (value) {
  11382. this.groundColor = value;
  11383. this.updateShaderUniforms();
  11384. },
  11385. enumerable: true,
  11386. configurable: true
  11387. });
  11388. return GrassProceduralTexture;
  11389. })(BABYLON.ProceduralTexture);
  11390. BABYLON.GrassProceduralTexture = GrassProceduralTexture;
  11391. var RoadProceduralTexture = (function (_super) {
  11392. __extends(RoadProceduralTexture, _super);
  11393. function RoadProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  11394. _super.call(this, name, size, "road", scene, fallbackTexture, generateMipMaps);
  11395. this._roadColor = new BABYLON.Color3(0.53, 0.53, 0.53);
  11396. this.updateShaderUniforms();
  11397. this.refreshRate = 0;
  11398. }
  11399. RoadProceduralTexture.prototype.updateShaderUniforms = function () {
  11400. this.setColor3("roadColor", this._roadColor);
  11401. };
  11402. Object.defineProperty(RoadProceduralTexture.prototype, "roadColor", {
  11403. get: function () {
  11404. return this._roadColor;
  11405. },
  11406. set: function (value) {
  11407. this._roadColor = value;
  11408. this.updateShaderUniforms();
  11409. },
  11410. enumerable: true,
  11411. configurable: true
  11412. });
  11413. return RoadProceduralTexture;
  11414. })(BABYLON.ProceduralTexture);
  11415. BABYLON.RoadProceduralTexture = RoadProceduralTexture;
  11416. var BrickProceduralTexture = (function (_super) {
  11417. __extends(BrickProceduralTexture, _super);
  11418. function BrickProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  11419. _super.call(this, name, size, "brick", scene, fallbackTexture, generateMipMaps);
  11420. this._numberOfBricksHeight = 15;
  11421. this._numberOfBricksWidth = 5;
  11422. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  11423. this._brickColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  11424. this.updateShaderUniforms();
  11425. this.refreshRate = 0;
  11426. }
  11427. BrickProceduralTexture.prototype.updateShaderUniforms = function () {
  11428. this.setFloat("numberOfBricksHeight", this._numberOfBricksHeight);
  11429. this.setFloat("numberOfBricksWidth", this._numberOfBricksWidth);
  11430. this.setColor3("brickColor", this._brickColor);
  11431. this.setColor3("jointColor", this._jointColor);
  11432. };
  11433. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksHeight", {
  11434. get: function () {
  11435. return this._numberOfBricksHeight;
  11436. },
  11437. enumerable: true,
  11438. configurable: true
  11439. });
  11440. Object.defineProperty(BrickProceduralTexture.prototype, "cloudColor", {
  11441. set: function (value) {
  11442. this._numberOfBricksHeight = value;
  11443. this.updateShaderUniforms();
  11444. },
  11445. enumerable: true,
  11446. configurable: true
  11447. });
  11448. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksWidth", {
  11449. get: function () {
  11450. return this._numberOfBricksWidth;
  11451. },
  11452. set: function (value) {
  11453. this._numberOfBricksHeight = value;
  11454. this.updateShaderUniforms();
  11455. },
  11456. enumerable: true,
  11457. configurable: true
  11458. });
  11459. Object.defineProperty(BrickProceduralTexture.prototype, "jointColor", {
  11460. get: function () {
  11461. return this._jointColor;
  11462. },
  11463. set: function (value) {
  11464. this._jointColor = value;
  11465. this.updateShaderUniforms();
  11466. },
  11467. enumerable: true,
  11468. configurable: true
  11469. });
  11470. Object.defineProperty(BrickProceduralTexture.prototype, "brickColor", {
  11471. get: function () {
  11472. return this._brickColor;
  11473. },
  11474. set: function (value) {
  11475. this._brickColor = value;
  11476. this.updateShaderUniforms();
  11477. },
  11478. enumerable: true,
  11479. configurable: true
  11480. });
  11481. return BrickProceduralTexture;
  11482. })(BABYLON.ProceduralTexture);
  11483. BABYLON.BrickProceduralTexture = BrickProceduralTexture;
  11484. var MarbleProceduralTexture = (function (_super) {
  11485. __extends(MarbleProceduralTexture, _super);
  11486. function MarbleProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  11487. _super.call(this, name, size, "marble", scene, fallbackTexture, generateMipMaps);
  11488. this._numberOfTilesHeight = 3;
  11489. this._numberOfTilesWidth = 3;
  11490. this._amplitude = 9.0;
  11491. this._marbleColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  11492. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  11493. this.updateShaderUniforms();
  11494. this.refreshRate = 0;
  11495. }
  11496. MarbleProceduralTexture.prototype.updateShaderUniforms = function () {
  11497. this.setFloat("numberOfTilesHeight", this._numberOfTilesHeight);
  11498. this.setFloat("numberOfTilesWidth", this._numberOfTilesWidth);
  11499. this.setFloat("amplitude", this._amplitude);
  11500. this.setColor3("marbleColor", this._marbleColor);
  11501. this.setColor3("jointColor", this._jointColor);
  11502. };
  11503. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesHeight", {
  11504. get: function () {
  11505. return this._numberOfTilesHeight;
  11506. },
  11507. set: function (value) {
  11508. this._numberOfTilesHeight = value;
  11509. this.updateShaderUniforms();
  11510. },
  11511. enumerable: true,
  11512. configurable: true
  11513. });
  11514. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesWidth", {
  11515. get: function () {
  11516. return this._numberOfTilesWidth;
  11517. },
  11518. set: function (value) {
  11519. this._numberOfTilesWidth = value;
  11520. this.updateShaderUniforms();
  11521. },
  11522. enumerable: true,
  11523. configurable: true
  11524. });
  11525. Object.defineProperty(MarbleProceduralTexture.prototype, "jointColor", {
  11526. get: function () {
  11527. return this._jointColor;
  11528. },
  11529. set: function (value) {
  11530. this._jointColor = value;
  11531. this.updateShaderUniforms();
  11532. },
  11533. enumerable: true,
  11534. configurable: true
  11535. });
  11536. Object.defineProperty(MarbleProceduralTexture.prototype, "marbleColor", {
  11537. get: function () {
  11538. return this._marbleColor;
  11539. },
  11540. set: function (value) {
  11541. this._marbleColor = value;
  11542. this.updateShaderUniforms();
  11543. },
  11544. enumerable: true,
  11545. configurable: true
  11546. });
  11547. return MarbleProceduralTexture;
  11548. })(BABYLON.ProceduralTexture);
  11549. BABYLON.MarbleProceduralTexture = MarbleProceduralTexture;
  11550. })(BABYLON || (BABYLON = {}));
  11551. //# sourceMappingURL=babylon.standardProceduralTexture.js.map
  11552. var BABYLON;
  11553. (function (BABYLON) {
  11554. var CustomProceduralTexture = (function (_super) {
  11555. __extends(CustomProceduralTexture, _super);
  11556. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  11557. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  11558. this._animate = true;
  11559. this._time = 0;
  11560. this._texturePath = texturePath;
  11561. //Try to load json
  11562. this.loadJson(texturePath);
  11563. this.refreshRate = 1;
  11564. }
  11565. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  11566. var _this = this;
  11567. var that = this;
  11568. function noConfigFile() {
  11569. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShaderStore or DOM element");
  11570. try {
  11571. that.setFragment(that._texturePath);
  11572. } catch (ex) {
  11573. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  11574. }
  11575. }
  11576. var configFileUrl = jsonUrl + "/config.json";
  11577. var xhr = new XMLHttpRequest();
  11578. xhr.open("GET", configFileUrl, true);
  11579. xhr.addEventListener("load", function () {
  11580. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  11581. try {
  11582. _this._config = JSON.parse(xhr.response);
  11583. _this.updateShaderUniforms();
  11584. _this.updateTextures();
  11585. _this.setFragment(_this._texturePath + "/custom");
  11586. _this._animate = _this._config.animate;
  11587. _this.refreshRate = _this._config.refreshrate;
  11588. } catch (ex) {
  11589. noConfigFile();
  11590. }
  11591. } else {
  11592. noConfigFile();
  11593. }
  11594. }, false);
  11595. xhr.addEventListener("error", function (event) {
  11596. noConfigFile();
  11597. }, false);
  11598. try {
  11599. xhr.send();
  11600. } catch (ex) {
  11601. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  11602. }
  11603. };
  11604. CustomProceduralTexture.prototype.isReady = function () {
  11605. if (!_super.prototype.isReady.call(this)) {
  11606. return false;
  11607. }
  11608. for (var name in this._textures) {
  11609. var texture = this._textures[name];
  11610. if (!texture.isReady()) {
  11611. return false;
  11612. }
  11613. }
  11614. return true;
  11615. };
  11616. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  11617. if (this._animate) {
  11618. this._time += this.getScene().getAnimationRatio() * 0.03;
  11619. this.updateShaderUniforms();
  11620. }
  11621. _super.prototype.render.call(this, useCameraPostProcess);
  11622. };
  11623. CustomProceduralTexture.prototype.updateTextures = function () {
  11624. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  11625. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  11626. }
  11627. };
  11628. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  11629. if (this._config) {
  11630. for (var j = 0; j < this._config.uniforms.length; j++) {
  11631. var uniform = this._config.uniforms[j];
  11632. switch (uniform.type) {
  11633. case "float":
  11634. this.setFloat(uniform.name, uniform.value);
  11635. break;
  11636. case "color3":
  11637. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  11638. break;
  11639. case "color4":
  11640. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  11641. break;
  11642. case "vector2":
  11643. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  11644. break;
  11645. case "vector3":
  11646. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  11647. break;
  11648. }
  11649. }
  11650. }
  11651. this.setFloat("time", this._time);
  11652. };
  11653. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  11654. get: function () {
  11655. return this._animate;
  11656. },
  11657. set: function (value) {
  11658. this._animate = value;
  11659. },
  11660. enumerable: true,
  11661. configurable: true
  11662. });
  11663. return CustomProceduralTexture;
  11664. })(BABYLON.ProceduralTexture);
  11665. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  11666. })(BABYLON || (BABYLON = {}));
  11667. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  11668. var BABYLON;
  11669. (function (BABYLON) {
  11670. var MirrorTexture = (function (_super) {
  11671. __extends(MirrorTexture, _super);
  11672. function MirrorTexture(name, size, scene, generateMipMaps) {
  11673. var _this = this;
  11674. _super.call(this, name, size, scene, generateMipMaps, true);
  11675. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  11676. this._transformMatrix = BABYLON.Matrix.Zero();
  11677. this._mirrorMatrix = BABYLON.Matrix.Zero();
  11678. this.onBeforeRender = function () {
  11679. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  11680. _this._savedViewMatrix = scene.getViewMatrix();
  11681. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  11682. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  11683. scene.clipPlane = _this.mirrorPlane;
  11684. scene.getEngine().cullBackFaces = false;
  11685. };
  11686. this.onAfterRender = function () {
  11687. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  11688. scene.getEngine().cullBackFaces = true;
  11689. delete scene.clipPlane;
  11690. };
  11691. }
  11692. MirrorTexture.prototype.clone = function () {
  11693. var textureSize = this.getSize();
  11694. var newTexture = new BABYLON.MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  11695. // Base texture
  11696. newTexture.hasAlpha = this.hasAlpha;
  11697. newTexture.level = this.level;
  11698. // Mirror Texture
  11699. newTexture.mirrorPlane = this.mirrorPlane.clone();
  11700. newTexture.renderList = this.renderList.slice(0);
  11701. return newTexture;
  11702. };
  11703. return MirrorTexture;
  11704. })(BABYLON.RenderTargetTexture);
  11705. BABYLON.MirrorTexture = MirrorTexture;
  11706. })(BABYLON || (BABYLON = {}));
  11707. //# sourceMappingURL=babylon.mirrorTexture.js.map
  11708. var BABYLON;
  11709. (function (BABYLON) {
  11710. var DynamicTexture = (function (_super) {
  11711. __extends(DynamicTexture, _super);
  11712. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  11713. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  11714. _super.call(this, null, scene, !generateMipMaps);
  11715. this.name = name;
  11716. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  11717. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  11718. this._generateMipMaps = generateMipMaps;
  11719. if (options.getContext) {
  11720. this._canvas = options;
  11721. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  11722. } else {
  11723. this._canvas = document.createElement("canvas");
  11724. if (options.width) {
  11725. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  11726. } else {
  11727. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  11728. }
  11729. }
  11730. var textureSize = this.getSize();
  11731. this._canvas.width = textureSize.width;
  11732. this._canvas.height = textureSize.height;
  11733. this._context = this._canvas.getContext("2d");
  11734. }
  11735. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  11736. get: function () {
  11737. return true;
  11738. },
  11739. enumerable: true,
  11740. configurable: true
  11741. });
  11742. DynamicTexture.prototype.scale = function (ratio) {
  11743. var textureSize = this.getSize();
  11744. textureSize.width *= ratio;
  11745. textureSize.height *= ratio;
  11746. this._canvas.width = textureSize.width;
  11747. this._canvas.height = textureSize.height;
  11748. this.releaseInternalTexture();
  11749. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  11750. };
  11751. DynamicTexture.prototype.getContext = function () {
  11752. return this._context;
  11753. };
  11754. DynamicTexture.prototype.update = function (invertY) {
  11755. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  11756. };
  11757. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY) {
  11758. var size = this.getSize();
  11759. if (clearColor) {
  11760. this._context.fillStyle = clearColor;
  11761. this._context.fillRect(0, 0, size.width, size.height);
  11762. }
  11763. this._context.font = font;
  11764. if (x === null) {
  11765. var textSize = this._context.measureText(text);
  11766. x = (size.width - textSize.width) / 2;
  11767. }
  11768. this._context.fillStyle = color;
  11769. this._context.fillText(text, x, y);
  11770. this.update(invertY);
  11771. };
  11772. DynamicTexture.prototype.clone = function () {
  11773. var textureSize = this.getSize();
  11774. var newTexture = new BABYLON.DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  11775. // Base texture
  11776. newTexture.hasAlpha = this.hasAlpha;
  11777. newTexture.level = this.level;
  11778. // Dynamic Texture
  11779. newTexture.wrapU = this.wrapU;
  11780. newTexture.wrapV = this.wrapV;
  11781. return newTexture;
  11782. };
  11783. return DynamicTexture;
  11784. })(BABYLON.Texture);
  11785. BABYLON.DynamicTexture = DynamicTexture;
  11786. })(BABYLON || (BABYLON = {}));
  11787. //# sourceMappingURL=babylon.dynamicTexture.js.map
  11788. var BABYLON;
  11789. (function (BABYLON) {
  11790. var VideoTexture = (function (_super) {
  11791. __extends(VideoTexture, _super);
  11792. function VideoTexture(name, urls, size, scene, generateMipMaps, invertY, samplingMode) {
  11793. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  11794. var _this = this;
  11795. _super.call(this, null, scene, !generateMipMaps, invertY);
  11796. this._autoLaunch = true;
  11797. this.name = name;
  11798. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  11799. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  11800. var requiredWidth = size.width || size;
  11801. var requiredHeight = size.height || size;
  11802. this._texture = scene.getEngine().createDynamicTexture(requiredWidth, requiredHeight, generateMipMaps, samplingMode);
  11803. var textureSize = this.getSize();
  11804. this.video = document.createElement("video");
  11805. this.video.width = textureSize.width;
  11806. this.video.height = textureSize.height;
  11807. this.video.autoplay = false;
  11808. this.video.loop = true;
  11809. this.video.addEventListener("canplaythrough", function () {
  11810. if (_this._texture) {
  11811. _this._texture.isReady = true;
  11812. }
  11813. });
  11814. urls.forEach(function (url) {
  11815. var source = document.createElement("source");
  11816. source.src = url;
  11817. _this.video.appendChild(source);
  11818. });
  11819. this._lastUpdate = BABYLON.Tools.Now;
  11820. }
  11821. VideoTexture.prototype.update = function () {
  11822. if (this._autoLaunch) {
  11823. this._autoLaunch = false;
  11824. this.video.play();
  11825. }
  11826. var now = BABYLON.Tools.Now;
  11827. if (now - this._lastUpdate < 15) {
  11828. return false;
  11829. }
  11830. this._lastUpdate = now;
  11831. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  11832. return true;
  11833. };
  11834. return VideoTexture;
  11835. })(BABYLON.Texture);
  11836. BABYLON.VideoTexture = VideoTexture;
  11837. })(BABYLON || (BABYLON = {}));
  11838. //# sourceMappingURL=babylon.videoTexture.js.map
  11839. var BABYLON;
  11840. (function (BABYLON) {
  11841. var EffectFallbacks = (function () {
  11842. function EffectFallbacks() {
  11843. this._defines = {};
  11844. this._currentRank = 32;
  11845. this._maxRank = -1;
  11846. }
  11847. EffectFallbacks.prototype.addFallback = function (rank, define) {
  11848. if (!this._defines[rank]) {
  11849. if (rank < this._currentRank) {
  11850. this._currentRank = rank;
  11851. }
  11852. if (rank > this._maxRank) {
  11853. this._maxRank = rank;
  11854. }
  11855. this._defines[rank] = new Array();
  11856. }
  11857. this._defines[rank].push(define);
  11858. };
  11859. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  11860. get: function () {
  11861. return this._currentRank <= this._maxRank;
  11862. },
  11863. enumerable: true,
  11864. configurable: true
  11865. });
  11866. EffectFallbacks.prototype.reduce = function (currentDefines) {
  11867. var currentFallbacks = this._defines[this._currentRank];
  11868. for (var index = 0; index < currentFallbacks.length; index++) {
  11869. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  11870. }
  11871. this._currentRank++;
  11872. return currentDefines;
  11873. };
  11874. return EffectFallbacks;
  11875. })();
  11876. BABYLON.EffectFallbacks = EffectFallbacks;
  11877. var Effect = (function () {
  11878. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  11879. var _this = this;
  11880. this._isReady = false;
  11881. this._compilationError = "";
  11882. this._valueCache = [];
  11883. this._engine = engine;
  11884. this.name = baseName;
  11885. this.defines = defines;
  11886. this._uniformsNames = uniformsNames.concat(samplers);
  11887. this._samplers = samplers;
  11888. this._attributesNames = attributesNames;
  11889. this.onError = onError;
  11890. this.onCompiled = onCompiled;
  11891. var vertexSource;
  11892. var fragmentSource;
  11893. if (baseName.vertexElement) {
  11894. vertexSource = document.getElementById(baseName.vertexElement);
  11895. if (!vertexSource) {
  11896. vertexSource = baseName.vertexElement;
  11897. }
  11898. } else {
  11899. vertexSource = baseName.vertex || baseName;
  11900. }
  11901. if (baseName.fragmentElement) {
  11902. fragmentSource = document.getElementById(baseName.fragmentElement);
  11903. if (!fragmentSource) {
  11904. fragmentSource = baseName.fragmentElement;
  11905. }
  11906. } else {
  11907. fragmentSource = baseName.fragment || baseName;
  11908. }
  11909. this._loadVertexShader(vertexSource, function (vertexCode) {
  11910. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  11911. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  11912. });
  11913. });
  11914. }
  11915. // Properties
  11916. Effect.prototype.isReady = function () {
  11917. return this._isReady;
  11918. };
  11919. Effect.prototype.getProgram = function () {
  11920. return this._program;
  11921. };
  11922. Effect.prototype.getAttributesNames = function () {
  11923. return this._attributesNames;
  11924. };
  11925. Effect.prototype.getAttributeLocation = function (index) {
  11926. return this._attributes[index];
  11927. };
  11928. Effect.prototype.getAttributeLocationByName = function (name) {
  11929. var index = this._attributesNames.indexOf(name);
  11930. return this._attributes[index];
  11931. };
  11932. Effect.prototype.getAttributesCount = function () {
  11933. return this._attributes.length;
  11934. };
  11935. Effect.prototype.getUniformIndex = function (uniformName) {
  11936. return this._uniformsNames.indexOf(uniformName);
  11937. };
  11938. Effect.prototype.getUniform = function (uniformName) {
  11939. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  11940. };
  11941. Effect.prototype.getSamplers = function () {
  11942. return this._samplers;
  11943. };
  11944. Effect.prototype.getCompilationError = function () {
  11945. return this._compilationError;
  11946. };
  11947. // Methods
  11948. Effect.prototype._loadVertexShader = function (vertex, callback) {
  11949. // DOM element ?
  11950. if (vertex instanceof HTMLElement) {
  11951. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  11952. callback(vertexCode);
  11953. return;
  11954. }
  11955. // Is in local store ?
  11956. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  11957. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  11958. return;
  11959. }
  11960. var vertexShaderUrl;
  11961. if (vertex[0] === ".") {
  11962. vertexShaderUrl = vertex;
  11963. } else {
  11964. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  11965. }
  11966. // Vertex shader
  11967. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  11968. };
  11969. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  11970. // DOM element ?
  11971. if (fragment instanceof HTMLElement) {
  11972. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  11973. callback(fragmentCode);
  11974. return;
  11975. }
  11976. // Is in local store ?
  11977. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  11978. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  11979. return;
  11980. }
  11981. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  11982. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  11983. return;
  11984. }
  11985. var fragmentShaderUrl;
  11986. if (fragment[0] === ".") {
  11987. fragmentShaderUrl = fragment;
  11988. } else {
  11989. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  11990. }
  11991. // Fragment shader
  11992. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  11993. };
  11994. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  11995. try {
  11996. var engine = this._engine;
  11997. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  11998. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  11999. this._attributes = engine.getAttributes(this._program, attributesNames);
  12000. for (var index = 0; index < this._samplers.length; index++) {
  12001. var sampler = this.getUniform(this._samplers[index]);
  12002. if (sampler == null) {
  12003. this._samplers.splice(index, 1);
  12004. index--;
  12005. }
  12006. }
  12007. engine.bindSamplers(this);
  12008. this._isReady = true;
  12009. if (this.onCompiled) {
  12010. this.onCompiled(this);
  12011. }
  12012. } catch (e) {
  12013. // Is it a problem with precision?
  12014. if (e.message.indexOf("highp") !== -1) {
  12015. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  12016. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  12017. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  12018. return;
  12019. }
  12020. // Let's go through fallbacks then
  12021. if (fallbacks && fallbacks.isMoreFallbacks) {
  12022. defines = fallbacks.reduce(defines);
  12023. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  12024. } else {
  12025. BABYLON.Tools.Error("Unable to compile effect: " + this.name);
  12026. BABYLON.Tools.Error("Defines: " + defines);
  12027. BABYLON.Tools.Error("Error: " + e.message);
  12028. this._compilationError = e.message;
  12029. if (this.onError) {
  12030. this.onError(this, this._compilationError);
  12031. }
  12032. }
  12033. }
  12034. };
  12035. Effect.prototype._bindTexture = function (channel, texture) {
  12036. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  12037. };
  12038. Effect.prototype.setTexture = function (channel, texture) {
  12039. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  12040. };
  12041. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  12042. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  12043. };
  12044. //public _cacheMatrix(uniformName, matrix) {
  12045. // if (!this._valueCache[uniformName]) {
  12046. // this._valueCache[uniformName] = new BABYLON.Matrix();
  12047. // }
  12048. // for (var index = 0; index < 16; index++) {
  12049. // this._valueCache[uniformName].m[index] = matrix.m[index];
  12050. // }
  12051. //};
  12052. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  12053. if (!this._valueCache[uniformName]) {
  12054. this._valueCache[uniformName] = [x, y];
  12055. return;
  12056. }
  12057. this._valueCache[uniformName][0] = x;
  12058. this._valueCache[uniformName][1] = y;
  12059. };
  12060. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  12061. if (!this._valueCache[uniformName]) {
  12062. this._valueCache[uniformName] = [x, y, z];
  12063. return;
  12064. }
  12065. this._valueCache[uniformName][0] = x;
  12066. this._valueCache[uniformName][1] = y;
  12067. this._valueCache[uniformName][2] = z;
  12068. };
  12069. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  12070. if (!this._valueCache[uniformName]) {
  12071. this._valueCache[uniformName] = [x, y, z, w];
  12072. return;
  12073. }
  12074. this._valueCache[uniformName][0] = x;
  12075. this._valueCache[uniformName][1] = y;
  12076. this._valueCache[uniformName][2] = z;
  12077. this._valueCache[uniformName][3] = w;
  12078. };
  12079. Effect.prototype.setArray = function (uniformName, array) {
  12080. this._engine.setArray(this.getUniform(uniformName), array);
  12081. return this;
  12082. };
  12083. Effect.prototype.setMatrices = function (uniformName, matrices) {
  12084. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  12085. return this;
  12086. };
  12087. Effect.prototype.setMatrix = function (uniformName, matrix) {
  12088. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  12089. // return;
  12090. //this._cacheMatrix(uniformName, matrix);
  12091. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  12092. return this;
  12093. };
  12094. Effect.prototype.setFloat = function (uniformName, value) {
  12095. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  12096. return this;
  12097. this._valueCache[uniformName] = value;
  12098. this._engine.setFloat(this.getUniform(uniformName), value);
  12099. return this;
  12100. };
  12101. Effect.prototype.setBool = function (uniformName, bool) {
  12102. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  12103. return this;
  12104. this._valueCache[uniformName] = bool;
  12105. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  12106. return this;
  12107. };
  12108. Effect.prototype.setVector2 = function (uniformName, vector2) {
  12109. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  12110. return this;
  12111. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  12112. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  12113. return this;
  12114. };
  12115. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  12116. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  12117. return this;
  12118. this._cacheFloat2(uniformName, x, y);
  12119. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  12120. return this;
  12121. };
  12122. Effect.prototype.setVector3 = function (uniformName, vector3) {
  12123. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  12124. return this;
  12125. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  12126. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  12127. return this;
  12128. };
  12129. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  12130. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  12131. return this;
  12132. this._cacheFloat3(uniformName, x, y, z);
  12133. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  12134. return this;
  12135. };
  12136. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  12137. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  12138. return this;
  12139. this._cacheFloat4(uniformName, x, y, z, w);
  12140. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  12141. return this;
  12142. };
  12143. Effect.prototype.setColor3 = function (uniformName, color3) {
  12144. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  12145. return this;
  12146. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  12147. this._engine.setColor3(this.getUniform(uniformName), color3);
  12148. return this;
  12149. };
  12150. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  12151. 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)
  12152. return this;
  12153. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  12154. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  12155. return this;
  12156. };
  12157. 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}",
  12158. 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}",
  12159. 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}",
  12160. 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}",
  12161. 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}",
  12162. colorPixelShader:"precision highp float;\n\nuniform vec4 color;\n\nvoid main(void) {\n gl_FragColor = color;\n}",
  12163. 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}",
  12164. 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}",
  12165. 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.3 - 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}",
  12166. 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}",
  12167. 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}",
  12168. 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}",
  12169. 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}",
  12170. 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}",
  12171. 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}",
  12172. 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}",
  12173. 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}",
  12174. 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}",
  12175. 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}",
  12176. 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}",
  12177. 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}",
  12178. 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}",
  12179. 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}",
  12180. 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}",
  12181. 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}",
  12182. 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}",
  12183. 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}",
  12184. 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}",
  12185. 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}",
  12186. 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}",
  12187. 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}",
  12188. 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}",
  12189. 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}",
  12190. 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}",
  12191. 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}",
  12192. 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}",
  12193. 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}",
  12194. };
  12195. return Effect;
  12196. })();
  12197. BABYLON.Effect = Effect;
  12198. })(BABYLON || (BABYLON = {}));
  12199. //# sourceMappingURL=babylon.effect.js.map
  12200. var BABYLON;
  12201. (function (BABYLON) {
  12202. var Material = (function () {
  12203. function Material(name, scene, doNotAdd) {
  12204. this.name = name;
  12205. this.checkReadyOnEveryCall = true;
  12206. this.checkReadyOnlyOnce = false;
  12207. this.state = "";
  12208. this.alpha = 1.0;
  12209. this.backFaceCulling = true;
  12210. this._wasPreviouslyReady = false;
  12211. this._fillMode = Material.TriangleFillMode;
  12212. this.pointSize = 1.0;
  12213. this.id = name;
  12214. this._scene = scene;
  12215. if (!doNotAdd) {
  12216. scene.materials.push(this);
  12217. }
  12218. }
  12219. Object.defineProperty(Material, "TriangleFillMode", {
  12220. get: function () {
  12221. return Material._TriangleFillMode;
  12222. },
  12223. enumerable: true,
  12224. configurable: true
  12225. });
  12226. Object.defineProperty(Material, "WireFrameFillMode", {
  12227. get: function () {
  12228. return Material._WireFrameFillMode;
  12229. },
  12230. enumerable: true,
  12231. configurable: true
  12232. });
  12233. Object.defineProperty(Material, "PointFillMode", {
  12234. get: function () {
  12235. return Material._PointFillMode;
  12236. },
  12237. enumerable: true,
  12238. configurable: true
  12239. });
  12240. Object.defineProperty(Material.prototype, "wireframe", {
  12241. get: function () {
  12242. return this._fillMode === Material.WireFrameFillMode;
  12243. },
  12244. set: function (value) {
  12245. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  12246. },
  12247. enumerable: true,
  12248. configurable: true
  12249. });
  12250. Object.defineProperty(Material.prototype, "pointsCloud", {
  12251. get: function () {
  12252. return this._fillMode === Material.PointFillMode;
  12253. },
  12254. set: function (value) {
  12255. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  12256. },
  12257. enumerable: true,
  12258. configurable: true
  12259. });
  12260. Object.defineProperty(Material.prototype, "fillMode", {
  12261. get: function () {
  12262. return this._fillMode;
  12263. },
  12264. set: function (value) {
  12265. this._fillMode = value;
  12266. },
  12267. enumerable: true,
  12268. configurable: true
  12269. });
  12270. Material.prototype.isReady = function (mesh, useInstances) {
  12271. return true;
  12272. };
  12273. Material.prototype.getEffect = function () {
  12274. return this._effect;
  12275. };
  12276. Material.prototype.getScene = function () {
  12277. return this._scene;
  12278. };
  12279. Material.prototype.needAlphaBlending = function () {
  12280. return (this.alpha < 1.0);
  12281. };
  12282. Material.prototype.needAlphaTesting = function () {
  12283. return false;
  12284. };
  12285. Material.prototype.getAlphaTestTexture = function () {
  12286. return null;
  12287. };
  12288. Material.prototype.trackCreation = function (onCompiled, onError) {
  12289. };
  12290. Material.prototype._preBind = function () {
  12291. var engine = this._scene.getEngine();
  12292. engine.enableEffect(this._effect);
  12293. engine.setState(this.backFaceCulling);
  12294. };
  12295. Material.prototype.bind = function (world, mesh) {
  12296. this._scene._cachedMaterial = this;
  12297. if (this.onBind) {
  12298. this.onBind(this);
  12299. }
  12300. };
  12301. Material.prototype.bindOnlyWorldMatrix = function (world) {
  12302. };
  12303. Material.prototype.unbind = function () {
  12304. };
  12305. Material.prototype.dispose = function (forceDisposeEffect) {
  12306. // Remove from scene
  12307. var index = this._scene.materials.indexOf(this);
  12308. this._scene.materials.splice(index, 1);
  12309. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  12310. if (forceDisposeEffect && this._effect) {
  12311. this._scene.getEngine()._releaseEffect(this._effect);
  12312. this._effect = null;
  12313. }
  12314. // Callback
  12315. if (this.onDispose) {
  12316. this.onDispose();
  12317. }
  12318. };
  12319. Material._TriangleFillMode = 0;
  12320. Material._WireFrameFillMode = 1;
  12321. Material._PointFillMode = 2;
  12322. return Material;
  12323. })();
  12324. BABYLON.Material = Material;
  12325. })(BABYLON || (BABYLON = {}));
  12326. //# sourceMappingURL=babylon.material.js.map
  12327. var BABYLON;
  12328. (function (BABYLON) {
  12329. var maxSimultaneousLights = 4;
  12330. var FresnelParameters = (function () {
  12331. function FresnelParameters() {
  12332. this.isEnabled = true;
  12333. this.leftColor = BABYLON.Color3.White();
  12334. this.rightColor = BABYLON.Color3.Black();
  12335. this.bias = 0;
  12336. this.power = 1;
  12337. }
  12338. return FresnelParameters;
  12339. })();
  12340. BABYLON.FresnelParameters = FresnelParameters;
  12341. var StandardMaterial = (function (_super) {
  12342. __extends(StandardMaterial, _super);
  12343. function StandardMaterial(name, scene) {
  12344. var _this = this;
  12345. _super.call(this, name, scene);
  12346. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  12347. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  12348. this.specularColor = new BABYLON.Color3(1, 1, 1);
  12349. this.specularPower = 64;
  12350. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  12351. this.useAlphaFromDiffuseTexture = false;
  12352. this.useSpecularOverAlpha = true;
  12353. this.fogEnabled = true;
  12354. this._cachedDefines = null;
  12355. this._renderTargets = new BABYLON.SmartArray(16);
  12356. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  12357. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  12358. this._scaledDiffuse = new BABYLON.Color3();
  12359. this._scaledSpecular = new BABYLON.Color3();
  12360. this.getRenderTargetTextures = function () {
  12361. _this._renderTargets.reset();
  12362. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  12363. _this._renderTargets.push(_this.reflectionTexture);
  12364. }
  12365. return _this._renderTargets;
  12366. };
  12367. }
  12368. StandardMaterial.prototype.needAlphaBlending = function () {
  12369. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  12370. };
  12371. StandardMaterial.prototype.needAlphaTesting = function () {
  12372. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && !this.diffuseTexture.getAlphaFromRGB;
  12373. };
  12374. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  12375. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  12376. };
  12377. StandardMaterial.prototype.getAlphaTestTexture = function () {
  12378. return this.diffuseTexture;
  12379. };
  12380. // Methods
  12381. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  12382. if (this.checkReadyOnlyOnce) {
  12383. if (this._wasPreviouslyReady) {
  12384. return true;
  12385. }
  12386. }
  12387. var scene = this.getScene();
  12388. if (!this.checkReadyOnEveryCall) {
  12389. if (this._renderId === scene.getRenderId()) {
  12390. return true;
  12391. }
  12392. }
  12393. var engine = scene.getEngine();
  12394. var defines = [];
  12395. var fallbacks = new BABYLON.EffectFallbacks();
  12396. // Textures
  12397. if (scene.texturesEnabled) {
  12398. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  12399. if (!this.diffuseTexture.isReady()) {
  12400. return false;
  12401. } else {
  12402. defines.push("#define DIFFUSE");
  12403. }
  12404. }
  12405. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  12406. if (!this.ambientTexture.isReady()) {
  12407. return false;
  12408. } else {
  12409. defines.push("#define AMBIENT");
  12410. }
  12411. }
  12412. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  12413. if (!this.opacityTexture.isReady()) {
  12414. return false;
  12415. } else {
  12416. defines.push("#define OPACITY");
  12417. if (this.opacityTexture.getAlphaFromRGB) {
  12418. defines.push("#define OPACITYRGB");
  12419. }
  12420. }
  12421. }
  12422. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  12423. if (!this.reflectionTexture.isReady()) {
  12424. return false;
  12425. } else {
  12426. defines.push("#define REFLECTION");
  12427. fallbacks.addFallback(0, "REFLECTION");
  12428. }
  12429. }
  12430. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  12431. if (!this.emissiveTexture.isReady()) {
  12432. return false;
  12433. } else {
  12434. defines.push("#define EMISSIVE");
  12435. }
  12436. }
  12437. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  12438. if (!this.specularTexture.isReady()) {
  12439. return false;
  12440. } else {
  12441. defines.push("#define SPECULAR");
  12442. fallbacks.addFallback(0, "SPECULAR");
  12443. }
  12444. }
  12445. }
  12446. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  12447. if (!this.bumpTexture.isReady()) {
  12448. return false;
  12449. } else {
  12450. defines.push("#define BUMP");
  12451. fallbacks.addFallback(0, "BUMP");
  12452. }
  12453. }
  12454. // Effect
  12455. if (this.useSpecularOverAlpha) {
  12456. defines.push("#define SPECULAROVERALPHA");
  12457. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  12458. }
  12459. if (scene.clipPlane) {
  12460. defines.push("#define CLIPPLANE");
  12461. }
  12462. if (engine.getAlphaTesting()) {
  12463. defines.push("#define ALPHATEST");
  12464. }
  12465. if (this._shouldUseAlphaFromDiffuseTexture()) {
  12466. defines.push("#define ALPHAFROMDIFFUSE");
  12467. }
  12468. // Point size
  12469. if (this.pointsCloud || scene.forcePointsCloud) {
  12470. defines.push("#define POINTSIZE");
  12471. }
  12472. // Fog
  12473. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  12474. defines.push("#define FOG");
  12475. fallbacks.addFallback(1, "FOG");
  12476. }
  12477. var shadowsActivated = false;
  12478. var lightIndex = 0;
  12479. if (scene.lightsEnabled) {
  12480. for (var index = 0; index < scene.lights.length; index++) {
  12481. var light = scene.lights[index];
  12482. if (!light.isEnabled()) {
  12483. continue;
  12484. }
  12485. // Excluded check
  12486. if (light._excludedMeshesIds.length > 0) {
  12487. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  12488. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  12489. if (excludedMesh) {
  12490. light.excludedMeshes.push(excludedMesh);
  12491. }
  12492. }
  12493. light._excludedMeshesIds = [];
  12494. }
  12495. // Included check
  12496. if (light._includedOnlyMeshesIds.length > 0) {
  12497. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  12498. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  12499. if (includedOnlyMesh) {
  12500. light.includedOnlyMeshes.push(includedOnlyMesh);
  12501. }
  12502. }
  12503. light._includedOnlyMeshesIds = [];
  12504. }
  12505. if (!light.canAffectMesh(mesh)) {
  12506. continue;
  12507. }
  12508. defines.push("#define LIGHT" + lightIndex);
  12509. if (lightIndex > 0) {
  12510. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  12511. }
  12512. var type;
  12513. if (light instanceof BABYLON.SpotLight) {
  12514. type = "#define SPOTLIGHT" + lightIndex;
  12515. } else if (light instanceof BABYLON.HemisphericLight) {
  12516. type = "#define HEMILIGHT" + lightIndex;
  12517. } else {
  12518. type = "#define POINTDIRLIGHT" + lightIndex;
  12519. }
  12520. defines.push(type);
  12521. if (lightIndex > 0) {
  12522. fallbacks.addFallback(lightIndex, type.replace("#define ", ""));
  12523. }
  12524. // Shadows
  12525. if (scene.shadowsEnabled) {
  12526. var shadowGenerator = light.getShadowGenerator();
  12527. if (mesh && mesh.receiveShadows && shadowGenerator) {
  12528. defines.push("#define SHADOW" + lightIndex);
  12529. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  12530. if (!shadowsActivated) {
  12531. defines.push("#define SHADOWS");
  12532. shadowsActivated = true;
  12533. }
  12534. if (shadowGenerator.useVarianceShadowMap) {
  12535. defines.push("#define SHADOWVSM" + lightIndex);
  12536. if (lightIndex > 0) {
  12537. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  12538. }
  12539. }
  12540. if (shadowGenerator.usePoissonSampling) {
  12541. defines.push("#define SHADOWPCF" + lightIndex);
  12542. if (lightIndex > 0) {
  12543. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  12544. }
  12545. }
  12546. }
  12547. }
  12548. lightIndex++;
  12549. if (lightIndex === maxSimultaneousLights)
  12550. break;
  12551. }
  12552. }
  12553. if (StandardMaterial.FresnelEnabled) {
  12554. // Fresnel
  12555. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled || this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled || this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  12556. var fresnelRank = 1;
  12557. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  12558. defines.push("#define DIFFUSEFRESNEL");
  12559. fallbacks.addFallback(fresnelRank, "DIFFUSEFRESNEL");
  12560. fresnelRank++;
  12561. }
  12562. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  12563. defines.push("#define OPACITYFRESNEL");
  12564. fallbacks.addFallback(fresnelRank, "OPACITYFRESNEL");
  12565. fresnelRank++;
  12566. }
  12567. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  12568. defines.push("#define REFLECTIONFRESNEL");
  12569. fallbacks.addFallback(fresnelRank, "REFLECTIONFRESNEL");
  12570. fresnelRank++;
  12571. }
  12572. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  12573. defines.push("#define EMISSIVEFRESNEL");
  12574. fallbacks.addFallback(fresnelRank, "EMISSIVEFRESNEL");
  12575. fresnelRank++;
  12576. }
  12577. defines.push("#define FRESNEL");
  12578. fallbacks.addFallback(fresnelRank - 1, "FRESNEL");
  12579. }
  12580. }
  12581. // Attribs
  12582. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  12583. if (mesh) {
  12584. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  12585. attribs.push(BABYLON.VertexBuffer.UVKind);
  12586. defines.push("#define UV1");
  12587. }
  12588. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  12589. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  12590. defines.push("#define UV2");
  12591. }
  12592. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  12593. attribs.push(BABYLON.VertexBuffer.ColorKind);
  12594. defines.push("#define VERTEXCOLOR");
  12595. if (mesh.hasVertexAlpha) {
  12596. defines.push("#define VERTEXALPHA");
  12597. }
  12598. }
  12599. if (mesh.skeleton && scene.skeletonsEnabled && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  12600. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  12601. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  12602. defines.push("#define BONES");
  12603. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  12604. defines.push("#define BONES4");
  12605. fallbacks.addFallback(0, "BONES4");
  12606. }
  12607. // Instances
  12608. if (useInstances) {
  12609. defines.push("#define INSTANCES");
  12610. attribs.push("world0");
  12611. attribs.push("world1");
  12612. attribs.push("world2");
  12613. attribs.push("world3");
  12614. }
  12615. }
  12616. // Get correct effect
  12617. var join = defines.join("\n");
  12618. if (this._cachedDefines !== join) {
  12619. this._cachedDefines = join;
  12620. scene.resetCachedMaterial();
  12621. // Legacy browser patch
  12622. var shaderName = "default";
  12623. if (!scene.getEngine().getCaps().standardDerivatives) {
  12624. shaderName = "legacydefault";
  12625. }
  12626. this._effect = scene.getEngine().createEffect(shaderName, attribs, [
  12627. "world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  12628. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  12629. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  12630. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  12631. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  12632. "vFogInfos", "vFogColor", "pointSize",
  12633. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos",
  12634. "mBones",
  12635. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix",
  12636. "darkness0", "darkness1", "darkness2", "darkness3",
  12637. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor"
  12638. ], [
  12639. "diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler",
  12640. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  12641. ], join, fallbacks, this.onCompiled, this.onError);
  12642. }
  12643. if (!this._effect.isReady()) {
  12644. return false;
  12645. }
  12646. this._renderId = scene.getRenderId();
  12647. this._wasPreviouslyReady = true;
  12648. return true;
  12649. };
  12650. StandardMaterial.prototype.unbind = function () {
  12651. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  12652. this._effect.setTexture("reflection2DSampler", null);
  12653. }
  12654. };
  12655. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  12656. this._effect.setMatrix("world", world);
  12657. };
  12658. StandardMaterial.prototype.bind = function (world, mesh) {
  12659. var scene = this.getScene();
  12660. // Matrices
  12661. this.bindOnlyWorldMatrix(world);
  12662. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  12663. // Bones
  12664. if (mesh.skeleton && scene.skeletonsEnabled && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  12665. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  12666. }
  12667. if (scene.getCachedMaterial() !== this) {
  12668. if (StandardMaterial.FresnelEnabled) {
  12669. // Fresnel
  12670. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  12671. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  12672. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  12673. }
  12674. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  12675. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  12676. }
  12677. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  12678. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  12679. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  12680. }
  12681. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  12682. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  12683. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  12684. }
  12685. }
  12686. // Textures
  12687. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  12688. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  12689. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  12690. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  12691. }
  12692. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  12693. this._effect.setTexture("ambientSampler", this.ambientTexture);
  12694. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  12695. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  12696. }
  12697. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  12698. this._effect.setTexture("opacitySampler", this.opacityTexture);
  12699. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  12700. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  12701. }
  12702. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  12703. if (this.reflectionTexture.isCube) {
  12704. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  12705. } else {
  12706. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  12707. }
  12708. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  12709. this._effect.setFloat3("vReflectionInfos", this.reflectionTexture.coordinatesMode, this.reflectionTexture.level, this.reflectionTexture.isCube ? 1 : 0);
  12710. }
  12711. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  12712. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  12713. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  12714. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  12715. }
  12716. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  12717. this._effect.setTexture("specularSampler", this.specularTexture);
  12718. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  12719. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  12720. }
  12721. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  12722. this._effect.setTexture("bumpSampler", this.bumpTexture);
  12723. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level);
  12724. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  12725. }
  12726. // Clip plane
  12727. if (scene.clipPlane) {
  12728. var clipPlane = scene.clipPlane;
  12729. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  12730. }
  12731. // Point size
  12732. if (this.pointsCloud) {
  12733. this._effect.setFloat("pointSize", this.pointSize);
  12734. }
  12735. // Colors
  12736. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  12737. // Scaling down color according to emissive
  12738. this._scaledSpecular.r = this.specularColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  12739. this._scaledSpecular.g = this.specularColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  12740. this._scaledSpecular.b = this.specularColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  12741. this._effect.setVector3("vEyePosition", scene.activeCamera.position);
  12742. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  12743. this._effect.setColor4("vSpecularColor", this._scaledSpecular, this.specularPower);
  12744. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  12745. }
  12746. // Scaling down color according to emissive
  12747. this._scaledDiffuse.r = this.diffuseColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  12748. this._scaledDiffuse.g = this.diffuseColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  12749. this._scaledDiffuse.b = this.diffuseColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  12750. this._effect.setColor4("vDiffuseColor", this._scaledDiffuse, this.alpha * mesh.visibility);
  12751. if (scene.lightsEnabled) {
  12752. var lightIndex = 0;
  12753. for (var index = 0; index < scene.lights.length; index++) {
  12754. var light = scene.lights[index];
  12755. if (!light.isEnabled()) {
  12756. continue;
  12757. }
  12758. if (!light.canAffectMesh(mesh)) {
  12759. continue;
  12760. }
  12761. if (light instanceof BABYLON.PointLight) {
  12762. // Point Light
  12763. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  12764. } else if (light instanceof BABYLON.DirectionalLight) {
  12765. // Directional Light
  12766. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  12767. } else if (light instanceof BABYLON.SpotLight) {
  12768. // Spot Light
  12769. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  12770. } else if (light instanceof BABYLON.HemisphericLight) {
  12771. // Hemispheric Light
  12772. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  12773. }
  12774. light.diffuse.scaleToRef(light.intensity, this._scaledDiffuse);
  12775. light.specular.scaleToRef(light.intensity, this._scaledSpecular);
  12776. this._effect.setColor4("vLightDiffuse" + lightIndex, this._scaledDiffuse, light.range);
  12777. this._effect.setColor3("vLightSpecular" + lightIndex, this._scaledSpecular);
  12778. // Shadows
  12779. if (scene.shadowsEnabled) {
  12780. var shadowGenerator = light.getShadowGenerator();
  12781. if (mesh.receiveShadows && shadowGenerator) {
  12782. this._effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  12783. this._effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMap());
  12784. this._effect.setFloat("darkness" + lightIndex, shadowGenerator.getDarkness());
  12785. }
  12786. }
  12787. lightIndex++;
  12788. if (lightIndex === maxSimultaneousLights)
  12789. break;
  12790. }
  12791. }
  12792. // View
  12793. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  12794. this._effect.setMatrix("view", scene.getViewMatrix());
  12795. }
  12796. // Fog
  12797. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  12798. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  12799. this._effect.setColor3("vFogColor", scene.fogColor);
  12800. }
  12801. _super.prototype.bind.call(this, world, mesh);
  12802. };
  12803. StandardMaterial.prototype.getAnimatables = function () {
  12804. var results = [];
  12805. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  12806. results.push(this.diffuseTexture);
  12807. }
  12808. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  12809. results.push(this.ambientTexture);
  12810. }
  12811. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  12812. results.push(this.opacityTexture);
  12813. }
  12814. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  12815. results.push(this.reflectionTexture);
  12816. }
  12817. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  12818. results.push(this.emissiveTexture);
  12819. }
  12820. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  12821. results.push(this.specularTexture);
  12822. }
  12823. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  12824. results.push(this.bumpTexture);
  12825. }
  12826. return results;
  12827. };
  12828. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  12829. if (this.diffuseTexture) {
  12830. this.diffuseTexture.dispose();
  12831. }
  12832. if (this.ambientTexture) {
  12833. this.ambientTexture.dispose();
  12834. }
  12835. if (this.opacityTexture) {
  12836. this.opacityTexture.dispose();
  12837. }
  12838. if (this.reflectionTexture) {
  12839. this.reflectionTexture.dispose();
  12840. }
  12841. if (this.emissiveTexture) {
  12842. this.emissiveTexture.dispose();
  12843. }
  12844. if (this.specularTexture) {
  12845. this.specularTexture.dispose();
  12846. }
  12847. if (this.bumpTexture) {
  12848. this.bumpTexture.dispose();
  12849. }
  12850. _super.prototype.dispose.call(this, forceDisposeEffect);
  12851. };
  12852. StandardMaterial.prototype.clone = function (name) {
  12853. var newStandardMaterial = new StandardMaterial(name, this.getScene());
  12854. // Base material
  12855. newStandardMaterial.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  12856. newStandardMaterial.alpha = this.alpha;
  12857. newStandardMaterial.fillMode = this.fillMode;
  12858. newStandardMaterial.backFaceCulling = this.backFaceCulling;
  12859. // Standard material
  12860. if (this.diffuseTexture && this.diffuseTexture.clone) {
  12861. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  12862. }
  12863. if (this.ambientTexture && this.ambientTexture.clone) {
  12864. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  12865. }
  12866. if (this.opacityTexture && this.opacityTexture.clone) {
  12867. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  12868. }
  12869. if (this.reflectionTexture && this.reflectionTexture.clone) {
  12870. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  12871. }
  12872. if (this.emissiveTexture && this.emissiveTexture.clone) {
  12873. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  12874. }
  12875. if (this.specularTexture && this.specularTexture.clone) {
  12876. newStandardMaterial.specularTexture = this.specularTexture.clone();
  12877. }
  12878. if (this.bumpTexture && this.bumpTexture.clone) {
  12879. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  12880. }
  12881. newStandardMaterial.ambientColor = this.ambientColor.clone();
  12882. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  12883. newStandardMaterial.specularColor = this.specularColor.clone();
  12884. newStandardMaterial.specularPower = this.specularPower;
  12885. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  12886. return newStandardMaterial;
  12887. };
  12888. StandardMaterial.DiffuseTextureEnabled = true;
  12889. StandardMaterial.AmbientTextureEnabled = true;
  12890. StandardMaterial.OpacityTextureEnabled = true;
  12891. StandardMaterial.ReflectionTextureEnabled = true;
  12892. StandardMaterial.EmissiveTextureEnabled = true;
  12893. StandardMaterial.SpecularTextureEnabled = true;
  12894. StandardMaterial.BumpTextureEnabled = true;
  12895. StandardMaterial.FresnelEnabled = true;
  12896. return StandardMaterial;
  12897. })(BABYLON.Material);
  12898. BABYLON.StandardMaterial = StandardMaterial;
  12899. })(BABYLON || (BABYLON = {}));
  12900. //# sourceMappingURL=babylon.standardMaterial.js.map
  12901. var BABYLON;
  12902. (function (BABYLON) {
  12903. var MultiMaterial = (function (_super) {
  12904. __extends(MultiMaterial, _super);
  12905. function MultiMaterial(name, scene) {
  12906. _super.call(this, name, scene, true);
  12907. this.subMaterials = new Array();
  12908. scene.multiMaterials.push(this);
  12909. }
  12910. // Properties
  12911. MultiMaterial.prototype.getSubMaterial = function (index) {
  12912. if (index < 0 || index >= this.subMaterials.length) {
  12913. return this.getScene().defaultMaterial;
  12914. }
  12915. return this.subMaterials[index];
  12916. };
  12917. // Methods
  12918. MultiMaterial.prototype.isReady = function (mesh) {
  12919. for (var index = 0; index < this.subMaterials.length; index++) {
  12920. var subMaterial = this.subMaterials[index];
  12921. if (subMaterial) {
  12922. if (!this.subMaterials[index].isReady(mesh)) {
  12923. return false;
  12924. }
  12925. }
  12926. }
  12927. return true;
  12928. };
  12929. return MultiMaterial;
  12930. })(BABYLON.Material);
  12931. BABYLON.MultiMaterial = MultiMaterial;
  12932. })(BABYLON || (BABYLON = {}));
  12933. //# sourceMappingURL=babylon.multiMaterial.js.map
  12934. var BABYLON;
  12935. (function (BABYLON) {
  12936. var Database = (function () {
  12937. function Database(urlToScene, callbackManifestChecked) {
  12938. // Handling various flavors of prefixed version of IndexedDB
  12939. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  12940. this.callbackManifestChecked = callbackManifestChecked;
  12941. this.currentSceneUrl = BABYLON.Database.ReturnFullUrlLocation(urlToScene);
  12942. this.db = null;
  12943. this.enableSceneOffline = false;
  12944. this.enableTexturesOffline = false;
  12945. this.manifestVersionFound = 0;
  12946. this.mustUpdateRessources = false;
  12947. this.hasReachedQuota = false;
  12948. this.checkManifestFile();
  12949. }
  12950. Database.prototype.checkManifestFile = function () {
  12951. var _this = this;
  12952. function noManifestFile() {
  12953. BABYLON.Tools.Log("Valid manifest file not found. Scene & textures will be loaded directly from the web server.");
  12954. that.enableSceneOffline = false;
  12955. that.enableTexturesOffline = false;
  12956. that.callbackManifestChecked(false);
  12957. }
  12958. var that = this;
  12959. var manifestURL = this.currentSceneUrl + ".manifest";
  12960. var xhr = new XMLHttpRequest();
  12961. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  12962. xhr.open("GET", manifestURLTimeStamped, true);
  12963. xhr.addEventListener("load", function () {
  12964. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  12965. try {
  12966. var manifestFile = JSON.parse(xhr.response);
  12967. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  12968. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  12969. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  12970. _this.manifestVersionFound = manifestFile.version;
  12971. }
  12972. if (_this.callbackManifestChecked) {
  12973. _this.callbackManifestChecked(true);
  12974. }
  12975. } catch (ex) {
  12976. noManifestFile();
  12977. }
  12978. } else {
  12979. noManifestFile();
  12980. }
  12981. }, false);
  12982. xhr.addEventListener("error", function (event) {
  12983. noManifestFile();
  12984. }, false);
  12985. try {
  12986. xhr.send();
  12987. } catch (ex) {
  12988. BABYLON.Tools.Error("Error on XHR send request.");
  12989. that.callbackManifestChecked(false);
  12990. }
  12991. };
  12992. Database.prototype.openAsync = function (successCallback, errorCallback) {
  12993. var _this = this;
  12994. function handleError() {
  12995. that.isSupported = false;
  12996. if (errorCallback)
  12997. errorCallback();
  12998. }
  12999. var that = this;
  13000. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  13001. // Your browser doesn't support IndexedDB
  13002. this.isSupported = false;
  13003. if (errorCallback)
  13004. errorCallback();
  13005. } else {
  13006. // If the DB hasn't been opened or created yet
  13007. if (!this.db) {
  13008. this.hasReachedQuota = false;
  13009. this.isSupported = true;
  13010. var request = this.idbFactory.open("babylonjs", 1);
  13011. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  13012. request.onerror = function (event) {
  13013. handleError();
  13014. };
  13015. // executes when a version change transaction cannot complete due to other active transactions
  13016. request.onblocked = function (event) {
  13017. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  13018. handleError();
  13019. };
  13020. // DB has been opened successfully
  13021. request.onsuccess = function (event) {
  13022. _this.db = request.result;
  13023. successCallback();
  13024. };
  13025. // Initialization of the DB. Creating Scenes & Textures stores
  13026. request.onupgradeneeded = function (event) {
  13027. _this.db = (event.target).result;
  13028. try {
  13029. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  13030. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  13031. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  13032. } catch (ex) {
  13033. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  13034. handleError();
  13035. }
  13036. };
  13037. } else {
  13038. if (successCallback)
  13039. successCallback();
  13040. }
  13041. }
  13042. };
  13043. Database.prototype.loadImageFromDB = function (url, image) {
  13044. var _this = this;
  13045. var completeURL = BABYLON.Database.ReturnFullUrlLocation(url);
  13046. var saveAndLoadImage = function () {
  13047. if (!_this.hasReachedQuota && _this.db !== null) {
  13048. // the texture is not yet in the DB, let's try to save it
  13049. _this._saveImageIntoDBAsync(completeURL, image);
  13050. } else {
  13051. image.src = url;
  13052. }
  13053. };
  13054. if (!this.mustUpdateRessources) {
  13055. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  13056. } else {
  13057. saveAndLoadImage();
  13058. }
  13059. };
  13060. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  13061. if (this.isSupported && this.db !== null) {
  13062. var texture;
  13063. var transaction = this.db.transaction(["textures"]);
  13064. transaction.onabort = function (event) {
  13065. image.src = url;
  13066. };
  13067. transaction.oncomplete = function (event) {
  13068. var blobTextureURL;
  13069. if (texture) {
  13070. var URL = window.URL || window.webkitURL;
  13071. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  13072. image.onerror = function () {
  13073. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  13074. image.src = url;
  13075. };
  13076. image.src = blobTextureURL;
  13077. } else {
  13078. notInDBCallback();
  13079. }
  13080. };
  13081. var getRequest = transaction.objectStore("textures").get(url);
  13082. getRequest.onsuccess = function (event) {
  13083. texture = (event.target).result;
  13084. };
  13085. getRequest.onerror = function (event) {
  13086. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  13087. image.src = url;
  13088. };
  13089. } else {
  13090. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  13091. image.src = url;
  13092. }
  13093. };
  13094. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  13095. var _this = this;
  13096. if (this.isSupported) {
  13097. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  13098. var generateBlobUrl = function () {
  13099. var blobTextureURL;
  13100. if (blob) {
  13101. var URL = window.URL || window.webkitURL;
  13102. try {
  13103. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  13104. } catch (ex) {
  13105. blobTextureURL = URL.createObjectURL(blob);
  13106. }
  13107. }
  13108. image.src = blobTextureURL;
  13109. };
  13110. if (BABYLON.Database.isUASupportingBlobStorage) {
  13111. var xhr = new XMLHttpRequest(), blob;
  13112. xhr.open("GET", url, true);
  13113. xhr.responseType = "blob";
  13114. xhr.addEventListener("load", function () {
  13115. if (xhr.status === 200) {
  13116. // Blob as response (XHR2)
  13117. blob = xhr.response;
  13118. var transaction = _this.db.transaction(["textures"], "readwrite");
  13119. // the transaction could abort because of a QuotaExceededError error
  13120. transaction.onabort = function (event) {
  13121. try {
  13122. if (event.srcElement.error.name === "QuotaExceededError") {
  13123. this.hasReachedQuota = true;
  13124. }
  13125. } catch (ex) {
  13126. }
  13127. generateBlobUrl();
  13128. };
  13129. transaction.oncomplete = function (event) {
  13130. generateBlobUrl();
  13131. };
  13132. var newTexture = { textureUrl: url, data: blob };
  13133. try {
  13134. // Put the blob into the dabase
  13135. var addRequest = transaction.objectStore("textures").put(newTexture);
  13136. addRequest.onsuccess = function (event) {
  13137. };
  13138. addRequest.onerror = function (event) {
  13139. generateBlobUrl();
  13140. };
  13141. } catch (ex) {
  13142. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  13143. if (ex.code === 25) {
  13144. BABYLON.Database.isUASupportingBlobStorage = false;
  13145. }
  13146. image.src = url;
  13147. }
  13148. } else {
  13149. image.src = url;
  13150. }
  13151. }, false);
  13152. xhr.addEventListener("error", function (event) {
  13153. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  13154. image.src = url;
  13155. }, false);
  13156. xhr.send();
  13157. } else {
  13158. image.src = url;
  13159. }
  13160. } else {
  13161. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  13162. image.src = url;
  13163. }
  13164. };
  13165. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  13166. var _this = this;
  13167. var updateVersion = function (event) {
  13168. // the version is not yet in the DB or we need to update it
  13169. _this._saveVersionIntoDBAsync(url, versionLoaded);
  13170. };
  13171. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  13172. };
  13173. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  13174. var _this = this;
  13175. if (this.isSupported) {
  13176. var version;
  13177. try {
  13178. var transaction = this.db.transaction(["versions"]);
  13179. transaction.oncomplete = function (event) {
  13180. if (version) {
  13181. // If the version in the JSON file is > than the version in DB
  13182. if (_this.manifestVersionFound > version.data) {
  13183. _this.mustUpdateRessources = true;
  13184. updateInDBCallback();
  13185. } else {
  13186. callback(version.data);
  13187. }
  13188. } else {
  13189. _this.mustUpdateRessources = true;
  13190. updateInDBCallback();
  13191. }
  13192. };
  13193. transaction.onabort = function (event) {
  13194. callback(-1);
  13195. };
  13196. var getRequest = transaction.objectStore("versions").get(url);
  13197. getRequest.onsuccess = function (event) {
  13198. version = (event.target).result;
  13199. };
  13200. getRequest.onerror = function (event) {
  13201. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  13202. callback(-1);
  13203. };
  13204. } catch (ex) {
  13205. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  13206. callback(-1);
  13207. }
  13208. } else {
  13209. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  13210. callback(-1);
  13211. }
  13212. };
  13213. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  13214. var _this = this;
  13215. if (this.isSupported && !this.hasReachedQuota) {
  13216. try {
  13217. // Open a transaction to the database
  13218. var transaction = this.db.transaction(["versions"], "readwrite");
  13219. // the transaction could abort because of a QuotaExceededError error
  13220. transaction.onabort = function (event) {
  13221. try {
  13222. if (event.srcElement.error.name === "QuotaExceededError") {
  13223. _this.hasReachedQuota = true;
  13224. }
  13225. } catch (ex) {
  13226. }
  13227. callback(-1);
  13228. };
  13229. transaction.oncomplete = function (event) {
  13230. callback(_this.manifestVersionFound);
  13231. };
  13232. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  13233. // Put the scene into the database
  13234. var addRequest = transaction.objectStore("versions").put(newVersion);
  13235. addRequest.onsuccess = function (event) {
  13236. };
  13237. addRequest.onerror = function (event) {
  13238. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  13239. };
  13240. } catch (ex) {
  13241. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  13242. callback(-1);
  13243. }
  13244. } else {
  13245. callback(-1);
  13246. }
  13247. };
  13248. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  13249. var _this = this;
  13250. var completeUrl = BABYLON.Database.ReturnFullUrlLocation(url);
  13251. var saveAndLoadFile = function (event) {
  13252. // the scene is not yet in the DB, let's try to save it
  13253. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  13254. };
  13255. this._checkVersionFromDB(completeUrl, function (version) {
  13256. if (version !== -1) {
  13257. if (!_this.mustUpdateRessources) {
  13258. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  13259. } else {
  13260. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  13261. }
  13262. } else {
  13263. errorCallback();
  13264. }
  13265. });
  13266. };
  13267. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  13268. if (this.isSupported) {
  13269. var targetStore;
  13270. if (url.indexOf(".babylon") !== -1) {
  13271. targetStore = "scenes";
  13272. } else {
  13273. targetStore = "textures";
  13274. }
  13275. var file;
  13276. var transaction = this.db.transaction([targetStore]);
  13277. transaction.oncomplete = function (event) {
  13278. if (file) {
  13279. callback(file.data);
  13280. } else {
  13281. notInDBCallback();
  13282. }
  13283. };
  13284. transaction.onabort = function (event) {
  13285. notInDBCallback();
  13286. };
  13287. var getRequest = transaction.objectStore(targetStore).get(url);
  13288. getRequest.onsuccess = function (event) {
  13289. file = (event.target).result;
  13290. };
  13291. getRequest.onerror = function (event) {
  13292. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  13293. notInDBCallback();
  13294. };
  13295. } else {
  13296. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  13297. callback();
  13298. }
  13299. };
  13300. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  13301. var _this = this;
  13302. if (this.isSupported) {
  13303. var targetStore;
  13304. if (url.indexOf(".babylon") !== -1) {
  13305. targetStore = "scenes";
  13306. } else {
  13307. targetStore = "textures";
  13308. }
  13309. // Create XHR
  13310. var xhr = new XMLHttpRequest(), fileData;
  13311. xhr.open("GET", url, true);
  13312. if (useArrayBuffer) {
  13313. xhr.responseType = "arraybuffer";
  13314. }
  13315. xhr.onprogress = progressCallback;
  13316. xhr.addEventListener("load", function () {
  13317. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  13318. // Blob as response (XHR2)
  13319. //fileData = xhr.responseText;
  13320. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  13321. if (!_this.hasReachedQuota) {
  13322. // Open a transaction to the database
  13323. var transaction = _this.db.transaction([targetStore], "readwrite");
  13324. // the transaction could abort because of a QuotaExceededError error
  13325. transaction.onabort = function (event) {
  13326. try {
  13327. if (event.srcElement.error.name === "QuotaExceededError") {
  13328. this.hasReachedQuota = true;
  13329. }
  13330. } catch (ex) {
  13331. }
  13332. callback(fileData);
  13333. };
  13334. transaction.oncomplete = function (event) {
  13335. callback(fileData);
  13336. };
  13337. var newFile;
  13338. if (targetStore === "scenes") {
  13339. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  13340. } else {
  13341. newFile = { textureUrl: url, data: fileData };
  13342. }
  13343. try {
  13344. // Put the scene into the database
  13345. var addRequest = transaction.objectStore(targetStore).put(newFile);
  13346. addRequest.onsuccess = function (event) {
  13347. };
  13348. addRequest.onerror = function (event) {
  13349. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  13350. };
  13351. } catch (ex) {
  13352. callback(fileData);
  13353. }
  13354. } else {
  13355. callback(fileData);
  13356. }
  13357. } else {
  13358. callback();
  13359. }
  13360. }, false);
  13361. xhr.addEventListener("error", function (event) {
  13362. BABYLON.Tools.Error("error on XHR request.");
  13363. callback();
  13364. }, false);
  13365. xhr.send();
  13366. } else {
  13367. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  13368. callback();
  13369. }
  13370. };
  13371. Database.isUASupportingBlobStorage = true;
  13372. Database.parseURL = function (url) {
  13373. var a = document.createElement('a');
  13374. a.href = url;
  13375. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  13376. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  13377. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  13378. return absLocation;
  13379. };
  13380. Database.ReturnFullUrlLocation = function (url) {
  13381. if (url.indexOf("http:/") === -1) {
  13382. return (BABYLON.Database.parseURL(window.location.href) + url);
  13383. } else {
  13384. return url;
  13385. }
  13386. };
  13387. return Database;
  13388. })();
  13389. BABYLON.Database = Database;
  13390. })(BABYLON || (BABYLON = {}));
  13391. //# sourceMappingURL=babylon.database.js.map
  13392. var BABYLON;
  13393. (function (BABYLON) {
  13394. var SpriteManager = (function () {
  13395. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon) {
  13396. this.name = name;
  13397. this.cellSize = cellSize;
  13398. this.sprites = new Array();
  13399. this.renderingGroupId = 0;
  13400. this.fogEnabled = true;
  13401. this._vertexDeclaration = [3, 4, 4, 4];
  13402. this._vertexStrideSize = 15 * 4;
  13403. this._capacity = capacity;
  13404. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false);
  13405. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  13406. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  13407. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  13408. this._scene = scene;
  13409. this._scene.spriteManagers.push(this);
  13410. // VBO
  13411. this._vertexDeclaration = [3, 4, 4, 4];
  13412. this._vertexStrideSize = 15 * 4;
  13413. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  13414. var indices = [];
  13415. var index = 0;
  13416. for (var count = 0; count < capacity; count++) {
  13417. indices.push(index);
  13418. indices.push(index + 1);
  13419. indices.push(index + 2);
  13420. indices.push(index);
  13421. indices.push(index + 2);
  13422. indices.push(index + 3);
  13423. index += 4;
  13424. }
  13425. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  13426. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  13427. // Effects
  13428. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  13429. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  13430. }
  13431. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  13432. var arrayOffset = index * 15;
  13433. if (offsetX == 0)
  13434. offsetX = this._epsilon;
  13435. else if (offsetX == 1)
  13436. offsetX = 1 - this._epsilon;
  13437. if (offsetY == 0)
  13438. offsetY = this._epsilon;
  13439. else if (offsetY == 1)
  13440. offsetY = 1 - this._epsilon;
  13441. this._vertices[arrayOffset] = sprite.position.x;
  13442. this._vertices[arrayOffset + 1] = sprite.position.y;
  13443. this._vertices[arrayOffset + 2] = sprite.position.z;
  13444. this._vertices[arrayOffset + 3] = sprite.angle;
  13445. this._vertices[arrayOffset + 4] = sprite.size;
  13446. this._vertices[arrayOffset + 5] = offsetX;
  13447. this._vertices[arrayOffset + 6] = offsetY;
  13448. this._vertices[arrayOffset + 7] = sprite.invertU ? 1 : 0;
  13449. this._vertices[arrayOffset + 8] = sprite.invertV ? 1 : 0;
  13450. var offset = (sprite.cellIndex / rowSize) >> 0;
  13451. this._vertices[arrayOffset + 9] = sprite.cellIndex - offset * rowSize;
  13452. this._vertices[arrayOffset + 10] = offset;
  13453. // Color
  13454. this._vertices[arrayOffset + 11] = sprite.color.r;
  13455. this._vertices[arrayOffset + 12] = sprite.color.g;
  13456. this._vertices[arrayOffset + 13] = sprite.color.b;
  13457. this._vertices[arrayOffset + 14] = sprite.color.a;
  13458. };
  13459. SpriteManager.prototype.render = function () {
  13460. // Check
  13461. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  13462. return;
  13463. var engine = this._scene.getEngine();
  13464. var baseSize = this._spriteTexture.getBaseSize();
  13465. // Sprites
  13466. var deltaTime = engine.getDeltaTime();
  13467. var max = Math.min(this._capacity, this.sprites.length);
  13468. var rowSize = baseSize.width / this.cellSize;
  13469. var offset = 0;
  13470. for (var index = 0; index < max; index++) {
  13471. var sprite = this.sprites[index];
  13472. if (!sprite) {
  13473. continue;
  13474. }
  13475. sprite._animate(deltaTime);
  13476. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  13477. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  13478. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  13479. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  13480. }
  13481. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  13482. // Render
  13483. var effect = this._effectBase;
  13484. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  13485. effect = this._effectFog;
  13486. }
  13487. engine.enableEffect(effect);
  13488. var viewMatrix = this._scene.getViewMatrix();
  13489. effect.setTexture("diffuseSampler", this._spriteTexture);
  13490. effect.setMatrix("view", viewMatrix);
  13491. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  13492. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  13493. // Fog
  13494. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  13495. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  13496. effect.setColor3("vFogColor", this._scene.fogColor);
  13497. }
  13498. // VBOs
  13499. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  13500. // Draw order
  13501. effect.setBool("alphaTest", true);
  13502. engine.setColorWrite(false);
  13503. engine.draw(true, 0, max * 6);
  13504. engine.setColorWrite(true);
  13505. effect.setBool("alphaTest", false);
  13506. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  13507. engine.draw(true, 0, max * 6);
  13508. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  13509. };
  13510. SpriteManager.prototype.dispose = function () {
  13511. if (this._vertexBuffer) {
  13512. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  13513. this._vertexBuffer = null;
  13514. }
  13515. if (this._indexBuffer) {
  13516. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  13517. this._indexBuffer = null;
  13518. }
  13519. if (this._spriteTexture) {
  13520. this._spriteTexture.dispose();
  13521. this._spriteTexture = null;
  13522. }
  13523. // Remove from scene
  13524. var index = this._scene.spriteManagers.indexOf(this);
  13525. this._scene.spriteManagers.splice(index, 1);
  13526. // Callback
  13527. if (this.onDispose) {
  13528. this.onDispose();
  13529. }
  13530. };
  13531. return SpriteManager;
  13532. })();
  13533. BABYLON.SpriteManager = SpriteManager;
  13534. })(BABYLON || (BABYLON = {}));
  13535. //# sourceMappingURL=babylon.spriteManager.js.map
  13536. var BABYLON;
  13537. (function (BABYLON) {
  13538. var Sprite = (function () {
  13539. function Sprite(name, manager) {
  13540. this.name = name;
  13541. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  13542. this.size = 1.0;
  13543. this.angle = 0;
  13544. this.cellIndex = 0;
  13545. this.invertU = 0;
  13546. this.invertV = 0;
  13547. this.animations = new Array();
  13548. this._animationStarted = false;
  13549. this._loopAnimation = false;
  13550. this._fromIndex = 0;
  13551. this._toIndex = 0;
  13552. this._delay = 0;
  13553. this._direction = 1;
  13554. this._frameCount = 0;
  13555. this._time = 0;
  13556. this._manager = manager;
  13557. this._manager.sprites.push(this);
  13558. this.position = BABYLON.Vector3.Zero();
  13559. }
  13560. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  13561. this._fromIndex = from;
  13562. this._toIndex = to;
  13563. this._loopAnimation = loop;
  13564. this._delay = delay;
  13565. this._animationStarted = true;
  13566. this._direction = from < to ? 1 : -1;
  13567. this.cellIndex = from;
  13568. this._time = 0;
  13569. };
  13570. Sprite.prototype.stopAnimation = function () {
  13571. this._animationStarted = false;
  13572. };
  13573. Sprite.prototype._animate = function (deltaTime) {
  13574. if (!this._animationStarted)
  13575. return;
  13576. this._time += deltaTime;
  13577. if (this._time > this._delay) {
  13578. this._time = this._time % this._delay;
  13579. this.cellIndex += this._direction;
  13580. if (this.cellIndex == this._toIndex) {
  13581. if (this._loopAnimation) {
  13582. this.cellIndex = this._fromIndex;
  13583. } else {
  13584. this._animationStarted = false;
  13585. if (this.disposeWhenFinishedAnimating) {
  13586. this.dispose();
  13587. }
  13588. }
  13589. }
  13590. }
  13591. };
  13592. Sprite.prototype.dispose = function () {
  13593. for (var i = 0; i < this._manager.sprites.length; i++) {
  13594. if (this._manager.sprites[i] == this) {
  13595. this._manager.sprites.splice(i, 1);
  13596. }
  13597. }
  13598. };
  13599. return Sprite;
  13600. })();
  13601. BABYLON.Sprite = Sprite;
  13602. })(BABYLON || (BABYLON = {}));
  13603. //# sourceMappingURL=babylon.sprite.js.map
  13604. var BABYLON;
  13605. (function (BABYLON) {
  13606. var Layer = (function () {
  13607. function Layer(name, imgUrl, scene, isBackground, color) {
  13608. this.name = name;
  13609. this._vertexDeclaration = [2];
  13610. this._vertexStrideSize = 2 * 4;
  13611. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  13612. this.isBackground = isBackground === undefined ? true : isBackground;
  13613. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  13614. this._scene = scene;
  13615. this._scene.layers.push(this);
  13616. // VBO
  13617. var vertices = [];
  13618. vertices.push(1, 1);
  13619. vertices.push(-1, 1);
  13620. vertices.push(-1, -1);
  13621. vertices.push(1, -1);
  13622. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  13623. // Indices
  13624. var indices = [];
  13625. indices.push(0);
  13626. indices.push(1);
  13627. indices.push(2);
  13628. indices.push(0);
  13629. indices.push(2);
  13630. indices.push(3);
  13631. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  13632. // Effects
  13633. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  13634. }
  13635. Layer.prototype.render = function () {
  13636. // Check
  13637. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  13638. return;
  13639. var engine = this._scene.getEngine();
  13640. // Render
  13641. engine.enableEffect(this._effect);
  13642. engine.setState(false);
  13643. // Texture
  13644. this._effect.setTexture("textureSampler", this.texture);
  13645. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  13646. // Color
  13647. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  13648. // VBOs
  13649. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  13650. // Draw order
  13651. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  13652. engine.draw(true, 0, 6);
  13653. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  13654. };
  13655. Layer.prototype.dispose = function () {
  13656. if (this._vertexBuffer) {
  13657. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  13658. this._vertexBuffer = null;
  13659. }
  13660. if (this._indexBuffer) {
  13661. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  13662. this._indexBuffer = null;
  13663. }
  13664. if (this.texture) {
  13665. this.texture.dispose();
  13666. this.texture = null;
  13667. }
  13668. // Remove from scene
  13669. var index = this._scene.layers.indexOf(this);
  13670. this._scene.layers.splice(index, 1);
  13671. // Callback
  13672. if (this.onDispose) {
  13673. this.onDispose();
  13674. }
  13675. };
  13676. return Layer;
  13677. })();
  13678. BABYLON.Layer = Layer;
  13679. })(BABYLON || (BABYLON = {}));
  13680. //# sourceMappingURL=babylon.layer.js.map
  13681. var BABYLON;
  13682. (function (BABYLON) {
  13683. var Particle = (function () {
  13684. function Particle() {
  13685. this.position = BABYLON.Vector3.Zero();
  13686. this.direction = BABYLON.Vector3.Zero();
  13687. this.color = new BABYLON.Color4(0, 0, 0, 0);
  13688. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  13689. this.lifeTime = 1.0;
  13690. this.age = 0;
  13691. this.size = 0;
  13692. this.angle = 0;
  13693. this.angularSpeed = 0;
  13694. }
  13695. return Particle;
  13696. })();
  13697. BABYLON.Particle = Particle;
  13698. })(BABYLON || (BABYLON = {}));
  13699. //# sourceMappingURL=babylon.particle.js.map
  13700. var BABYLON;
  13701. (function (BABYLON) {
  13702. var randomNumber = function (min, max) {
  13703. if (min === max) {
  13704. return (min);
  13705. }
  13706. var random = Math.random();
  13707. return ((random * (max - min)) + min);
  13708. };
  13709. var ParticleSystem = (function () {
  13710. function ParticleSystem(name, capacity, scene, customEffect) {
  13711. var _this = this;
  13712. this.name = name;
  13713. this.renderingGroupId = 0;
  13714. this.emitter = null;
  13715. this.emitRate = 10;
  13716. this.manualEmitCount = -1;
  13717. this.updateSpeed = 0.01;
  13718. this.targetStopDuration = 0;
  13719. this.disposeOnStop = false;
  13720. this.minEmitPower = 1;
  13721. this.maxEmitPower = 1;
  13722. this.minLifeTime = 1;
  13723. this.maxLifeTime = 1;
  13724. this.minSize = 1;
  13725. this.maxSize = 1;
  13726. this.minAngularSpeed = 0;
  13727. this.maxAngularSpeed = 0;
  13728. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  13729. this.forceDepthWrite = false;
  13730. this.gravity = BABYLON.Vector3.Zero();
  13731. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  13732. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  13733. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  13734. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  13735. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  13736. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  13737. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  13738. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  13739. this.particles = new Array();
  13740. this._vertexDeclaration = [3, 4, 4];
  13741. this._vertexStrideSize = 11 * 4;
  13742. this._stockParticles = new Array();
  13743. this._newPartsExcess = 0;
  13744. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  13745. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  13746. this._scaledDirection = BABYLON.Vector3.Zero();
  13747. this._scaledGravity = BABYLON.Vector3.Zero();
  13748. this._currentRenderId = -1;
  13749. this._started = false;
  13750. this._stopped = false;
  13751. this._actualFrame = 0;
  13752. this.id = name;
  13753. this._capacity = capacity;
  13754. this._scene = scene;
  13755. this._customEffect = customEffect;
  13756. scene.particleSystems.push(this);
  13757. // VBO
  13758. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  13759. var indices = [];
  13760. var index = 0;
  13761. for (var count = 0; count < capacity; count++) {
  13762. indices.push(index);
  13763. indices.push(index + 1);
  13764. indices.push(index + 2);
  13765. indices.push(index);
  13766. indices.push(index + 2);
  13767. indices.push(index + 3);
  13768. index += 4;
  13769. }
  13770. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  13771. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  13772. // Default behaviors
  13773. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate) {
  13774. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  13775. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  13776. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  13777. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  13778. };
  13779. this.startPositionFunction = function (worldMatrix, positionToUpdate) {
  13780. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  13781. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  13782. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  13783. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  13784. };
  13785. this.updateFunction = function (particles) {
  13786. for (var index = 0; index < particles.length; index++) {
  13787. var particle = particles[index];
  13788. particle.age += _this._scaledUpdateSpeed;
  13789. if (particle.age >= particle.lifeTime) {
  13790. particles.splice(index, 1);
  13791. _this._stockParticles.push(particle);
  13792. index--;
  13793. continue;
  13794. } else {
  13795. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  13796. particle.color.addInPlace(_this._scaledColorStep);
  13797. if (particle.color.a < 0)
  13798. particle.color.a = 0;
  13799. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  13800. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  13801. particle.position.addInPlace(_this._scaledDirection);
  13802. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  13803. particle.direction.addInPlace(_this._scaledGravity);
  13804. }
  13805. }
  13806. };
  13807. }
  13808. ParticleSystem.prototype.getCapacity = function () {
  13809. return this._capacity;
  13810. };
  13811. ParticleSystem.prototype.isAlive = function () {
  13812. return this._alive;
  13813. };
  13814. ParticleSystem.prototype.isStarted = function () {
  13815. return this._started;
  13816. };
  13817. ParticleSystem.prototype.start = function () {
  13818. this._started = true;
  13819. this._stopped = false;
  13820. this._actualFrame = 0;
  13821. };
  13822. ParticleSystem.prototype.stop = function () {
  13823. this._stopped = true;
  13824. };
  13825. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  13826. var offset = index * 11;
  13827. this._vertices[offset] = particle.position.x;
  13828. this._vertices[offset + 1] = particle.position.y;
  13829. this._vertices[offset + 2] = particle.position.z;
  13830. this._vertices[offset + 3] = particle.color.r;
  13831. this._vertices[offset + 4] = particle.color.g;
  13832. this._vertices[offset + 5] = particle.color.b;
  13833. this._vertices[offset + 6] = particle.color.a;
  13834. this._vertices[offset + 7] = particle.angle;
  13835. this._vertices[offset + 8] = particle.size;
  13836. this._vertices[offset + 9] = offsetX;
  13837. this._vertices[offset + 10] = offsetY;
  13838. };
  13839. ParticleSystem.prototype._update = function (newParticles) {
  13840. // Update current
  13841. this._alive = this.particles.length > 0;
  13842. this.updateFunction(this.particles);
  13843. // Add new ones
  13844. var worldMatrix;
  13845. if (this.emitter.position) {
  13846. worldMatrix = this.emitter.getWorldMatrix();
  13847. } else {
  13848. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  13849. }
  13850. for (var index = 0; index < newParticles; index++) {
  13851. if (this.particles.length === this._capacity) {
  13852. break;
  13853. }
  13854. if (this._stockParticles.length !== 0) {
  13855. var particle = this._stockParticles.pop();
  13856. particle.age = 0;
  13857. } else {
  13858. particle = new BABYLON.Particle();
  13859. }
  13860. this.particles.push(particle);
  13861. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  13862. this.startDirectionFunction(emitPower, worldMatrix, particle.direction);
  13863. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  13864. particle.size = randomNumber(this.minSize, this.maxSize);
  13865. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  13866. this.startPositionFunction(worldMatrix, particle.position);
  13867. var step = randomNumber(0, 1.0);
  13868. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  13869. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  13870. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  13871. }
  13872. };
  13873. ParticleSystem.prototype._getEffect = function () {
  13874. if (this._customEffect) {
  13875. return this._customEffect;
  13876. }
  13877. ;
  13878. var defines = [];
  13879. if (this._scene.clipPlane) {
  13880. defines.push("#define CLIPPLANE");
  13881. }
  13882. // Effect
  13883. var join = defines.join("\n");
  13884. if (this._cachedDefines !== join) {
  13885. this._cachedDefines = join;
  13886. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  13887. }
  13888. return this._effect;
  13889. };
  13890. ParticleSystem.prototype.animate = function () {
  13891. if (!this._started)
  13892. return;
  13893. var effect = this._getEffect();
  13894. // Check
  13895. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  13896. return;
  13897. if (this._currentRenderId === this._scene.getRenderId()) {
  13898. return;
  13899. }
  13900. this._currentRenderId = this._scene.getRenderId();
  13901. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  13902. // determine the number of particles we need to create
  13903. var emitCout;
  13904. if (this.manualEmitCount > -1) {
  13905. emitCout = this.manualEmitCount;
  13906. this.manualEmitCount = 0;
  13907. } else {
  13908. emitCout = this.emitRate;
  13909. }
  13910. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  13911. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  13912. if (this._newPartsExcess > 1.0) {
  13913. newParticles += this._newPartsExcess >> 0;
  13914. this._newPartsExcess -= this._newPartsExcess >> 0;
  13915. }
  13916. this._alive = false;
  13917. if (!this._stopped) {
  13918. this._actualFrame += this._scaledUpdateSpeed;
  13919. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  13920. this.stop();
  13921. } else {
  13922. newParticles = 0;
  13923. }
  13924. this._update(newParticles);
  13925. // Stopped?
  13926. if (this._stopped) {
  13927. if (!this._alive) {
  13928. this._started = false;
  13929. if (this.disposeOnStop) {
  13930. this._scene._toBeDisposed.push(this);
  13931. }
  13932. }
  13933. }
  13934. // Update VBO
  13935. var offset = 0;
  13936. for (var index = 0; index < this.particles.length; index++) {
  13937. var particle = this.particles[index];
  13938. this._appendParticleVertex(offset++, particle, 0, 0);
  13939. this._appendParticleVertex(offset++, particle, 1, 0);
  13940. this._appendParticleVertex(offset++, particle, 1, 1);
  13941. this._appendParticleVertex(offset++, particle, 0, 1);
  13942. }
  13943. var engine = this._scene.getEngine();
  13944. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  13945. };
  13946. ParticleSystem.prototype.render = function () {
  13947. var effect = this._getEffect();
  13948. // Check
  13949. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  13950. return 0;
  13951. var engine = this._scene.getEngine();
  13952. // Render
  13953. engine.enableEffect(effect);
  13954. engine.setState(false);
  13955. var viewMatrix = this._scene.getViewMatrix();
  13956. effect.setTexture("diffuseSampler", this.particleTexture);
  13957. effect.setMatrix("view", viewMatrix);
  13958. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  13959. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  13960. if (this._scene.clipPlane) {
  13961. var clipPlane = this._scene.clipPlane;
  13962. var invView = viewMatrix.clone();
  13963. invView.invert();
  13964. effect.setMatrix("invView", invView);
  13965. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  13966. }
  13967. // VBOs
  13968. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  13969. // Draw order
  13970. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  13971. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  13972. } else {
  13973. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  13974. }
  13975. if (this.forceDepthWrite) {
  13976. engine.setDepthWrite(true);
  13977. }
  13978. engine.draw(true, 0, this.particles.length * 6);
  13979. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  13980. return this.particles.length;
  13981. };
  13982. ParticleSystem.prototype.dispose = function () {
  13983. if (this._vertexBuffer) {
  13984. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  13985. this._vertexBuffer = null;
  13986. }
  13987. if (this._indexBuffer) {
  13988. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  13989. this._indexBuffer = null;
  13990. }
  13991. if (this.particleTexture) {
  13992. this.particleTexture.dispose();
  13993. this.particleTexture = null;
  13994. }
  13995. // Remove from scene
  13996. var index = this._scene.particleSystems.indexOf(this);
  13997. this._scene.particleSystems.splice(index, 1);
  13998. // Callback
  13999. if (this.onDispose) {
  14000. this.onDispose();
  14001. }
  14002. };
  14003. // Clone
  14004. ParticleSystem.prototype.clone = function (name, newEmitter) {
  14005. var result = new ParticleSystem(name, this._capacity, this._scene);
  14006. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  14007. if (newEmitter === undefined) {
  14008. newEmitter = this.emitter;
  14009. }
  14010. result.emitter = newEmitter;
  14011. if (this.particleTexture) {
  14012. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  14013. }
  14014. result.start();
  14015. return result;
  14016. };
  14017. ParticleSystem.BLENDMODE_ONEONE = 0;
  14018. ParticleSystem.BLENDMODE_STANDARD = 1;
  14019. return ParticleSystem;
  14020. })();
  14021. BABYLON.ParticleSystem = ParticleSystem;
  14022. })(BABYLON || (BABYLON = {}));
  14023. //# sourceMappingURL=babylon.particleSystem.js.map
  14024. var BABYLON;
  14025. (function (BABYLON) {
  14026. var Animation = (function () {
  14027. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  14028. this.name = name;
  14029. this.targetProperty = targetProperty;
  14030. this.framePerSecond = framePerSecond;
  14031. this.dataType = dataType;
  14032. this.loopMode = loopMode;
  14033. this._offsetsCache = {};
  14034. this._highLimitsCache = {};
  14035. this._stopped = false;
  14036. this.targetPropertyPath = targetProperty.split(".");
  14037. this.dataType = dataType;
  14038. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  14039. }
  14040. Animation.CreateAndStartAnimation = function (name, mesh, tartgetProperty, framePerSecond, totalFrame, from, to, loopMode) {
  14041. var dataType = undefined;
  14042. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  14043. dataType = Animation.ANIMATIONTYPE_FLOAT;
  14044. } else if (from instanceof BABYLON.Quaternion) {
  14045. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  14046. } else if (from instanceof BABYLON.Vector3) {
  14047. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  14048. } else if (from instanceof BABYLON.Vector2) {
  14049. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  14050. } else if (from instanceof BABYLON.Color3) {
  14051. dataType = Animation.ANIMATIONTYPE_COLOR3;
  14052. }
  14053. if (dataType == undefined) {
  14054. return;
  14055. }
  14056. var animation = new Animation(name, tartgetProperty, framePerSecond, dataType, loopMode);
  14057. var keys = [];
  14058. keys.push({ frame: 0, value: from });
  14059. keys.push({ frame: totalFrame, value: to });
  14060. animation.setKeys(keys);
  14061. mesh.animations.push(animation);
  14062. mesh.getScene().beginAnimation(mesh, 0, totalFrame, (animation.loopMode == 1));
  14063. };
  14064. // Methods
  14065. Animation.prototype.isStopped = function () {
  14066. return this._stopped;
  14067. };
  14068. Animation.prototype.getKeys = function () {
  14069. return this._keys;
  14070. };
  14071. Animation.prototype.getEasingFunction = function () {
  14072. return this._easingFunction;
  14073. };
  14074. Animation.prototype.setEasingFunction = function (easingFunction) {
  14075. this._easingFunction = easingFunction;
  14076. };
  14077. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  14078. return startValue + (endValue - startValue) * gradient;
  14079. };
  14080. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  14081. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  14082. };
  14083. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  14084. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  14085. };
  14086. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  14087. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  14088. };
  14089. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  14090. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  14091. };
  14092. Animation.prototype.clone = function () {
  14093. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  14094. clone.setKeys(this._keys);
  14095. return clone;
  14096. };
  14097. Animation.prototype.setKeys = function (values) {
  14098. this._keys = values.slice(0);
  14099. this._offsetsCache = {};
  14100. this._highLimitsCache = {};
  14101. };
  14102. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  14103. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  14104. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  14105. }
  14106. this.currentFrame = currentFrame;
  14107. for (var key = 0; key < this._keys.length; key++) {
  14108. // for each frame, we need the key just before the frame superior
  14109. if (this._keys[key + 1].frame >= currentFrame) {
  14110. var startValue = this._keys[key].value;
  14111. var endValue = this._keys[key + 1].value;
  14112. // gradient : percent of currentFrame between the frame inf and the frame sup
  14113. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  14114. // check for easingFunction and correction of gradient
  14115. if (this._easingFunction != null) {
  14116. gradient = this._easingFunction.ease(gradient);
  14117. }
  14118. switch (this.dataType) {
  14119. case Animation.ANIMATIONTYPE_FLOAT:
  14120. switch (loopMode) {
  14121. case Animation.ANIMATIONLOOPMODE_CYCLE:
  14122. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  14123. return this.floatInterpolateFunction(startValue, endValue, gradient);
  14124. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  14125. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  14126. }
  14127. break;
  14128. case Animation.ANIMATIONTYPE_QUATERNION:
  14129. var quaternion = null;
  14130. switch (loopMode) {
  14131. case Animation.ANIMATIONLOOPMODE_CYCLE:
  14132. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  14133. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  14134. break;
  14135. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  14136. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  14137. break;
  14138. }
  14139. return quaternion;
  14140. case Animation.ANIMATIONTYPE_VECTOR3:
  14141. switch (loopMode) {
  14142. case Animation.ANIMATIONLOOPMODE_CYCLE:
  14143. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  14144. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  14145. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  14146. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  14147. }
  14148. case Animation.ANIMATIONTYPE_VECTOR2:
  14149. switch (loopMode) {
  14150. case Animation.ANIMATIONLOOPMODE_CYCLE:
  14151. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  14152. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  14153. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  14154. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  14155. }
  14156. case Animation.ANIMATIONTYPE_COLOR3:
  14157. switch (loopMode) {
  14158. case Animation.ANIMATIONLOOPMODE_CYCLE:
  14159. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  14160. return this.color3InterpolateFunction(startValue, endValue, gradient);
  14161. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  14162. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  14163. }
  14164. case Animation.ANIMATIONTYPE_MATRIX:
  14165. switch (loopMode) {
  14166. case Animation.ANIMATIONLOOPMODE_CYCLE:
  14167. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  14168. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  14169. return startValue;
  14170. }
  14171. default:
  14172. break;
  14173. }
  14174. break;
  14175. }
  14176. }
  14177. return this._keys[this._keys.length - 1].value;
  14178. };
  14179. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  14180. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  14181. this._stopped = true;
  14182. return false;
  14183. }
  14184. var returnValue = true;
  14185. // Adding a start key at frame 0 if missing
  14186. if (this._keys[0].frame != 0) {
  14187. var newKey = { frame: 0, value: this._keys[0].value };
  14188. this._keys.splice(0, 0, newKey);
  14189. }
  14190. // Check limits
  14191. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  14192. from = this._keys[0].frame;
  14193. }
  14194. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  14195. to = this._keys[this._keys.length - 1].frame;
  14196. }
  14197. // Compute ratio
  14198. var range = to - from;
  14199. var offsetValue;
  14200. // ratio represents the frame delta between from and to
  14201. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  14202. if (ratio > range && !loop) {
  14203. returnValue = false;
  14204. highLimitValue = this._keys[this._keys.length - 1].value;
  14205. } else {
  14206. // Get max value if required
  14207. var highLimitValue = 0;
  14208. if (this.loopMode != Animation.ANIMATIONLOOPMODE_CYCLE) {
  14209. var keyOffset = to.toString() + from.toString();
  14210. if (!this._offsetsCache[keyOffset]) {
  14211. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  14212. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  14213. switch (this.dataType) {
  14214. case Animation.ANIMATIONTYPE_FLOAT:
  14215. this._offsetsCache[keyOffset] = toValue - fromValue;
  14216. break;
  14217. case Animation.ANIMATIONTYPE_QUATERNION:
  14218. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  14219. break;
  14220. case Animation.ANIMATIONTYPE_VECTOR3:
  14221. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  14222. case Animation.ANIMATIONTYPE_VECTOR2:
  14223. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  14224. case Animation.ANIMATIONTYPE_COLOR3:
  14225. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  14226. default:
  14227. break;
  14228. }
  14229. this._highLimitsCache[keyOffset] = toValue;
  14230. }
  14231. highLimitValue = this._highLimitsCache[keyOffset];
  14232. offsetValue = this._offsetsCache[keyOffset];
  14233. }
  14234. }
  14235. if (offsetValue === undefined) {
  14236. switch (this.dataType) {
  14237. case Animation.ANIMATIONTYPE_FLOAT:
  14238. offsetValue = 0;
  14239. break;
  14240. case Animation.ANIMATIONTYPE_QUATERNION:
  14241. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  14242. break;
  14243. case Animation.ANIMATIONTYPE_VECTOR3:
  14244. offsetValue = BABYLON.Vector3.Zero();
  14245. break;
  14246. case Animation.ANIMATIONTYPE_VECTOR2:
  14247. offsetValue = BABYLON.Vector2.Zero();
  14248. break;
  14249. case Animation.ANIMATIONTYPE_COLOR3:
  14250. offsetValue = BABYLON.Color3.Black();
  14251. }
  14252. }
  14253. // Compute value
  14254. var repeatCount = (ratio / range) >> 0;
  14255. var currentFrame = returnValue ? from + ratio % range : to;
  14256. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  14257. // Set value
  14258. if (this.targetPropertyPath.length > 1) {
  14259. var property = this._target[this.targetPropertyPath[0]];
  14260. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  14261. property = property[this.targetPropertyPath[index]];
  14262. }
  14263. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  14264. } else {
  14265. this._target[this.targetPropertyPath[0]] = currentValue;
  14266. }
  14267. if (this._target.markAsDirty) {
  14268. this._target.markAsDirty(this.targetProperty);
  14269. }
  14270. if (!returnValue) {
  14271. this._stopped = true;
  14272. }
  14273. return returnValue;
  14274. };
  14275. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  14276. get: function () {
  14277. return Animation._ANIMATIONTYPE_FLOAT;
  14278. },
  14279. enumerable: true,
  14280. configurable: true
  14281. });
  14282. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  14283. get: function () {
  14284. return Animation._ANIMATIONTYPE_VECTOR3;
  14285. },
  14286. enumerable: true,
  14287. configurable: true
  14288. });
  14289. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  14290. get: function () {
  14291. return Animation._ANIMATIONTYPE_VECTOR2;
  14292. },
  14293. enumerable: true,
  14294. configurable: true
  14295. });
  14296. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  14297. get: function () {
  14298. return Animation._ANIMATIONTYPE_QUATERNION;
  14299. },
  14300. enumerable: true,
  14301. configurable: true
  14302. });
  14303. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  14304. get: function () {
  14305. return Animation._ANIMATIONTYPE_MATRIX;
  14306. },
  14307. enumerable: true,
  14308. configurable: true
  14309. });
  14310. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  14311. get: function () {
  14312. return Animation._ANIMATIONTYPE_COLOR3;
  14313. },
  14314. enumerable: true,
  14315. configurable: true
  14316. });
  14317. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  14318. get: function () {
  14319. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  14320. },
  14321. enumerable: true,
  14322. configurable: true
  14323. });
  14324. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  14325. get: function () {
  14326. return Animation._ANIMATIONLOOPMODE_CYCLE;
  14327. },
  14328. enumerable: true,
  14329. configurable: true
  14330. });
  14331. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  14332. get: function () {
  14333. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  14334. },
  14335. enumerable: true,
  14336. configurable: true
  14337. });
  14338. Animation._ANIMATIONTYPE_FLOAT = 0;
  14339. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  14340. Animation._ANIMATIONTYPE_QUATERNION = 2;
  14341. Animation._ANIMATIONTYPE_MATRIX = 3;
  14342. Animation._ANIMATIONTYPE_COLOR3 = 4;
  14343. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  14344. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  14345. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  14346. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  14347. return Animation;
  14348. })();
  14349. BABYLON.Animation = Animation;
  14350. })(BABYLON || (BABYLON = {}));
  14351. //# sourceMappingURL=babylon.animation.js.map
  14352. var BABYLON;
  14353. (function (BABYLON) {
  14354. var Animatable = (function () {
  14355. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  14356. if (typeof fromFrame === "undefined") { fromFrame = 0; }
  14357. if (typeof toFrame === "undefined") { toFrame = 100; }
  14358. if (typeof loopAnimation === "undefined") { loopAnimation = false; }
  14359. if (typeof speedRatio === "undefined") { speedRatio = 1.0; }
  14360. this.target = target;
  14361. this.fromFrame = fromFrame;
  14362. this.toFrame = toFrame;
  14363. this.loopAnimation = loopAnimation;
  14364. this.speedRatio = speedRatio;
  14365. this.onAnimationEnd = onAnimationEnd;
  14366. this._animations = new Array();
  14367. this._paused = false;
  14368. this.animationStarted = false;
  14369. if (animations) {
  14370. this.appendAnimations(target, animations);
  14371. }
  14372. this._scene = scene;
  14373. scene._activeAnimatables.push(this);
  14374. }
  14375. // Methods
  14376. Animatable.prototype.appendAnimations = function (target, animations) {
  14377. for (var index = 0; index < animations.length; index++) {
  14378. var animation = animations[index];
  14379. animation._target = target;
  14380. this._animations.push(animation);
  14381. }
  14382. };
  14383. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  14384. var animations = this._animations;
  14385. for (var index = 0; index < animations.length; index++) {
  14386. if (animations[index].targetProperty === property) {
  14387. return animations[index];
  14388. }
  14389. }
  14390. return null;
  14391. };
  14392. Animatable.prototype.pause = function () {
  14393. if (this._paused) {
  14394. return;
  14395. }
  14396. this._paused = true;
  14397. };
  14398. Animatable.prototype.restart = function () {
  14399. this._paused = false;
  14400. };
  14401. Animatable.prototype.stop = function () {
  14402. var index = this._scene._activeAnimatables.indexOf(this);
  14403. if (index > -1) {
  14404. this._scene._activeAnimatables.splice(index, 1);
  14405. }
  14406. if (this.onAnimationEnd) {
  14407. this.onAnimationEnd();
  14408. }
  14409. };
  14410. Animatable.prototype._animate = function (delay) {
  14411. if (this._paused) {
  14412. if (!this._pausedDelay) {
  14413. this._pausedDelay = delay;
  14414. }
  14415. return true;
  14416. }
  14417. if (!this._localDelayOffset) {
  14418. this._localDelayOffset = delay;
  14419. } else if (this._pausedDelay) {
  14420. this._localDelayOffset += delay - this._pausedDelay;
  14421. this._pausedDelay = null;
  14422. }
  14423. // Animating
  14424. var running = false;
  14425. var animations = this._animations;
  14426. for (var index = 0; index < animations.length; index++) {
  14427. var animation = animations[index];
  14428. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  14429. running = running || isRunning;
  14430. }
  14431. if (!running && this.onAnimationEnd) {
  14432. this.onAnimationEnd();
  14433. }
  14434. return running;
  14435. };
  14436. return Animatable;
  14437. })();
  14438. BABYLON.Animatable = Animatable;
  14439. })(BABYLON || (BABYLON = {}));
  14440. //# sourceMappingURL=babylon.animatable.js.map
  14441. var BABYLON;
  14442. (function (BABYLON) {
  14443. var EasingFunction = (function () {
  14444. function EasingFunction() {
  14445. // Properties
  14446. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  14447. }
  14448. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  14449. get: function () {
  14450. return EasingFunction._EASINGMODE_EASEIN;
  14451. },
  14452. enumerable: true,
  14453. configurable: true
  14454. });
  14455. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  14456. get: function () {
  14457. return EasingFunction._EASINGMODE_EASEOUT;
  14458. },
  14459. enumerable: true,
  14460. configurable: true
  14461. });
  14462. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  14463. get: function () {
  14464. return EasingFunction._EASINGMODE_EASEINOUT;
  14465. },
  14466. enumerable: true,
  14467. configurable: true
  14468. });
  14469. EasingFunction.prototype.setEasingMode = function (easingMode) {
  14470. var n = Math.min(Math.max(easingMode, 0), 2);
  14471. this._easingMode = n;
  14472. };
  14473. EasingFunction.prototype.getEasingMode = function () {
  14474. return this._easingMode;
  14475. };
  14476. EasingFunction.prototype.easeInCore = function (gradient) {
  14477. throw new Error('You must implement this method');
  14478. };
  14479. EasingFunction.prototype.ease = function (gradient) {
  14480. switch (this._easingMode) {
  14481. case EasingFunction.EASINGMODE_EASEIN:
  14482. return this.easeInCore(gradient);
  14483. case EasingFunction.EASINGMODE_EASEOUT:
  14484. return (1 - this.easeInCore(1 - gradient));
  14485. }
  14486. if (gradient >= 0.5) {
  14487. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  14488. }
  14489. return (this.easeInCore(gradient * 2) * 0.5);
  14490. };
  14491. EasingFunction._EASINGMODE_EASEIN = 0;
  14492. EasingFunction._EASINGMODE_EASEOUT = 1;
  14493. EasingFunction._EASINGMODE_EASEINOUT = 2;
  14494. return EasingFunction;
  14495. })();
  14496. BABYLON.EasingFunction = EasingFunction;
  14497. var CircleEase = (function (_super) {
  14498. __extends(CircleEase, _super);
  14499. function CircleEase() {
  14500. _super.apply(this, arguments);
  14501. }
  14502. CircleEase.prototype.easeInCore = function (gradient) {
  14503. gradient = Math.max(0, Math.min(1, gradient));
  14504. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  14505. };
  14506. return CircleEase;
  14507. })(EasingFunction);
  14508. BABYLON.CircleEase = CircleEase;
  14509. var BackEase = (function (_super) {
  14510. __extends(BackEase, _super);
  14511. function BackEase(amplitude) {
  14512. if (typeof amplitude === "undefined") { amplitude = 1; }
  14513. _super.call(this);
  14514. this.amplitude = amplitude;
  14515. }
  14516. BackEase.prototype.easeInCore = function (gradient) {
  14517. var num = Math.max(0, this.amplitude);
  14518. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  14519. };
  14520. return BackEase;
  14521. })(EasingFunction);
  14522. BABYLON.BackEase = BackEase;
  14523. var BounceEase = (function (_super) {
  14524. __extends(BounceEase, _super);
  14525. function BounceEase(bounces, bounciness) {
  14526. if (typeof bounces === "undefined") { bounces = 3; }
  14527. if (typeof bounciness === "undefined") { bounciness = 2; }
  14528. _super.call(this);
  14529. this.bounces = bounces;
  14530. this.bounciness = bounciness;
  14531. }
  14532. BounceEase.prototype.easeInCore = function (gradient) {
  14533. var y = Math.max(0.0, this.bounces);
  14534. var bounciness = this.bounciness;
  14535. if (bounciness <= 1.0) {
  14536. bounciness = 1.001;
  14537. }
  14538. var num9 = Math.pow(bounciness, y);
  14539. var num5 = 1.0 - bounciness;
  14540. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  14541. var num15 = gradient * num4;
  14542. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  14543. var num3 = Math.floor(num65);
  14544. var num13 = num3 + 1.0;
  14545. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  14546. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  14547. var num7 = (num8 + num12) * 0.5;
  14548. var num6 = gradient - num7;
  14549. var num2 = num7 - num8;
  14550. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  14551. };
  14552. return BounceEase;
  14553. })(EasingFunction);
  14554. BABYLON.BounceEase = BounceEase;
  14555. var CubicEase = (function (_super) {
  14556. __extends(CubicEase, _super);
  14557. function CubicEase() {
  14558. _super.apply(this, arguments);
  14559. }
  14560. CubicEase.prototype.easeInCore = function (gradient) {
  14561. return (gradient * gradient * gradient);
  14562. };
  14563. return CubicEase;
  14564. })(EasingFunction);
  14565. BABYLON.CubicEase = CubicEase;
  14566. var ElasticEase = (function (_super) {
  14567. __extends(ElasticEase, _super);
  14568. function ElasticEase(oscillations, springiness) {
  14569. if (typeof oscillations === "undefined") { oscillations = 3; }
  14570. if (typeof springiness === "undefined") { springiness = 3; }
  14571. _super.call(this);
  14572. this.oscillations = oscillations;
  14573. this.springiness = springiness;
  14574. }
  14575. ElasticEase.prototype.easeInCore = function (gradient) {
  14576. var num2;
  14577. var num3 = Math.max(0.0, this.oscillations);
  14578. var num = Math.max(0.0, this.springiness);
  14579. if (num == 0) {
  14580. num2 = gradient;
  14581. } else {
  14582. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  14583. }
  14584. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  14585. };
  14586. return ElasticEase;
  14587. })(EasingFunction);
  14588. BABYLON.ElasticEase = ElasticEase;
  14589. var ExponentialEase = (function (_super) {
  14590. __extends(ExponentialEase, _super);
  14591. function ExponentialEase(exponent) {
  14592. if (typeof exponent === "undefined") { exponent = 2; }
  14593. _super.call(this);
  14594. this.exponent = exponent;
  14595. }
  14596. ExponentialEase.prototype.easeInCore = function (gradient) {
  14597. if (this.exponent <= 0) {
  14598. return gradient;
  14599. }
  14600. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  14601. };
  14602. return ExponentialEase;
  14603. })(EasingFunction);
  14604. BABYLON.ExponentialEase = ExponentialEase;
  14605. var PowerEase = (function (_super) {
  14606. __extends(PowerEase, _super);
  14607. function PowerEase(power) {
  14608. if (typeof power === "undefined") { power = 2; }
  14609. _super.call(this);
  14610. this.power = power;
  14611. }
  14612. PowerEase.prototype.easeInCore = function (gradient) {
  14613. var y = Math.max(0.0, this.power);
  14614. return Math.pow(gradient, y);
  14615. };
  14616. return PowerEase;
  14617. })(EasingFunction);
  14618. BABYLON.PowerEase = PowerEase;
  14619. var QuadraticEase = (function (_super) {
  14620. __extends(QuadraticEase, _super);
  14621. function QuadraticEase() {
  14622. _super.apply(this, arguments);
  14623. }
  14624. QuadraticEase.prototype.easeInCore = function (gradient) {
  14625. return (gradient * gradient);
  14626. };
  14627. return QuadraticEase;
  14628. })(EasingFunction);
  14629. BABYLON.QuadraticEase = QuadraticEase;
  14630. var QuarticEase = (function (_super) {
  14631. __extends(QuarticEase, _super);
  14632. function QuarticEase() {
  14633. _super.apply(this, arguments);
  14634. }
  14635. QuarticEase.prototype.easeInCore = function (gradient) {
  14636. return (gradient * gradient * gradient * gradient);
  14637. };
  14638. return QuarticEase;
  14639. })(EasingFunction);
  14640. BABYLON.QuarticEase = QuarticEase;
  14641. var QuinticEase = (function (_super) {
  14642. __extends(QuinticEase, _super);
  14643. function QuinticEase() {
  14644. _super.apply(this, arguments);
  14645. }
  14646. QuinticEase.prototype.easeInCore = function (gradient) {
  14647. return (gradient * gradient * gradient * gradient * gradient);
  14648. };
  14649. return QuinticEase;
  14650. })(EasingFunction);
  14651. BABYLON.QuinticEase = QuinticEase;
  14652. var SineEase = (function (_super) {
  14653. __extends(SineEase, _super);
  14654. function SineEase() {
  14655. _super.apply(this, arguments);
  14656. }
  14657. SineEase.prototype.easeInCore = function (gradient) {
  14658. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  14659. };
  14660. return SineEase;
  14661. })(EasingFunction);
  14662. BABYLON.SineEase = SineEase;
  14663. var BezierCurveEase = (function (_super) {
  14664. __extends(BezierCurveEase, _super);
  14665. function BezierCurveEase(x1, y1, x2, y2) {
  14666. if (typeof x1 === "undefined") { x1 = 0; }
  14667. if (typeof y1 === "undefined") { y1 = 0; }
  14668. if (typeof x2 === "undefined") { x2 = 1; }
  14669. if (typeof y2 === "undefined") { y2 = 1; }
  14670. _super.call(this);
  14671. this.x1 = x1;
  14672. this.y1 = y1;
  14673. this.x2 = x2;
  14674. this.y2 = y2;
  14675. }
  14676. BezierCurveEase.prototype.easeInCore = function (gradient) {
  14677. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  14678. };
  14679. return BezierCurveEase;
  14680. })(EasingFunction);
  14681. BABYLON.BezierCurveEase = BezierCurveEase;
  14682. })(BABYLON || (BABYLON = {}));
  14683. //# sourceMappingURL=babylon.easing.js.map
  14684. var BABYLON;
  14685. (function (BABYLON) {
  14686. var Octree = (function () {
  14687. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  14688. if (typeof maxDepth === "undefined") { maxDepth = 2; }
  14689. this.maxDepth = maxDepth;
  14690. this.dynamicContent = new Array();
  14691. this._maxBlockCapacity = maxBlockCapacity || 64;
  14692. this._selectionContent = new BABYLON.SmartArray(1024);
  14693. this._creationFunc = creationFunc;
  14694. }
  14695. // Methods
  14696. Octree.prototype.update = function (worldMin, worldMax, entries) {
  14697. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  14698. };
  14699. Octree.prototype.addMesh = function (entry) {
  14700. for (var index = 0; index < this.blocks.length; index++) {
  14701. var block = this.blocks[index];
  14702. block.addEntry(entry);
  14703. }
  14704. };
  14705. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  14706. this._selectionContent.reset();
  14707. for (var index = 0; index < this.blocks.length; index++) {
  14708. var block = this.blocks[index];
  14709. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  14710. }
  14711. if (allowDuplicate) {
  14712. this._selectionContent.concat(this.dynamicContent);
  14713. } else {
  14714. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  14715. }
  14716. return this._selectionContent;
  14717. };
  14718. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  14719. this._selectionContent.reset();
  14720. for (var index = 0; index < this.blocks.length; index++) {
  14721. var block = this.blocks[index];
  14722. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  14723. }
  14724. if (allowDuplicate) {
  14725. this._selectionContent.concat(this.dynamicContent);
  14726. } else {
  14727. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  14728. }
  14729. return this._selectionContent;
  14730. };
  14731. Octree.prototype.intersectsRay = function (ray) {
  14732. this._selectionContent.reset();
  14733. for (var index = 0; index < this.blocks.length; index++) {
  14734. var block = this.blocks[index];
  14735. block.intersectsRay(ray, this._selectionContent);
  14736. }
  14737. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  14738. return this._selectionContent;
  14739. };
  14740. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  14741. target.blocks = new Array();
  14742. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  14743. for (var x = 0; x < 2; x++) {
  14744. for (var y = 0; y < 2; y++) {
  14745. for (var z = 0; z < 2; z++) {
  14746. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  14747. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  14748. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  14749. block.addEntries(entries);
  14750. target.blocks.push(block);
  14751. }
  14752. }
  14753. }
  14754. };
  14755. Octree.CreationFuncForMeshes = function (entry, block) {
  14756. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  14757. block.entries.push(entry);
  14758. }
  14759. };
  14760. Octree.CreationFuncForSubMeshes = function (entry, block) {
  14761. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  14762. block.entries.push(entry);
  14763. }
  14764. };
  14765. return Octree;
  14766. })();
  14767. BABYLON.Octree = Octree;
  14768. })(BABYLON || (BABYLON = {}));
  14769. //# sourceMappingURL=babylon.octree.js.map
  14770. var BABYLON;
  14771. (function (BABYLON) {
  14772. var OctreeBlock = (function () {
  14773. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  14774. this.entries = new Array();
  14775. this._boundingVectors = new Array();
  14776. this._capacity = capacity;
  14777. this._depth = depth;
  14778. this._maxDepth = maxDepth;
  14779. this._creationFunc = creationFunc;
  14780. this._minPoint = minPoint;
  14781. this._maxPoint = maxPoint;
  14782. this._boundingVectors.push(minPoint.clone());
  14783. this._boundingVectors.push(maxPoint.clone());
  14784. this._boundingVectors.push(minPoint.clone());
  14785. this._boundingVectors[2].x = maxPoint.x;
  14786. this._boundingVectors.push(minPoint.clone());
  14787. this._boundingVectors[3].y = maxPoint.y;
  14788. this._boundingVectors.push(minPoint.clone());
  14789. this._boundingVectors[4].z = maxPoint.z;
  14790. this._boundingVectors.push(maxPoint.clone());
  14791. this._boundingVectors[5].z = minPoint.z;
  14792. this._boundingVectors.push(maxPoint.clone());
  14793. this._boundingVectors[6].x = minPoint.x;
  14794. this._boundingVectors.push(maxPoint.clone());
  14795. this._boundingVectors[7].y = minPoint.y;
  14796. }
  14797. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  14798. // Property
  14799. get: function () {
  14800. return this._capacity;
  14801. },
  14802. enumerable: true,
  14803. configurable: true
  14804. });
  14805. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  14806. get: function () {
  14807. return this._minPoint;
  14808. },
  14809. enumerable: true,
  14810. configurable: true
  14811. });
  14812. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  14813. get: function () {
  14814. return this._maxPoint;
  14815. },
  14816. enumerable: true,
  14817. configurable: true
  14818. });
  14819. // Methods
  14820. OctreeBlock.prototype.addEntry = function (entry) {
  14821. if (this.blocks) {
  14822. for (var index = 0; index < this.blocks.length; index++) {
  14823. var block = this.blocks[index];
  14824. block.addEntry(entry);
  14825. }
  14826. return;
  14827. }
  14828. this._creationFunc(entry, this);
  14829. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  14830. this.createInnerBlocks();
  14831. }
  14832. };
  14833. OctreeBlock.prototype.addEntries = function (entries) {
  14834. for (var index = 0; index < entries.length; index++) {
  14835. var mesh = entries[index];
  14836. this.addEntry(mesh);
  14837. }
  14838. };
  14839. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  14840. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  14841. if (this.blocks) {
  14842. for (var index = 0; index < this.blocks.length; index++) {
  14843. var block = this.blocks[index];
  14844. block.select(frustumPlanes, selection, allowDuplicate);
  14845. }
  14846. return;
  14847. }
  14848. if (allowDuplicate) {
  14849. selection.concat(this.entries);
  14850. } else {
  14851. selection.concatWithNoDuplicate(this.entries);
  14852. }
  14853. }
  14854. };
  14855. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  14856. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  14857. if (this.blocks) {
  14858. for (var index = 0; index < this.blocks.length; index++) {
  14859. var block = this.blocks[index];
  14860. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  14861. }
  14862. return;
  14863. }
  14864. if (allowDuplicate) {
  14865. selection.concat(this.entries);
  14866. } else {
  14867. selection.concatWithNoDuplicate(this.entries);
  14868. }
  14869. }
  14870. };
  14871. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  14872. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  14873. if (this.blocks) {
  14874. for (var index = 0; index < this.blocks.length; index++) {
  14875. var block = this.blocks[index];
  14876. block.intersectsRay(ray, selection);
  14877. }
  14878. return;
  14879. }
  14880. selection.concatWithNoDuplicate(this.entries);
  14881. }
  14882. };
  14883. OctreeBlock.prototype.createInnerBlocks = function () {
  14884. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  14885. };
  14886. return OctreeBlock;
  14887. })();
  14888. BABYLON.OctreeBlock = OctreeBlock;
  14889. })(BABYLON || (BABYLON = {}));
  14890. //# sourceMappingURL=babylon.octreeBlock.js.map
  14891. var BABYLON;
  14892. (function (BABYLON) {
  14893. var Bone = (function () {
  14894. function Bone(name, skeleton, parentBone, matrix) {
  14895. this.name = name;
  14896. this.children = new Array();
  14897. this.animations = new Array();
  14898. this._worldTransform = new BABYLON.Matrix();
  14899. this._absoluteTransform = new BABYLON.Matrix();
  14900. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  14901. this._skeleton = skeleton;
  14902. this._matrix = matrix;
  14903. this._baseMatrix = matrix;
  14904. skeleton.bones.push(this);
  14905. if (parentBone) {
  14906. this._parent = parentBone;
  14907. parentBone.children.push(this);
  14908. } else {
  14909. this._parent = null;
  14910. }
  14911. this._updateDifferenceMatrix();
  14912. }
  14913. // Members
  14914. Bone.prototype.getParent = function () {
  14915. return this._parent;
  14916. };
  14917. Bone.prototype.getLocalMatrix = function () {
  14918. return this._matrix;
  14919. };
  14920. Bone.prototype.getBaseMatrix = function () {
  14921. return this._baseMatrix;
  14922. };
  14923. Bone.prototype.getWorldMatrix = function () {
  14924. return this._worldTransform;
  14925. };
  14926. Bone.prototype.getInvertedAbsoluteTransform = function () {
  14927. return this._invertedAbsoluteTransform;
  14928. };
  14929. Bone.prototype.getAbsoluteMatrix = function () {
  14930. var matrix = this._matrix.clone();
  14931. var parent = this._parent;
  14932. while (parent) {
  14933. matrix = matrix.multiply(parent.getLocalMatrix());
  14934. parent = parent.getParent();
  14935. }
  14936. return matrix;
  14937. };
  14938. // Methods
  14939. Bone.prototype.updateMatrix = function (matrix) {
  14940. this._matrix = matrix;
  14941. this._skeleton._markAsDirty();
  14942. this._updateDifferenceMatrix();
  14943. };
  14944. Bone.prototype._updateDifferenceMatrix = function () {
  14945. if (this._parent) {
  14946. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  14947. } else {
  14948. this._absoluteTransform.copyFrom(this._matrix);
  14949. }
  14950. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  14951. for (var index = 0; index < this.children.length; index++) {
  14952. this.children[index]._updateDifferenceMatrix();
  14953. }
  14954. };
  14955. Bone.prototype.markAsDirty = function () {
  14956. this._skeleton._markAsDirty();
  14957. };
  14958. return Bone;
  14959. })();
  14960. BABYLON.Bone = Bone;
  14961. })(BABYLON || (BABYLON = {}));
  14962. //# sourceMappingURL=babylon.bone.js.map
  14963. var BABYLON;
  14964. (function (BABYLON) {
  14965. var Skeleton = (function () {
  14966. function Skeleton(name, id, scene) {
  14967. this.name = name;
  14968. this.id = id;
  14969. this.bones = new Array();
  14970. this._isDirty = true;
  14971. this._identity = BABYLON.Matrix.Identity();
  14972. this.bones = [];
  14973. this._scene = scene;
  14974. scene.skeletons.push(this);
  14975. }
  14976. // Members
  14977. Skeleton.prototype.getTransformMatrices = function () {
  14978. return this._transformMatrices;
  14979. };
  14980. // Methods
  14981. Skeleton.prototype._markAsDirty = function () {
  14982. this._isDirty = true;
  14983. };
  14984. Skeleton.prototype.prepare = function () {
  14985. if (!this._isDirty) {
  14986. return;
  14987. }
  14988. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  14989. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  14990. }
  14991. for (var index = 0; index < this.bones.length; index++) {
  14992. var bone = this.bones[index];
  14993. var parentBone = bone.getParent();
  14994. if (parentBone) {
  14995. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  14996. } else {
  14997. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  14998. }
  14999. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  15000. }
  15001. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  15002. this._isDirty = false;
  15003. };
  15004. Skeleton.prototype.getAnimatables = function () {
  15005. if (!this._animatables || this._animatables.length != this.bones.length) {
  15006. this._animatables = [];
  15007. for (var index = 0; index < this.bones.length; index++) {
  15008. this._animatables.push(this.bones[index]);
  15009. }
  15010. }
  15011. return this._animatables;
  15012. };
  15013. Skeleton.prototype.clone = function (name, id) {
  15014. var result = new BABYLON.Skeleton(name, id || name, this._scene);
  15015. for (var index = 0; index < this.bones.length; index++) {
  15016. var source = this.bones[index];
  15017. var parentBone = null;
  15018. if (source.getParent()) {
  15019. var parentIndex = this.bones.indexOf(source.getParent());
  15020. parentBone = result.bones[parentIndex];
  15021. }
  15022. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  15023. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  15024. }
  15025. return result;
  15026. };
  15027. return Skeleton;
  15028. })();
  15029. BABYLON.Skeleton = Skeleton;
  15030. })(BABYLON || (BABYLON = {}));
  15031. //# sourceMappingURL=babylon.skeleton.js.map
  15032. var BABYLON;
  15033. (function (BABYLON) {
  15034. var PostProcess = (function () {
  15035. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable) {
  15036. this.name = name;
  15037. this.width = -1;
  15038. this.height = -1;
  15039. this._reusable = false;
  15040. this._textures = new BABYLON.SmartArray(2);
  15041. this._currentRenderTextureInd = 0;
  15042. if (camera != null) {
  15043. this._camera = camera;
  15044. this._scene = camera.getScene();
  15045. camera.attachPostProcess(this);
  15046. this._engine = this._scene.getEngine();
  15047. } else {
  15048. this._engine = engine;
  15049. }
  15050. this._renderRatio = ratio;
  15051. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15052. this._reusable = reusable || false;
  15053. samplers = samplers || [];
  15054. samplers.push("textureSampler");
  15055. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: fragmentUrl }, ["position"], parameters || [], samplers, "");
  15056. }
  15057. PostProcess.prototype.isReusable = function () {
  15058. return this._reusable;
  15059. };
  15060. PostProcess.prototype.activate = function (camera, sourceTexture) {
  15061. camera = camera || this._camera;
  15062. var scene = camera.getScene();
  15063. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  15064. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  15065. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  15066. desiredWidth = BABYLON.Tools.GetExponantOfTwo(desiredWidth, maxSize);
  15067. desiredHeight = BABYLON.Tools.GetExponantOfTwo(desiredHeight, maxSize);
  15068. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  15069. if (this._textures.length > 0) {
  15070. for (var i = 0; i < this._textures.length; i++) {
  15071. this._engine._releaseTexture(this._textures.data[i]);
  15072. }
  15073. this._textures.reset();
  15074. }
  15075. this.width = desiredWidth;
  15076. this.height = desiredHeight;
  15077. 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 }));
  15078. if (this._reusable) {
  15079. 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 }));
  15080. }
  15081. if (this.onSizeChanged) {
  15082. this.onSizeChanged();
  15083. }
  15084. }
  15085. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  15086. if (this.onActivate) {
  15087. this.onActivate(camera);
  15088. }
  15089. // Clear
  15090. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  15091. if (this._reusable) {
  15092. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  15093. }
  15094. };
  15095. PostProcess.prototype.apply = function () {
  15096. // Check
  15097. if (!this._effect.isReady())
  15098. return null;
  15099. // States
  15100. this._engine.enableEffect(this._effect);
  15101. this._engine.setState(false);
  15102. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  15103. this._engine.setDepthBuffer(false);
  15104. this._engine.setDepthWrite(false);
  15105. // Texture
  15106. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  15107. // Parameters
  15108. if (this.onApply) {
  15109. this.onApply(this._effect);
  15110. }
  15111. return this._effect;
  15112. };
  15113. PostProcess.prototype.dispose = function (camera) {
  15114. camera = camera || this._camera;
  15115. if (this._textures.length > 0) {
  15116. for (var i = 0; i < this._textures.length; i++) {
  15117. this._engine._releaseTexture(this._textures.data[i]);
  15118. }
  15119. this._textures.reset();
  15120. }
  15121. camera.detachPostProcess(this);
  15122. var index = camera._postProcesses.indexOf(this);
  15123. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  15124. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  15125. }
  15126. };
  15127. return PostProcess;
  15128. })();
  15129. BABYLON.PostProcess = PostProcess;
  15130. })(BABYLON || (BABYLON = {}));
  15131. //# sourceMappingURL=babylon.postProcess.js.map
  15132. var BABYLON;
  15133. (function (BABYLON) {
  15134. var PostProcessManager = (function () {
  15135. function PostProcessManager(scene) {
  15136. this._vertexDeclaration = [2];
  15137. this._vertexStrideSize = 2 * 4;
  15138. this._scene = scene;
  15139. // VBO
  15140. var vertices = [];
  15141. vertices.push(1, 1);
  15142. vertices.push(-1, 1);
  15143. vertices.push(-1, -1);
  15144. vertices.push(1, -1);
  15145. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  15146. // Indices
  15147. var indices = [];
  15148. indices.push(0);
  15149. indices.push(1);
  15150. indices.push(2);
  15151. indices.push(0);
  15152. indices.push(2);
  15153. indices.push(3);
  15154. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  15155. }
  15156. // Methods
  15157. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  15158. var postProcesses = this._scene.activeCamera._postProcesses;
  15159. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  15160. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  15161. return false;
  15162. }
  15163. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  15164. return true;
  15165. };
  15166. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture) {
  15167. var postProcesses = this._scene.activeCamera._postProcesses;
  15168. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  15169. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  15170. return;
  15171. }
  15172. var engine = this._scene.getEngine();
  15173. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  15174. if (index < postProcessesTakenIndices.length - 1) {
  15175. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  15176. } else {
  15177. if (targetTexture) {
  15178. engine.bindFramebuffer(targetTexture);
  15179. } else {
  15180. engine.restoreDefaultFramebuffer();
  15181. }
  15182. }
  15183. if (doNotPresent) {
  15184. break;
  15185. }
  15186. var pp = postProcesses[postProcessesTakenIndices[index]];
  15187. var effect = pp.apply();
  15188. if (effect) {
  15189. if (pp.onBeforeRender) {
  15190. pp.onBeforeRender(effect);
  15191. }
  15192. // VBOs
  15193. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  15194. // Draw order
  15195. engine.draw(true, 0, 6);
  15196. }
  15197. }
  15198. // Restore depth buffer
  15199. engine.setDepthBuffer(true);
  15200. engine.setDepthWrite(true);
  15201. };
  15202. PostProcessManager.prototype.dispose = function () {
  15203. if (this._vertexBuffer) {
  15204. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  15205. this._vertexBuffer = null;
  15206. }
  15207. if (this._indexBuffer) {
  15208. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  15209. this._indexBuffer = null;
  15210. }
  15211. };
  15212. return PostProcessManager;
  15213. })();
  15214. BABYLON.PostProcessManager = PostProcessManager;
  15215. })(BABYLON || (BABYLON = {}));
  15216. //# sourceMappingURL=babylon.postProcessManager.js.map
  15217. var BABYLON;
  15218. (function (BABYLON) {
  15219. var PassPostProcess = (function (_super) {
  15220. __extends(PassPostProcess, _super);
  15221. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  15222. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  15223. }
  15224. return PassPostProcess;
  15225. })(BABYLON.PostProcess);
  15226. BABYLON.PassPostProcess = PassPostProcess;
  15227. })(BABYLON || (BABYLON = {}));
  15228. //# sourceMappingURL=babylon.passPostProcess.js.map
  15229. var BABYLON;
  15230. (function (BABYLON) {
  15231. var BlurPostProcess = (function (_super) {
  15232. __extends(BlurPostProcess, _super);
  15233. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  15234. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  15235. var _this = this;
  15236. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  15237. this.direction = direction;
  15238. this.blurWidth = blurWidth;
  15239. this.onApply = function (effect) {
  15240. effect.setFloat2("screenSize", _this.width, _this.height);
  15241. effect.setVector2("direction", _this.direction);
  15242. effect.setFloat("blurWidth", _this.blurWidth);
  15243. };
  15244. }
  15245. return BlurPostProcess;
  15246. })(BABYLON.PostProcess);
  15247. BABYLON.BlurPostProcess = BlurPostProcess;
  15248. })(BABYLON || (BABYLON = {}));
  15249. //# sourceMappingURL=babylon.blurPostProcess.js.map
  15250. var BABYLON;
  15251. (function (BABYLON) {
  15252. var FilterPostProcess = (function (_super) {
  15253. __extends(FilterPostProcess, _super);
  15254. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  15255. var _this = this;
  15256. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  15257. this.kernelMatrix = kernelMatrix;
  15258. this.onApply = function (effect) {
  15259. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  15260. };
  15261. }
  15262. return FilterPostProcess;
  15263. })(BABYLON.PostProcess);
  15264. BABYLON.FilterPostProcess = FilterPostProcess;
  15265. })(BABYLON || (BABYLON = {}));
  15266. //# sourceMappingURL=babylon.filterPostProcess.js.map
  15267. var BABYLON;
  15268. (function (BABYLON) {
  15269. var RefractionPostProcess = (function (_super) {
  15270. __extends(RefractionPostProcess, _super);
  15271. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  15272. var _this = this;
  15273. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  15274. this.color = color;
  15275. this.depth = depth;
  15276. this.colorLevel = colorLevel;
  15277. this.onActivate = function (cam) {
  15278. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  15279. };
  15280. this.onApply = function (effect) {
  15281. effect.setColor3("baseColor", _this.color);
  15282. effect.setFloat("depth", _this.depth);
  15283. effect.setFloat("colorLevel", _this.colorLevel);
  15284. effect.setTexture("refractionSampler", _this._refRexture);
  15285. };
  15286. }
  15287. // Methods
  15288. RefractionPostProcess.prototype.dispose = function (camera) {
  15289. if (this._refRexture) {
  15290. this._refRexture.dispose();
  15291. }
  15292. _super.prototype.dispose.call(this, camera);
  15293. };
  15294. return RefractionPostProcess;
  15295. })(BABYLON.PostProcess);
  15296. BABYLON.RefractionPostProcess = RefractionPostProcess;
  15297. })(BABYLON || (BABYLON = {}));
  15298. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  15299. var BABYLON;
  15300. (function (BABYLON) {
  15301. var BlackAndWhitePostProcess = (function (_super) {
  15302. __extends(BlackAndWhitePostProcess, _super);
  15303. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  15304. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  15305. }
  15306. return BlackAndWhitePostProcess;
  15307. })(BABYLON.PostProcess);
  15308. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  15309. })(BABYLON || (BABYLON = {}));
  15310. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  15311. var BABYLON;
  15312. (function (BABYLON) {
  15313. var ConvolutionPostProcess = (function (_super) {
  15314. __extends(ConvolutionPostProcess, _super);
  15315. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  15316. var _this = this;
  15317. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  15318. this.kernel = kernel;
  15319. this.onApply = function (effect) {
  15320. effect.setFloat2("screenSize", _this.width, _this.height);
  15321. effect.setArray("kernel", _this.kernel);
  15322. };
  15323. }
  15324. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  15325. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  15326. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  15327. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  15328. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  15329. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  15330. return ConvolutionPostProcess;
  15331. })(BABYLON.PostProcess);
  15332. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  15333. })(BABYLON || (BABYLON = {}));
  15334. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  15335. var BABYLON;
  15336. (function (BABYLON) {
  15337. var FxaaPostProcess = (function (_super) {
  15338. __extends(FxaaPostProcess, _super);
  15339. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  15340. var _this = this;
  15341. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  15342. this.onSizeChanged = function () {
  15343. _this.texelWidth = 1.0 / _this.width;
  15344. _this.texelHeight = 1.0 / _this.height;
  15345. };
  15346. this.onApply = function (effect) {
  15347. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  15348. };
  15349. }
  15350. return FxaaPostProcess;
  15351. })(BABYLON.PostProcess);
  15352. BABYLON.FxaaPostProcess = FxaaPostProcess;
  15353. })(BABYLON || (BABYLON = {}));
  15354. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  15355. var BABYLON;
  15356. (function (BABYLON) {
  15357. var LensFlare = (function () {
  15358. function LensFlare(size, position, color, imgUrl, system) {
  15359. this.size = size;
  15360. this.position = position;
  15361. this.dispose = function () {
  15362. if (this.texture) {
  15363. this.texture.dispose();
  15364. }
  15365. // Remove from scene
  15366. var index = this._system.lensFlares.indexOf(this);
  15367. this._system.lensFlares.splice(index, 1);
  15368. };
  15369. this.color = color || new BABYLON.Color3(1, 1, 1);
  15370. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  15371. this._system = system;
  15372. system.lensFlares.push(this);
  15373. }
  15374. return LensFlare;
  15375. })();
  15376. BABYLON.LensFlare = LensFlare;
  15377. })(BABYLON || (BABYLON = {}));
  15378. //# sourceMappingURL=babylon.lensFlare.js.map
  15379. var BABYLON;
  15380. (function (BABYLON) {
  15381. var LensFlareSystem = (function () {
  15382. function LensFlareSystem(name, emitter, scene) {
  15383. this.name = name;
  15384. this.lensFlares = new Array();
  15385. this.borderLimit = 300;
  15386. this._vertexDeclaration = [2];
  15387. this._vertexStrideSize = 2 * 4;
  15388. this._isEnabled = true;
  15389. this._scene = scene;
  15390. this._emitter = emitter;
  15391. scene.lensFlareSystems.push(this);
  15392. this.meshesSelectionPredicate = function (m) {
  15393. return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0);
  15394. };
  15395. // VBO
  15396. var vertices = [];
  15397. vertices.push(1, 1);
  15398. vertices.push(-1, 1);
  15399. vertices.push(-1, -1);
  15400. vertices.push(1, -1);
  15401. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  15402. // Indices
  15403. var indices = [];
  15404. indices.push(0);
  15405. indices.push(1);
  15406. indices.push(2);
  15407. indices.push(0);
  15408. indices.push(2);
  15409. indices.push(3);
  15410. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  15411. // Effects
  15412. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  15413. }
  15414. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  15415. get: function () {
  15416. return this._isEnabled;
  15417. },
  15418. set: function (value) {
  15419. this._isEnabled = value;
  15420. },
  15421. enumerable: true,
  15422. configurable: true
  15423. });
  15424. LensFlareSystem.prototype.getScene = function () {
  15425. return this._scene;
  15426. };
  15427. LensFlareSystem.prototype.getEmitter = function () {
  15428. return this._emitter;
  15429. };
  15430. LensFlareSystem.prototype.getEmitterPosition = function () {
  15431. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  15432. };
  15433. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  15434. var position = this.getEmitterPosition();
  15435. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  15436. this._positionX = position.x;
  15437. this._positionY = position.y;
  15438. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  15439. if (position.z > 0) {
  15440. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  15441. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  15442. return true;
  15443. }
  15444. }
  15445. return false;
  15446. };
  15447. LensFlareSystem.prototype._isVisible = function () {
  15448. if (!this._isEnabled) {
  15449. return false;
  15450. }
  15451. var emitterPosition = this.getEmitterPosition();
  15452. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  15453. var distance = direction.length();
  15454. direction.normalize();
  15455. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  15456. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  15457. return !pickInfo.hit || pickInfo.distance > distance;
  15458. };
  15459. LensFlareSystem.prototype.render = function () {
  15460. if (!this._effect.isReady())
  15461. return false;
  15462. var engine = this._scene.getEngine();
  15463. var viewport = this._scene.activeCamera.viewport;
  15464. var globalViewport = viewport.toGlobal(engine);
  15465. // Position
  15466. if (!this.computeEffectivePosition(globalViewport)) {
  15467. return false;
  15468. }
  15469. // Visibility
  15470. if (!this._isVisible()) {
  15471. return false;
  15472. }
  15473. // Intensity
  15474. var awayX;
  15475. var awayY;
  15476. if (this._positionX < this.borderLimit + globalViewport.x) {
  15477. awayX = this.borderLimit + globalViewport.x - this._positionX;
  15478. } else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  15479. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  15480. } else {
  15481. awayX = 0;
  15482. }
  15483. if (this._positionY < this.borderLimit + globalViewport.y) {
  15484. awayY = this.borderLimit + globalViewport.y - this._positionY;
  15485. } else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  15486. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  15487. } else {
  15488. awayY = 0;
  15489. }
  15490. var away = (awayX > awayY) ? awayX : awayY;
  15491. if (away > this.borderLimit) {
  15492. away = this.borderLimit;
  15493. }
  15494. var intensity = 1.0 - (away / this.borderLimit);
  15495. if (intensity < 0) {
  15496. return false;
  15497. }
  15498. if (intensity > 1.0) {
  15499. intensity = 1.0;
  15500. }
  15501. // Position
  15502. var centerX = globalViewport.x + globalViewport.width / 2;
  15503. var centerY = globalViewport.y + globalViewport.height / 2;
  15504. var distX = centerX - this._positionX;
  15505. var distY = centerY - this._positionY;
  15506. // Effects
  15507. engine.enableEffect(this._effect);
  15508. engine.setState(false);
  15509. engine.setDepthBuffer(false);
  15510. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  15511. // VBOs
  15512. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  15513. for (var index = 0; index < this.lensFlares.length; index++) {
  15514. var flare = this.lensFlares[index];
  15515. var x = centerX - (distX * flare.position);
  15516. var y = centerY - (distY * flare.position);
  15517. var cw = flare.size;
  15518. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  15519. var cx = 2 * (x / globalViewport.width) - 1.0;
  15520. var cy = 1.0 - 2 * (y / globalViewport.height);
  15521. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  15522. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  15523. // Texture
  15524. this._effect.setTexture("textureSampler", flare.texture);
  15525. // Color
  15526. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  15527. // Draw order
  15528. engine.draw(true, 0, 6);
  15529. }
  15530. engine.setDepthBuffer(true);
  15531. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  15532. return true;
  15533. };
  15534. LensFlareSystem.prototype.dispose = function () {
  15535. if (this._vertexBuffer) {
  15536. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  15537. this._vertexBuffer = null;
  15538. }
  15539. if (this._indexBuffer) {
  15540. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  15541. this._indexBuffer = null;
  15542. }
  15543. while (this.lensFlares.length) {
  15544. this.lensFlares[0].dispose();
  15545. }
  15546. // Remove from scene
  15547. var index = this._scene.lensFlareSystems.indexOf(this);
  15548. this._scene.lensFlareSystems.splice(index, 1);
  15549. };
  15550. return LensFlareSystem;
  15551. })();
  15552. BABYLON.LensFlareSystem = LensFlareSystem;
  15553. })(BABYLON || (BABYLON = {}));
  15554. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  15555. var BABYLON;
  15556. (function (BABYLON) {
  15557. var IntersectionInfo = (function () {
  15558. function IntersectionInfo(bu, bv, distance) {
  15559. this.bu = bu;
  15560. this.bv = bv;
  15561. this.distance = distance;
  15562. this.faceId = 0;
  15563. }
  15564. return IntersectionInfo;
  15565. })();
  15566. BABYLON.IntersectionInfo = IntersectionInfo;
  15567. var PickingInfo = (function () {
  15568. function PickingInfo() {
  15569. this.hit = false;
  15570. this.distance = 0;
  15571. this.pickedPoint = null;
  15572. this.pickedMesh = null;
  15573. this.bu = 0;
  15574. this.bv = 0;
  15575. this.faceId = -1;
  15576. }
  15577. // Methods
  15578. PickingInfo.prototype.getNormal = function () {
  15579. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15580. return null;
  15581. }
  15582. var indices = this.pickedMesh.getIndices();
  15583. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15584. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  15585. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  15586. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  15587. normal0 = normal0.scale(this.bu);
  15588. normal1 = normal1.scale(this.bv);
  15589. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  15590. return new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  15591. };
  15592. PickingInfo.prototype.getTextureCoordinates = function () {
  15593. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  15594. return null;
  15595. }
  15596. var indices = this.pickedMesh.getIndices();
  15597. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  15598. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  15599. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  15600. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  15601. uv0 = uv0.scale(this.bu);
  15602. uv1 = uv1.scale(this.bv);
  15603. uv2 = uv2.scale(1.0 - this.bu - this.bv);
  15604. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  15605. };
  15606. return PickingInfo;
  15607. })();
  15608. BABYLON.PickingInfo = PickingInfo;
  15609. })(BABYLON || (BABYLON = {}));
  15610. //# sourceMappingURL=babylon.pickingInfo.js.map
  15611. var BABYLON;
  15612. (function (BABYLON) {
  15613. var FilesInput = (function () {
  15614. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  15615. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  15616. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  15617. this.engine = p_engine;
  15618. this.canvas = p_canvas;
  15619. this.currentScene = p_scene;
  15620. this.sceneLoadedCallback = p_sceneLoadedCallback;
  15621. this.progressCallback = p_progressCallback;
  15622. this.additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  15623. this.textureLoadingCallback = p_textureLoadingCallback;
  15624. this.startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  15625. }
  15626. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  15627. var _this = this;
  15628. if (p_elementToMonitor) {
  15629. this.elementToMonitor = p_elementToMonitor;
  15630. this.elementToMonitor.addEventListener("dragenter", function (e) {
  15631. _this.drag(e);
  15632. }, false);
  15633. this.elementToMonitor.addEventListener("dragover", function (e) {
  15634. _this.drag(e);
  15635. }, false);
  15636. this.elementToMonitor.addEventListener("drop", function (e) {
  15637. _this.drop(e);
  15638. }, false);
  15639. }
  15640. };
  15641. FilesInput.prototype.renderFunction = function () {
  15642. if (this.additionnalRenderLoopLogicCallback) {
  15643. this.additionnalRenderLoopLogicCallback();
  15644. }
  15645. if (this.currentScene) {
  15646. if (this.textureLoadingCallback) {
  15647. var remaining = this.currentScene.getWaitingItemsCount();
  15648. if (remaining > 0) {
  15649. this.textureLoadingCallback(remaining);
  15650. }
  15651. }
  15652. this.currentScene.render();
  15653. }
  15654. };
  15655. FilesInput.prototype.drag = function (e) {
  15656. e.stopPropagation();
  15657. e.preventDefault();
  15658. };
  15659. FilesInput.prototype.drop = function (eventDrop) {
  15660. eventDrop.stopPropagation();
  15661. eventDrop.preventDefault();
  15662. this.loadFiles(eventDrop);
  15663. };
  15664. FilesInput.prototype.loadFiles = function (event) {
  15665. var _this = this;
  15666. var that = this;
  15667. if (this.startingProcessingFilesCallback)
  15668. this.startingProcessingFilesCallback();
  15669. var sceneFileToLoad;
  15670. var filesToLoad;
  15671. // Handling data transfer via drag'n'drop
  15672. if (event && event.dataTransfer && event.dataTransfer.files) {
  15673. filesToLoad = event.dataTransfer.files;
  15674. }
  15675. // Handling files from input files
  15676. if (event && event.target && event.target.files) {
  15677. filesToLoad = event.target.files;
  15678. }
  15679. if (filesToLoad && filesToLoad.length > 0) {
  15680. for (var i = 0; i < filesToLoad.length; i++) {
  15681. switch (filesToLoad[i].type) {
  15682. case "image/jpeg":
  15683. case "image/png":
  15684. BABYLON.FilesInput.FilesTextures[filesToLoad[i].name] = filesToLoad[i];
  15685. break;
  15686. case "image/targa":
  15687. case "image/vnd.ms-dds":
  15688. BABYLON.FilesInput.FilesToLoad[filesToLoad[i].name] = filesToLoad[i];
  15689. break;
  15690. default:
  15691. 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) {
  15692. sceneFileToLoad = filesToLoad[i];
  15693. }
  15694. break;
  15695. }
  15696. }
  15697. // If a ".babylon" file has been provided
  15698. if (sceneFileToLoad) {
  15699. if (this.currentScene) {
  15700. this.engine.stopRenderLoop();
  15701. this.currentScene.dispose();
  15702. }
  15703. BABYLON.SceneLoader.Load("file:", sceneFileToLoad, this.engine, function (newScene) {
  15704. that.currentScene = newScene;
  15705. // Wait for textures and shaders to be ready
  15706. that.currentScene.executeWhenReady(function () {
  15707. // Attach camera to canvas inputs
  15708. if (that.currentScene.activeCamera) {
  15709. that.currentScene.activeCamera.attachControl(that.canvas);
  15710. }
  15711. if (that.sceneLoadedCallback) {
  15712. that.sceneLoadedCallback(sceneFileToLoad, that.currentScene);
  15713. }
  15714. that.engine.runRenderLoop(function () {
  15715. that.renderFunction();
  15716. });
  15717. });
  15718. }, function (progress) {
  15719. if (_this.progressCallback) {
  15720. _this.progressCallback(progress);
  15721. }
  15722. });
  15723. } else {
  15724. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  15725. }
  15726. }
  15727. };
  15728. FilesInput.FilesTextures = new Array();
  15729. FilesInput.FilesToLoad = new Array();
  15730. return FilesInput;
  15731. })();
  15732. BABYLON.FilesInput = FilesInput;
  15733. })(BABYLON || (BABYLON = {}));
  15734. //# sourceMappingURL=babylon.filesInput.js.map
  15735. var BABYLON;
  15736. (function (BABYLON) {
  15737. var OimoJSPlugin = (function () {
  15738. function OimoJSPlugin() {
  15739. this._registeredMeshes = [];
  15740. /**
  15741. * Update the body position according to the mesh position
  15742. * @param mesh
  15743. */
  15744. this.updateBodyPosition = function (mesh) {
  15745. for (var index = 0; index < this._registeredMeshes.length; index++) {
  15746. var registeredMesh = this._registeredMeshes[index];
  15747. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  15748. var body = registeredMesh.body.body;
  15749. mesh.computeWorldMatrix(true);
  15750. var center = mesh.getBoundingInfo().boundingBox.center;
  15751. body.setPosition(center.x, center.y, center.z);
  15752. body.setOrientation(mesh.rotation.x, mesh.rotation.y, mesh.rotation.z);
  15753. return;
  15754. }
  15755. // Case where the parent has been updated
  15756. if (registeredMesh.mesh.parent === mesh) {
  15757. mesh.computeWorldMatrix(true);
  15758. registeredMesh.mesh.computeWorldMatrix(true);
  15759. var absolutePosition = registeredMesh.mesh.getAbsolutePosition();
  15760. var absoluteRotation = mesh.rotation;
  15761. body = registeredMesh.body.body;
  15762. body.setPosition(absolutePosition.x, absolutePosition.y, absolutePosition.z);
  15763. body.setOrientation(absoluteRotation.x, absoluteRotation.y, absoluteRotation.z);
  15764. return;
  15765. }
  15766. }
  15767. };
  15768. }
  15769. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  15770. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  15771. };
  15772. OimoJSPlugin.prototype.initialize = function (iterations) {
  15773. this._world = new OIMO.World();
  15774. this._world.clear();
  15775. };
  15776. OimoJSPlugin.prototype.setGravity = function (gravity) {
  15777. this._world.gravity = gravity;
  15778. };
  15779. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  15780. var body = null;
  15781. this.unregisterMesh(mesh);
  15782. mesh.computeWorldMatrix(true);
  15783. switch (impostor) {
  15784. case BABYLON.PhysicsEngine.SphereImpostor:
  15785. var bbox = mesh.getBoundingInfo().boundingBox;
  15786. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  15787. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  15788. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  15789. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  15790. // The delta between the mesh position and the mesh bounding box center
  15791. var deltaPosition = mesh.position.subtract(bbox.center);
  15792. body = new OIMO.Body({
  15793. type: 'sphere',
  15794. size: [size],
  15795. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  15796. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  15797. move: options.mass != 0,
  15798. config: [options.mass, options.friction, options.restitution],
  15799. world: this._world
  15800. });
  15801. this._registeredMeshes.push({
  15802. mesh: mesh,
  15803. body: body,
  15804. delta: deltaPosition
  15805. });
  15806. break;
  15807. case BABYLON.PhysicsEngine.PlaneImpostor:
  15808. case BABYLON.PhysicsEngine.BoxImpostor:
  15809. bbox = mesh.getBoundingInfo().boundingBox;
  15810. var min = bbox.minimumWorld;
  15811. var max = bbox.maximumWorld;
  15812. var box = max.subtract(min);
  15813. var sizeX = this._checkWithEpsilon(box.x);
  15814. var sizeY = this._checkWithEpsilon(box.y);
  15815. var sizeZ = this._checkWithEpsilon(box.z);
  15816. // The delta between the mesh position and the mesh boudning box center
  15817. var deltaPosition = mesh.position.subtract(bbox.center);
  15818. body = new OIMO.Body({
  15819. type: 'box',
  15820. size: [sizeX, sizeY, sizeZ],
  15821. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  15822. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  15823. move: options.mass != 0,
  15824. config: [options.mass, options.friction, options.restitution],
  15825. world: this._world
  15826. });
  15827. this._registeredMeshes.push({
  15828. mesh: mesh,
  15829. body: body,
  15830. delta: deltaPosition
  15831. });
  15832. break;
  15833. }
  15834. return body;
  15835. };
  15836. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  15837. var types = [], sizes = [], positions = [], rotations = [];
  15838. var initialMesh = parts[0].mesh;
  15839. for (var index = 0; index < parts.length; index++) {
  15840. var part = parts[index];
  15841. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  15842. types.push(bodyParameters.type);
  15843. sizes.push.apply(sizes, bodyParameters.size);
  15844. positions.push.apply(positions, bodyParameters.pos);
  15845. rotations.push.apply(rotations, bodyParameters.rot);
  15846. }
  15847. var body = new OIMO.Body({
  15848. type: types,
  15849. size: sizes,
  15850. pos: positions,
  15851. rot: rotations,
  15852. move: options.mass != 0,
  15853. config: [options.mass, options.friction, options.restitution],
  15854. world: this._world
  15855. });
  15856. this._registeredMeshes.push({
  15857. mesh: initialMesh,
  15858. body: body
  15859. });
  15860. return body;
  15861. };
  15862. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  15863. var bodyParameters = null;
  15864. var mesh = part.mesh;
  15865. switch (part.impostor) {
  15866. case BABYLON.PhysicsEngine.SphereImpostor:
  15867. var bbox = mesh.getBoundingInfo().boundingBox;
  15868. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  15869. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  15870. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  15871. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  15872. bodyParameters = {
  15873. type: 'sphere',
  15874. /* bug with oimo : sphere needs 3 sizes in this case */
  15875. size: [size, -1, -1],
  15876. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  15877. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  15878. };
  15879. break;
  15880. case BABYLON.PhysicsEngine.PlaneImpostor:
  15881. case BABYLON.PhysicsEngine.BoxImpostor:
  15882. bbox = mesh.getBoundingInfo().boundingBox;
  15883. var min = bbox.minimumWorld;
  15884. var max = bbox.maximumWorld;
  15885. var box = max.subtract(min);
  15886. var sizeX = this._checkWithEpsilon(box.x);
  15887. var sizeY = this._checkWithEpsilon(box.y);
  15888. var sizeZ = this._checkWithEpsilon(box.z);
  15889. var relativePosition = mesh.position;
  15890. bodyParameters = {
  15891. type: 'box',
  15892. size: [sizeX, sizeY, sizeZ],
  15893. pos: [relativePosition.x, relativePosition.y, relativePosition.z],
  15894. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  15895. };
  15896. break;
  15897. }
  15898. return bodyParameters;
  15899. };
  15900. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  15901. for (var index = 0; index < this._registeredMeshes.length; index++) {
  15902. var registeredMesh = this._registeredMeshes[index];
  15903. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  15904. if (registeredMesh.body) {
  15905. this._world.removeRigidBody(registeredMesh.body.body);
  15906. this._unbindBody(registeredMesh.body);
  15907. }
  15908. this._registeredMeshes.splice(index, 1);
  15909. return;
  15910. }
  15911. }
  15912. };
  15913. OimoJSPlugin.prototype._unbindBody = function (body) {
  15914. for (var index = 0; index < this._registeredMeshes.length; index++) {
  15915. var registeredMesh = this._registeredMeshes[index];
  15916. if (registeredMesh.body === body) {
  15917. registeredMesh.body = null;
  15918. }
  15919. }
  15920. };
  15921. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  15922. for (var index = 0; index < this._registeredMeshes.length; index++) {
  15923. var registeredMesh = this._registeredMeshes[index];
  15924. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  15925. // Get object mass to have a behaviour similar to cannon.js
  15926. var mass = registeredMesh.body.body.massInfo.mass;
  15927. // The force is scaled with the mass of object
  15928. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  15929. return;
  15930. }
  15931. }
  15932. };
  15933. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  15934. var body1 = null, body2 = null;
  15935. for (var index = 0; index < this._registeredMeshes.length; index++) {
  15936. var registeredMesh = this._registeredMeshes[index];
  15937. if (registeredMesh.mesh === mesh1) {
  15938. body1 = registeredMesh.body.body;
  15939. } else if (registeredMesh.mesh === mesh2) {
  15940. body2 = registeredMesh.body.body;
  15941. }
  15942. }
  15943. if (!body1 || !body2) {
  15944. return false;
  15945. }
  15946. if (!options) {
  15947. options = {};
  15948. }
  15949. new OIMO.Link({
  15950. type: options.type,
  15951. body1: body1,
  15952. body2: body2,
  15953. min: options.min,
  15954. max: options.max,
  15955. axe1: options.axe1,
  15956. axe2: options.axe2,
  15957. pos1: [pivot1.x, pivot1.y, pivot1.z],
  15958. pos2: [pivot2.x, pivot2.y, pivot2.z],
  15959. collision: options.collision,
  15960. spring: options.spring,
  15961. world: this._world
  15962. });
  15963. return true;
  15964. };
  15965. OimoJSPlugin.prototype.dispose = function () {
  15966. this._world.clear();
  15967. while (this._registeredMeshes.length) {
  15968. this.unregisterMesh(this._registeredMeshes[0].mesh);
  15969. }
  15970. };
  15971. OimoJSPlugin.prototype.isSupported = function () {
  15972. return OIMO !== undefined;
  15973. };
  15974. OimoJSPlugin.prototype._getLastShape = function (body) {
  15975. var lastShape = body.shapes;
  15976. while (lastShape.next) {
  15977. lastShape = lastShape.next;
  15978. }
  15979. return lastShape;
  15980. };
  15981. OimoJSPlugin.prototype.runOneStep = function (time) {
  15982. this._world.step();
  15983. // Update the position of all registered meshes
  15984. var i = this._registeredMeshes.length;
  15985. var m;
  15986. while (i--) {
  15987. var body = this._registeredMeshes[i].body.body;
  15988. var mesh = this._registeredMeshes[i].mesh;
  15989. var delta = this._registeredMeshes[i].delta;
  15990. if (!body.sleeping) {
  15991. if (body.shapes.next) {
  15992. var parentShape = this._getLastShape(body);
  15993. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  15994. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  15995. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  15996. var mtx = BABYLON.Matrix.FromArray(body.getMatrix());
  15997. if (!mesh.rotationQuaternion) {
  15998. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  15999. }
  16000. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  16001. mesh.computeWorldMatrix();
  16002. } else {
  16003. m = body.getMatrix();
  16004. mtx = BABYLON.Matrix.FromArray(m);
  16005. // Body position
  16006. var bodyX = mtx.m[12], bodyY = mtx.m[13], bodyZ = mtx.m[14];
  16007. if (!delta) {
  16008. mesh.position.x = bodyX;
  16009. mesh.position.y = bodyY;
  16010. mesh.position.z = bodyZ;
  16011. } else {
  16012. mesh.position.x = bodyX + delta.x;
  16013. mesh.position.y = bodyY + delta.y;
  16014. mesh.position.z = bodyZ + delta.z;
  16015. }
  16016. if (!mesh.rotationQuaternion) {
  16017. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  16018. }
  16019. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  16020. mesh.computeWorldMatrix();
  16021. }
  16022. }
  16023. }
  16024. };
  16025. return OimoJSPlugin;
  16026. })();
  16027. BABYLON.OimoJSPlugin = OimoJSPlugin;
  16028. })(BABYLON || (BABYLON = {}));
  16029. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  16030. var BABYLON;
  16031. (function (BABYLON) {
  16032. var PhysicsEngine = (function () {
  16033. function PhysicsEngine(plugin) {
  16034. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  16035. }
  16036. PhysicsEngine.prototype._initialize = function (gravity) {
  16037. this._currentPlugin.initialize();
  16038. this._setGravity(gravity);
  16039. };
  16040. PhysicsEngine.prototype._runOneStep = function (delta) {
  16041. if (delta > 0.1) {
  16042. delta = 0.1;
  16043. } else if (delta <= 0) {
  16044. delta = 1.0 / 60.0;
  16045. }
  16046. this._currentPlugin.runOneStep(delta);
  16047. };
  16048. PhysicsEngine.prototype._setGravity = function (gravity) {
  16049. this.gravity = gravity || new BABYLON.Vector3(0, -9.82, 0);
  16050. this._currentPlugin.setGravity(this.gravity);
  16051. };
  16052. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  16053. return this._currentPlugin.registerMesh(mesh, impostor, options);
  16054. };
  16055. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  16056. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  16057. };
  16058. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  16059. this._currentPlugin.unregisterMesh(mesh);
  16060. };
  16061. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  16062. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  16063. };
  16064. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  16065. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  16066. };
  16067. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  16068. this._currentPlugin.updateBodyPosition(mesh);
  16069. };
  16070. PhysicsEngine.prototype.dispose = function () {
  16071. this._currentPlugin.dispose();
  16072. };
  16073. PhysicsEngine.prototype.isSupported = function () {
  16074. return this._currentPlugin.isSupported();
  16075. };
  16076. PhysicsEngine.NoImpostor = 0;
  16077. PhysicsEngine.SphereImpostor = 1;
  16078. PhysicsEngine.BoxImpostor = 2;
  16079. PhysicsEngine.PlaneImpostor = 3;
  16080. PhysicsEngine.MeshImpostor = 4;
  16081. PhysicsEngine.CapsuleImpostor = 5;
  16082. PhysicsEngine.ConeImpostor = 6;
  16083. PhysicsEngine.CylinderImpostor = 7;
  16084. PhysicsEngine.ConvexHullImpostor = 8;
  16085. PhysicsEngine.Epsilon = 0.001;
  16086. return PhysicsEngine;
  16087. })();
  16088. BABYLON.PhysicsEngine = PhysicsEngine;
  16089. })(BABYLON || (BABYLON = {}));
  16090. //# sourceMappingURL=babylon.physicsEngine.js.map
  16091. var BABYLON;
  16092. (function (BABYLON) {
  16093. var serializeLight = function (light) {
  16094. var serializationObject = {};
  16095. serializationObject.name = light.name;
  16096. serializationObject.id = light.id;
  16097. serializationObject.tags = BABYLON.Tags.GetTags(light);
  16098. if (light instanceof BABYLON.PointLight) {
  16099. serializationObject.type = 0;
  16100. serializationObject.position = light.position.asArray();
  16101. } else if (light instanceof BABYLON.DirectionalLight) {
  16102. serializationObject.type = 1;
  16103. var directionalLight = light;
  16104. serializationObject.position = directionalLight.position.asArray();
  16105. serializationObject.direction = directionalLight.direction.asArray();
  16106. } else if (light instanceof BABYLON.SpotLight) {
  16107. serializationObject.type = 2;
  16108. var spotLight = light;
  16109. serializationObject.position = spotLight.position.asArray();
  16110. serializationObject.direction = spotLight.position.asArray();
  16111. serializationObject.angle = spotLight.angle;
  16112. serializationObject.exponent = spotLight.exponent;
  16113. } else if (light instanceof BABYLON.HemisphericLight) {
  16114. serializationObject.type = 3;
  16115. var hemisphericLight = light;
  16116. serializationObject.direction = hemisphericLight.direction.asArray();
  16117. serializationObject.groundColor = hemisphericLight.groundColor.asArray();
  16118. }
  16119. if (light.intensity) {
  16120. serializationObject.intensity = light.intensity;
  16121. }
  16122. serializationObject.range = light.range;
  16123. serializationObject.diffuse = light.diffuse.asArray();
  16124. serializationObject.specular = light.specular.asArray();
  16125. return serializationObject;
  16126. };
  16127. var serializeFresnelParameter = function (fresnelParameter) {
  16128. var serializationObject = {};
  16129. serializationObject.isEnabled = fresnelParameter.isEnabled;
  16130. serializationObject.leftColor = fresnelParameter.leftColor;
  16131. serializationObject.rightColor = fresnelParameter.rightColor;
  16132. serializationObject.bias = fresnelParameter.bias;
  16133. serializationObject.power = fresnelParameter.power;
  16134. return serializationObject;
  16135. };
  16136. var serializeCamera = function (camera) {
  16137. var serializationObject = {};
  16138. serializationObject.name = camera.name;
  16139. serializationObject.tags = BABYLON.Tags.GetTags(camera);
  16140. serializationObject.id = camera.id;
  16141. serializationObject.position = camera.position.asArray();
  16142. // Parent
  16143. if (camera.parent) {
  16144. serializationObject.parentId = camera.parent.id;
  16145. }
  16146. // Target
  16147. serializationObject.rotation = camera.rotation.asArray();
  16148. // Locked target
  16149. if (camera.lockedTarget && camera.lockedTarget.id) {
  16150. serializationObject.lockedTargetId = camera.lockedTarget.id;
  16151. }
  16152. serializationObject.fov = camera.fov;
  16153. serializationObject.minZ = camera.minZ;
  16154. serializationObject.maxZ = camera.maxZ;
  16155. serializationObject.speed = camera.speed;
  16156. serializationObject.inertia = camera.inertia;
  16157. serializationObject.checkCollisions = camera.checkCollisions;
  16158. serializationObject.applyGravity = camera.applyGravity;
  16159. if (camera.ellipsoid) {
  16160. serializationObject.ellipsoid = camera.ellipsoid.asArray();
  16161. }
  16162. // Animations
  16163. appendAnimations(camera, serializationObject);
  16164. // Layer mask
  16165. serializationObject.layerMask = camera.layerMask;
  16166. return serializationObject;
  16167. };
  16168. var appendAnimations = function (source, destination) {
  16169. if (source.animations) {
  16170. destination.animations = [];
  16171. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  16172. var animation = source.animations[animationIndex];
  16173. destination.animations.push(serializeAnimation(animation));
  16174. }
  16175. }
  16176. };
  16177. var serializeAnimation = function (animation) {
  16178. var serializationObject = {};
  16179. serializationObject.name = animation.name;
  16180. serializationObject.property = animation.targetProperty;
  16181. serializationObject.framePerSecond = animation.framePerSecond;
  16182. serializationObject.dataType = animation.dataType;
  16183. serializationObject.loopBehavior = animation.loopMode;
  16184. var dataType = animation.dataType;
  16185. serializationObject.keys = [];
  16186. var keys = animation.getKeys();
  16187. for (var index = 0; index < keys.length; index++) {
  16188. var animationKey = keys[index];
  16189. var key = {};
  16190. key.frame = animationKey.frame;
  16191. switch (dataType) {
  16192. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  16193. key.values = [animationKey.value];
  16194. break;
  16195. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  16196. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  16197. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  16198. key.values = animationKey.value.asArray();
  16199. break;
  16200. }
  16201. serializationObject.keys.push(key);
  16202. }
  16203. return serializationObject;
  16204. };
  16205. var serializeMultiMaterial = function (material) {
  16206. var serializationObject = {};
  16207. serializationObject.name = material.name;
  16208. serializationObject.id = material.id;
  16209. serializationObject.tags = BABYLON.Tags.GetTags(material);
  16210. serializationObject.materials = [];
  16211. for (var matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
  16212. var subMat = material.subMaterials[matIndex];
  16213. if (subMat) {
  16214. serializationObject.materials.push(subMat.id);
  16215. } else {
  16216. serializationObject.materials.push(null);
  16217. }
  16218. }
  16219. return serializationObject;
  16220. };
  16221. var serializeMaterial = function (material) {
  16222. var serializationObject = {};
  16223. serializationObject.name = material.name;
  16224. serializationObject.ambient = material.ambientColor.asArray();
  16225. serializationObject.diffuse = material.diffuseColor.asArray();
  16226. serializationObject.specular = material.specularColor.asArray();
  16227. serializationObject.specularPower = material.specularPower;
  16228. serializationObject.emissive = material.emissiveColor.asArray();
  16229. serializationObject.alpha = material.alpha;
  16230. serializationObject.id = material.id;
  16231. serializationObject.tags = BABYLON.Tags.GetTags(material);
  16232. serializationObject.backFaceCulling = material.backFaceCulling;
  16233. if (material.diffuseTexture) {
  16234. serializationObject.diffuseTexture = serializeTexture(material.diffuseTexture);
  16235. }
  16236. if (material.diffuseFresnelParameters) {
  16237. serializationObject.diffuseFresnelParameters = serializeFresnelParameter(material.diffuseFresnelParameters);
  16238. }
  16239. if (material.ambientTexture) {
  16240. serializationObject.ambientTexture = serializeTexture(material.ambientTexture);
  16241. }
  16242. if (material.opacityTexture) {
  16243. serializationObject.opacityTexture = serializeTexture(material.opacityTexture);
  16244. }
  16245. if (material.opacityFresnelParameters) {
  16246. serializationObject.opacityFresnelParameters = serializeFresnelParameter(material.opacityFresnelParameters);
  16247. }
  16248. if (material.reflectionTexture) {
  16249. serializationObject.reflectionTexture = serializeTexture(material.reflectionTexture);
  16250. }
  16251. if (material.reflectionFresnelParameters) {
  16252. serializationObject.reflectionFresnelParameters = serializeFresnelParameter(material.reflectionFresnelParameters);
  16253. }
  16254. if (material.emissiveTexture) {
  16255. serializationObject.emissiveTexture = serializeTexture(material.emissiveTexture);
  16256. }
  16257. if (material.emissiveFresnelParameters) {
  16258. serializationObject.emissiveFresnelParameters = serializeFresnelParameter(material.emissiveFresnelParameters);
  16259. }
  16260. if (material.specularTexture) {
  16261. serializationObject.specularTexture = serializeTexture(material.specularTexture);
  16262. }
  16263. if (material.bumpTexture) {
  16264. serializationObject.bumpTexture = serializeTexture(material.bumpTexture);
  16265. }
  16266. return serializationObject;
  16267. };
  16268. var serializeTexture = function (texture) {
  16269. var serializationObject = {};
  16270. if (!texture.name) {
  16271. return null;
  16272. }
  16273. if (texture instanceof BABYLON.CubeTexture) {
  16274. serializationObject.name = texture.name;
  16275. serializationObject.hasAlpha = texture.hasAlpha;
  16276. serializationObject.level = texture.level;
  16277. serializationObject.coordinatesMode = texture.coordinatesMode;
  16278. return serializationObject;
  16279. }
  16280. if (texture instanceof BABYLON.MirrorTexture) {
  16281. var mirrorTexture = texture;
  16282. serializationObject.renderTargetSize = mirrorTexture.getRenderSize();
  16283. serializationObject.renderList = [];
  16284. for (var index = 0; index < mirrorTexture.renderList.length; index++) {
  16285. serializationObject.renderList.push(mirrorTexture.renderList[index].id);
  16286. }
  16287. serializationObject.mirrorPlane = mirrorTexture.mirrorPlane.asArray();
  16288. } else if (texture instanceof BABYLON.RenderTargetTexture) {
  16289. var renderTargetTexture = texture;
  16290. serializationObject.renderTargetSize = renderTargetTexture.getRenderSize();
  16291. serializationObject.renderList = [];
  16292. for (index = 0; index < renderTargetTexture.renderList.length; index++) {
  16293. serializationObject.renderList.push(renderTargetTexture.renderList[index].id);
  16294. }
  16295. }
  16296. var regularTexture = texture;
  16297. serializationObject.name = texture.name;
  16298. serializationObject.hasAlpha = texture.hasAlpha;
  16299. serializationObject.level = texture.level;
  16300. serializationObject.coordinatesIndex = texture.coordinatesIndex;
  16301. serializationObject.coordinatesMode = texture.coordinatesMode;
  16302. serializationObject.uOffset = regularTexture.uOffset;
  16303. serializationObject.vOffset = regularTexture.vOffset;
  16304. serializationObject.uScale = regularTexture.uScale;
  16305. serializationObject.vScale = regularTexture.vScale;
  16306. serializationObject.uAng = regularTexture.uAng;
  16307. serializationObject.vAng = regularTexture.vAng;
  16308. serializationObject.wAng = regularTexture.wAng;
  16309. serializationObject.wrapU = texture.wrapU;
  16310. serializationObject.wrapV = texture.wrapV;
  16311. // Animations
  16312. appendAnimations(texture, serializationObject);
  16313. return serializationObject;
  16314. };
  16315. var serializeSkeleton = function (skeleton) {
  16316. var serializationObject = {};
  16317. serializationObject.name = skeleton.name;
  16318. serializationObject.id = skeleton.id;
  16319. serializationObject.bones = [];
  16320. for (var index = 0; index < skeleton.bones.length; index++) {
  16321. var bone = skeleton.bones[index];
  16322. var serializedBone = {
  16323. parentBoneIndex: bone.getParent() ? skeleton.bones.indexOf(bone.getParent()) : -1,
  16324. name: bone.name,
  16325. matrix: bone.getLocalMatrix().toArray()
  16326. };
  16327. serializationObject.bones.push(serializedBone);
  16328. if (bone.animations && bone.animations.length > 0) {
  16329. serializedBone.animation = serializeAnimation(bone.animations[0]);
  16330. }
  16331. }
  16332. return serializationObject;
  16333. };
  16334. var serializeParticleSystem = function (particleSystem) {
  16335. var serializationObject = {};
  16336. serializationObject.emitterId = particleSystem.emitter.id;
  16337. serializationObject.capacity = particleSystem.getCapacity();
  16338. if (particleSystem.particleTexture) {
  16339. serializationObject.textureName = particleSystem.particleTexture.name;
  16340. }
  16341. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  16342. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  16343. serializationObject.minSize = particleSystem.minSize;
  16344. serializationObject.maxSize = particleSystem.maxSize;
  16345. serializationObject.minLifeTime = particleSystem.minLifeTime;
  16346. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  16347. serializationObject.emitRate = particleSystem.emitRate;
  16348. serializationObject.minEmitBox = particleSystem.minEmitBox.asArray();
  16349. serializationObject.maxEmitBox = particleSystem.maxEmitBox.asArray();
  16350. serializationObject.gravity = particleSystem.gravity.asArray();
  16351. serializationObject.direction1 = particleSystem.direction1.asArray();
  16352. serializationObject.direction2 = particleSystem.direction2.asArray();
  16353. serializationObject.color1 = particleSystem.color1.asArray();
  16354. serializationObject.color2 = particleSystem.color2.asArray();
  16355. serializationObject.colorDead = particleSystem.colorDead.asArray();
  16356. serializationObject.updateSpeed = particleSystem.updateSpeed;
  16357. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  16358. serializationObject.textureMask = particleSystem.textureMask.asArray();
  16359. serializationObject.blendMode = particleSystem.blendMode;
  16360. return serializationObject;
  16361. };
  16362. var serializeLensFlareSystem = function (lensFlareSystem) {
  16363. var serializationObject = {};
  16364. serializationObject.emitterId = lensFlareSystem.getEmitter().id;
  16365. serializationObject.borderLimit = lensFlareSystem.borderLimit;
  16366. serializationObject.flares = [];
  16367. for (var index = 0; index < lensFlareSystem.lensFlares.length; index++) {
  16368. var flare = lensFlareSystem.lensFlares[index];
  16369. serializationObject.flares.push({
  16370. size: flare.size,
  16371. position: flare.position,
  16372. color: flare.color.asArray(),
  16373. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  16374. });
  16375. }
  16376. return serializationObject;
  16377. };
  16378. var serializeShadowGenerator = function (light) {
  16379. var serializationObject = {};
  16380. var shadowGenerator = light.getShadowGenerator();
  16381. serializationObject.lightId = light.id;
  16382. serializationObject.mapSize = shadowGenerator.getShadowMap().getRenderSize();
  16383. serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
  16384. serializationObject.usePoissonSampling = shadowGenerator.usePoissonSampling;
  16385. serializationObject.renderList = [];
  16386. for (var meshIndex = 0; meshIndex < shadowGenerator.getShadowMap().renderList.length; meshIndex++) {
  16387. var mesh = shadowGenerator.getShadowMap().renderList[meshIndex];
  16388. serializationObject.renderList.push(mesh.id);
  16389. }
  16390. return serializationObject;
  16391. };
  16392. var serializedGeometries = [];
  16393. var serializeGeometry = function (geometry, serializationGeometries) {
  16394. if (serializedGeometries[geometry.id]) {
  16395. return;
  16396. }
  16397. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  16398. serializationGeometries.boxes.push(serializeBox(geometry));
  16399. } else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  16400. serializationGeometries.spheres.push(serializeSphere(geometry));
  16401. } else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  16402. serializationGeometries.cylinders.push(serializeCylinder(geometry));
  16403. } else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  16404. serializationGeometries.toruses.push(serializeTorus(geometry));
  16405. } else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  16406. serializationGeometries.grounds.push(serializeGround(geometry));
  16407. } else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  16408. serializationGeometries.planes.push(serializePlane(geometry));
  16409. } else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  16410. serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
  16411. } else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  16412. throw new Error("Unknow primitive type");
  16413. } else {
  16414. serializationGeometries.vertexData.push(serializeVertexData(geometry));
  16415. }
  16416. serializedGeometries[geometry.id] = true;
  16417. };
  16418. var serializeGeometryBase = function (geometry) {
  16419. var serializationObject = {};
  16420. serializationObject.id = geometry.id;
  16421. if (BABYLON.Tags.HasTags(geometry)) {
  16422. serializationObject.tags = BABYLON.Tags.GetTags(geometry);
  16423. }
  16424. return serializationObject;
  16425. };
  16426. var serializeVertexData = function (vertexData) {
  16427. var serializationObject = serializeGeometryBase(vertexData);
  16428. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  16429. serializationObject.positions = vertexData.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16430. }
  16431. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  16432. serializationObject.normals = vertexData.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16433. }
  16434. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  16435. serializationObject.uvs = vertexData.getVerticesData(BABYLON.VertexBuffer.UVKind);
  16436. }
  16437. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  16438. serializationObject.uvs2 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  16439. }
  16440. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  16441. serializationObject.colors = vertexData.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  16442. }
  16443. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  16444. serializationObject.matricesIndices = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  16445. serializationObject.matricesIndices._isExpanded = true;
  16446. }
  16447. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  16448. serializationObject.matricesWeights = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  16449. }
  16450. serializationObject.indices = vertexData.getIndices();
  16451. return serializationObject;
  16452. };
  16453. var serializePrimitive = function (primitive) {
  16454. var serializationObject = serializeGeometryBase(primitive);
  16455. serializationObject.canBeRegenerated = primitive.canBeRegenerated();
  16456. return serializationObject;
  16457. };
  16458. var serializeBox = function (box) {
  16459. var serializationObject = serializePrimitive(box);
  16460. serializationObject.size = box.size;
  16461. return serializationObject;
  16462. };
  16463. var serializeSphere = function (sphere) {
  16464. var serializationObject = serializePrimitive(sphere);
  16465. serializationObject.segments = sphere.segments;
  16466. serializationObject.diameter = sphere.diameter;
  16467. return serializationObject;
  16468. };
  16469. var serializeCylinder = function (cylinder) {
  16470. var serializationObject = serializePrimitive(cylinder);
  16471. serializationObject.height = cylinder.height;
  16472. serializationObject.diameterTop = cylinder.diameterTop;
  16473. serializationObject.diameterBottom = cylinder.diameterBottom;
  16474. serializationObject.tessellation = cylinder.tessellation;
  16475. return serializationObject;
  16476. };
  16477. var serializeTorus = function (torus) {
  16478. var serializationObject = serializePrimitive(torus);
  16479. serializationObject.diameter = torus.diameter;
  16480. serializationObject.thickness = torus.thickness;
  16481. serializationObject.tessellation = torus.tessellation;
  16482. return serializationObject;
  16483. };
  16484. var serializeGround = function (ground) {
  16485. var serializationObject = serializePrimitive(ground);
  16486. serializationObject.width = ground.width;
  16487. serializationObject.height = ground.height;
  16488. serializationObject.subdivisions = ground.subdivisions;
  16489. return serializationObject;
  16490. };
  16491. var serializePlane = function (plane) {
  16492. var serializationObject = serializePrimitive(plane);
  16493. serializationObject.size = plane.size;
  16494. return serializationObject;
  16495. };
  16496. var serializeTorusKnot = function (torusKnot) {
  16497. var serializationObject = serializePrimitive(torusKnot);
  16498. serializationObject.radius = torusKnot.radius;
  16499. serializationObject.tube = torusKnot.tube;
  16500. serializationObject.radialSegments = torusKnot.radialSegments;
  16501. serializationObject.tubularSegments = torusKnot.tubularSegments;
  16502. serializationObject.p = torusKnot.p;
  16503. serializationObject.q = torusKnot.q;
  16504. return serializationObject;
  16505. };
  16506. var serializeMesh = function (mesh, serializationScene) {
  16507. var serializationObject = {};
  16508. serializationObject.name = mesh.name;
  16509. serializationObject.id = mesh.id;
  16510. if (BABYLON.Tags.HasTags(mesh)) {
  16511. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  16512. }
  16513. serializationObject.position = mesh.position.asArray();
  16514. if (mesh.rotationQuaternion) {
  16515. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  16516. } else if (mesh.rotation) {
  16517. serializationObject.rotation = mesh.rotation.asArray();
  16518. }
  16519. serializationObject.scaling = mesh.scaling.asArray();
  16520. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  16521. serializationObject.isEnabled = mesh.isEnabled();
  16522. serializationObject.isVisible = mesh.isVisible;
  16523. serializationObject.infiniteDistance = mesh.infiniteDistance;
  16524. serializationObject.pickable = mesh.isPickable;
  16525. serializationObject.receiveShadows = mesh.receiveShadows;
  16526. serializationObject.billboardMode = mesh.billboardMode;
  16527. serializationObject.visibility = mesh.visibility;
  16528. serializationObject.checkCollisions = mesh.checkCollisions;
  16529. // Parent
  16530. if (mesh.parent) {
  16531. serializationObject.parentId = mesh.parent.id;
  16532. }
  16533. // Geometry
  16534. var geometry = mesh._geometry;
  16535. if (geometry) {
  16536. var geometryId = geometry.id;
  16537. serializationObject.geometryId = geometryId;
  16538. if (!mesh.getScene().getGeometryByID(geometryId)) {
  16539. // 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
  16540. serializeGeometry(geometry, serializationScene.geometries);
  16541. }
  16542. // SubMeshes
  16543. serializationObject.subMeshes = [];
  16544. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  16545. var subMesh = mesh.subMeshes[subIndex];
  16546. serializationObject.subMeshes.push({
  16547. materialIndex: subMesh.materialIndex,
  16548. verticesStart: subMesh.verticesStart,
  16549. verticesCount: subMesh.verticesCount,
  16550. indexStart: subMesh.indexStart,
  16551. indexCount: subMesh.indexCount
  16552. });
  16553. }
  16554. }
  16555. // Material
  16556. if (mesh.material) {
  16557. serializationObject.materialId = mesh.material.id;
  16558. } else {
  16559. mesh.material = null;
  16560. }
  16561. // Skeleton
  16562. if (mesh.skeleton) {
  16563. serializationObject.skeletonId = mesh.skeleton.id;
  16564. }
  16565. // Physics
  16566. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  16567. serializationObject.physicsMass = mesh.getPhysicsMass();
  16568. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  16569. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  16570. switch (mesh.getPhysicsImpostor()) {
  16571. case BABYLON.PhysicsEngine.BoxImpostor:
  16572. serializationObject.physicsImpostor = 1;
  16573. break;
  16574. case BABYLON.PhysicsEngine.SphereImpostor:
  16575. serializationObject.physicsImpostor = 2;
  16576. break;
  16577. }
  16578. }
  16579. // Instances
  16580. serializationObject.instances = [];
  16581. for (var index = 0; index < mesh.instances.length; index++) {
  16582. var instance = mesh.instances[index];
  16583. var serializationInstance = {
  16584. name: instance.name,
  16585. position: instance.position,
  16586. rotation: instance.rotation,
  16587. rotationQuaternion: instance.rotationQuaternion,
  16588. scaling: instance.scaling
  16589. };
  16590. serializationObject.instances.push(serializationInstance);
  16591. // Animations
  16592. appendAnimations(instance, serializationInstance);
  16593. }
  16594. // Animations
  16595. appendAnimations(mesh, serializationObject);
  16596. // Layer mask
  16597. serializationObject.layerMask = mesh.layerMask;
  16598. return serializationObject;
  16599. };
  16600. var SceneSerializer = (function () {
  16601. function SceneSerializer() {
  16602. }
  16603. SceneSerializer.Serialize = function (scene) {
  16604. var serializationObject = {};
  16605. // Scene
  16606. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  16607. serializationObject.autoClear = scene.autoClear;
  16608. serializationObject.clearColor = scene.clearColor.asArray();
  16609. serializationObject.ambientColor = scene.ambientColor.asArray();
  16610. serializationObject.gravity = scene.gravity.asArray();
  16611. // Fog
  16612. if (scene.fogMode && scene.fogMode !== 0) {
  16613. serializationObject.fogMode = scene.fogMode;
  16614. serializationObject.fogColor = scene.fogColor.asArray();
  16615. serializationObject.fogStart = scene.fogStart;
  16616. serializationObject.fogEnd = scene.fogEnd;
  16617. serializationObject.fogDensity = scene.fogDensity;
  16618. }
  16619. // Lights
  16620. serializationObject.lights = [];
  16621. for (var index = 0; index < scene.lights.length; index++) {
  16622. var light = scene.lights[index];
  16623. serializationObject.lights.push(serializeLight(light));
  16624. }
  16625. // Cameras
  16626. serializationObject.cameras = [];
  16627. for (index = 0; index < scene.cameras.length; index++) {
  16628. var camera = scene.cameras[index];
  16629. if (camera instanceof BABYLON.FreeCamera) {
  16630. serializationObject.cameras.push(serializeCamera(camera));
  16631. }
  16632. }
  16633. if (scene.activeCamera) {
  16634. serializationObject.activeCameraID = scene.activeCamera.id;
  16635. }
  16636. // Materials
  16637. serializationObject.materials = [];
  16638. serializationObject.multiMaterials = [];
  16639. for (index = 0; index < scene.materials.length; index++) {
  16640. var material = scene.materials[index];
  16641. if (material instanceof BABYLON.StandardMaterial) {
  16642. serializationObject.materials.push(serializeMaterial(material));
  16643. } else if (material instanceof BABYLON.MultiMaterial) {
  16644. serializationObject.multiMaterials.push(serializeMultiMaterial(material));
  16645. }
  16646. }
  16647. // Skeletons
  16648. serializationObject.skeletons = [];
  16649. for (index = 0; index < scene.skeletons.length; index++) {
  16650. serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
  16651. }
  16652. // Geometries
  16653. serializationObject.geometries = {};
  16654. serializationObject.geometries.boxes = [];
  16655. serializationObject.geometries.spheres = [];
  16656. serializationObject.geometries.cylinders = [];
  16657. serializationObject.geometries.toruses = [];
  16658. serializationObject.geometries.grounds = [];
  16659. serializationObject.geometries.planes = [];
  16660. serializationObject.geometries.torusKnots = [];
  16661. serializationObject.geometries.vertexData = [];
  16662. serializedGeometries = [];
  16663. var geometries = scene.getGeometries();
  16664. for (var index = 0; index < geometries.length; index++) {
  16665. var geometry = geometries[index];
  16666. if (geometry.isReady()) {
  16667. serializeGeometry(geometry, serializationObject.geometries);
  16668. }
  16669. }
  16670. // Meshes
  16671. serializationObject.meshes = [];
  16672. for (index = 0; index < scene.meshes.length; index++) {
  16673. var abstractMesh = scene.meshes[index];
  16674. if (abstractMesh instanceof BABYLON.Mesh) {
  16675. var mesh = abstractMesh;
  16676. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  16677. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  16678. }
  16679. }
  16680. }
  16681. // Particles Systems
  16682. serializationObject.particleSystems = [];
  16683. for (index = 0; index < scene.particleSystems.length; index++) {
  16684. serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
  16685. }
  16686. // Lens flares
  16687. serializationObject.lensFlareSystems = [];
  16688. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  16689. serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
  16690. }
  16691. // Shadows
  16692. serializationObject.shadowGenerators = [];
  16693. for (index = 0; index < scene.lights.length; index++) {
  16694. light = scene.lights[index];
  16695. if (light.getShadowGenerator()) {
  16696. serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
  16697. }
  16698. }
  16699. return serializationObject;
  16700. };
  16701. return SceneSerializer;
  16702. })();
  16703. BABYLON.SceneSerializer = SceneSerializer;
  16704. })(BABYLON || (BABYLON = {}));
  16705. //# sourceMappingURL=babylon.sceneSerializer.js.map
  16706. var BABYLON;
  16707. (function (BABYLON) {
  16708. var SceneLoader = (function () {
  16709. function SceneLoader() {
  16710. }
  16711. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  16712. get: function () {
  16713. return SceneLoader._ForceFullSceneLoadingForIncremental;
  16714. },
  16715. set: function (value) {
  16716. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  16717. },
  16718. enumerable: true,
  16719. configurable: true
  16720. });
  16721. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  16722. get: function () {
  16723. return SceneLoader._ShowLoadingScreen;
  16724. },
  16725. set: function (value) {
  16726. SceneLoader._ShowLoadingScreen = value;
  16727. },
  16728. enumerable: true,
  16729. configurable: true
  16730. });
  16731. SceneLoader._getPluginForFilename = function (sceneFilename) {
  16732. var dotPosition = sceneFilename.lastIndexOf(".");
  16733. var queryStringPosition = sceneFilename.indexOf("?");
  16734. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  16735. for (var index = 0; index < this._registeredPlugins.length; index++) {
  16736. var plugin = this._registeredPlugins[index];
  16737. if (plugin.extensions.indexOf(extension) !== -1) {
  16738. return plugin;
  16739. }
  16740. }
  16741. return this._registeredPlugins[this._registeredPlugins.length - 1];
  16742. };
  16743. // Public functions
  16744. SceneLoader.RegisterPlugin = function (plugin) {
  16745. plugin.extensions = plugin.extensions.toLowerCase();
  16746. SceneLoader._registeredPlugins.push(plugin);
  16747. };
  16748. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  16749. var manifestChecked = function (success) {
  16750. scene.database = database;
  16751. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  16752. var importMeshFromData = function (data) {
  16753. var meshes = [];
  16754. var particleSystems = [];
  16755. var skeletons = [];
  16756. try {
  16757. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  16758. if (onerror) {
  16759. onerror(scene, 'unable to load the scene');
  16760. }
  16761. return;
  16762. }
  16763. } catch (e) {
  16764. if (onerror) {
  16765. onerror(scene, e);
  16766. }
  16767. return;
  16768. }
  16769. if (onsuccess) {
  16770. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  16771. onsuccess(meshes, particleSystems, skeletons);
  16772. }
  16773. };
  16774. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  16775. // Direct load
  16776. importMeshFromData(sceneFilename.substr(5));
  16777. return;
  16778. }
  16779. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  16780. importMeshFromData(data);
  16781. }, progressCallBack, database);
  16782. };
  16783. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  16784. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  16785. };
  16786. /**
  16787. * Load a scene
  16788. * @param rootUrl a string that defines the root url for scene and resources
  16789. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  16790. * @param engine is the instance of BABYLON.Engine to use to create the scene
  16791. */
  16792. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  16793. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  16794. };
  16795. /**
  16796. * Append a scene
  16797. * @param rootUrl a string that defines the root url for scene and resources
  16798. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  16799. * @param scene is the instance of BABYLON.Scene to append to
  16800. */
  16801. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  16802. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  16803. var database;
  16804. if (SceneLoader.ShowLoadingScreen) {
  16805. scene.getEngine().displayLoadingUI();
  16806. }
  16807. var loadSceneFromData = function (data) {
  16808. scene.database = database;
  16809. if (!plugin.load(scene, data, rootUrl)) {
  16810. if (onerror) {
  16811. onerror(scene);
  16812. }
  16813. scene.getEngine().hideLoadingUI();
  16814. return;
  16815. }
  16816. if (onsuccess) {
  16817. onsuccess(scene);
  16818. }
  16819. if (SceneLoader.ShowLoadingScreen) {
  16820. scene.executeWhenReady(function () {
  16821. scene.getEngine().hideLoadingUI();
  16822. });
  16823. }
  16824. };
  16825. var manifestChecked = function (success) {
  16826. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  16827. };
  16828. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  16829. // Direct load
  16830. loadSceneFromData(sceneFilename.substr(5));
  16831. return;
  16832. }
  16833. if (rootUrl.indexOf("file:") === -1) {
  16834. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  16835. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  16836. } else {
  16837. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  16838. }
  16839. };
  16840. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  16841. SceneLoader._ShowLoadingScreen = true;
  16842. SceneLoader._registeredPlugins = new Array();
  16843. return SceneLoader;
  16844. })();
  16845. BABYLON.SceneLoader = SceneLoader;
  16846. ;
  16847. })(BABYLON || (BABYLON = {}));
  16848. //# sourceMappingURL=babylon.sceneLoader.js.map
  16849. var BABYLON;
  16850. (function (BABYLON) {
  16851. (function (Internals) {
  16852. var checkColors4 = function (colors, count) {
  16853. // Check if color3 was used
  16854. if (colors.length === count * 3) {
  16855. var colors4 = [];
  16856. for (var index = 0; index < colors.length; index += 3) {
  16857. var newIndex = (index / 3) * 4;
  16858. colors4[newIndex] = colors[index];
  16859. colors4[newIndex + 1] = colors[index + 1];
  16860. colors4[newIndex + 2] = colors[index + 2];
  16861. colors4[newIndex + 3] = 1.0;
  16862. }
  16863. return colors4;
  16864. }
  16865. return colors;
  16866. };
  16867. var loadCubeTexture = function (rootUrl, parsedTexture, scene) {
  16868. var texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene);
  16869. texture.name = parsedTexture.name;
  16870. texture.hasAlpha = parsedTexture.hasAlpha;
  16871. texture.level = parsedTexture.level;
  16872. texture.coordinatesMode = parsedTexture.coordinatesMode;
  16873. return texture;
  16874. };
  16875. var loadTexture = function (rootUrl, parsedTexture, scene) {
  16876. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  16877. return null;
  16878. }
  16879. if (parsedTexture.isCube) {
  16880. return loadCubeTexture(rootUrl, parsedTexture, scene);
  16881. }
  16882. var texture;
  16883. if (parsedTexture.mirrorPlane) {
  16884. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  16885. texture._waitingRenderList = parsedTexture.renderList;
  16886. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  16887. } else if (parsedTexture.isRenderTarget) {
  16888. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  16889. texture._waitingRenderList = parsedTexture.renderList;
  16890. } else {
  16891. texture = new BABYLON.Texture(rootUrl + parsedTexture.name, scene);
  16892. }
  16893. texture.name = parsedTexture.name;
  16894. texture.hasAlpha = parsedTexture.hasAlpha;
  16895. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  16896. texture.level = parsedTexture.level;
  16897. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  16898. texture.coordinatesMode = parsedTexture.coordinatesMode;
  16899. texture.uOffset = parsedTexture.uOffset;
  16900. texture.vOffset = parsedTexture.vOffset;
  16901. texture.uScale = parsedTexture.uScale;
  16902. texture.vScale = parsedTexture.vScale;
  16903. texture.uAng = parsedTexture.uAng;
  16904. texture.vAng = parsedTexture.vAng;
  16905. texture.wAng = parsedTexture.wAng;
  16906. texture.wrapU = parsedTexture.wrapU;
  16907. texture.wrapV = parsedTexture.wrapV;
  16908. // Animations
  16909. if (parsedTexture.animations) {
  16910. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  16911. var parsedAnimation = parsedTexture.animations[animationIndex];
  16912. texture.animations.push(parseAnimation(parsedAnimation));
  16913. }
  16914. }
  16915. return texture;
  16916. };
  16917. var parseSkeleton = function (parsedSkeleton, scene) {
  16918. var skeleton = new BABYLON.Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  16919. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  16920. var parsedBone = parsedSkeleton.bones[index];
  16921. var parentBone = null;
  16922. if (parsedBone.parentBoneIndex > -1) {
  16923. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  16924. }
  16925. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  16926. if (parsedBone.animation) {
  16927. bone.animations.push(parseAnimation(parsedBone.animation));
  16928. }
  16929. }
  16930. return skeleton;
  16931. };
  16932. var parseFresnelParameters = function (parsedFresnelParameters) {
  16933. var fresnelParameters = new BABYLON.FresnelParameters();
  16934. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  16935. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  16936. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  16937. fresnelParameters.bias = parsedFresnelParameters.bias;
  16938. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  16939. return fresnelParameters;
  16940. };
  16941. var parseMaterial = function (parsedMaterial, scene, rootUrl) {
  16942. var material;
  16943. material = new BABYLON.StandardMaterial(parsedMaterial.name, scene);
  16944. material.ambientColor = BABYLON.Color3.FromArray(parsedMaterial.ambient);
  16945. material.diffuseColor = BABYLON.Color3.FromArray(parsedMaterial.diffuse);
  16946. material.specularColor = BABYLON.Color3.FromArray(parsedMaterial.specular);
  16947. material.specularPower = parsedMaterial.specularPower;
  16948. material.emissiveColor = BABYLON.Color3.FromArray(parsedMaterial.emissive);
  16949. material.alpha = parsedMaterial.alpha;
  16950. material.id = parsedMaterial.id;
  16951. BABYLON.Tags.AddTagsTo(material, parsedMaterial.tags);
  16952. material.backFaceCulling = parsedMaterial.backFaceCulling;
  16953. material.wireframe = parsedMaterial.wireframe;
  16954. if (parsedMaterial.diffuseTexture) {
  16955. material.diffuseTexture = loadTexture(rootUrl, parsedMaterial.diffuseTexture, scene);
  16956. }
  16957. if (parsedMaterial.diffuseFresnelParameters) {
  16958. material.diffuseFresnelParameters = parseFresnelParameters(parsedMaterial.diffuseFresnelParameters);
  16959. }
  16960. if (parsedMaterial.ambientTexture) {
  16961. material.ambientTexture = loadTexture(rootUrl, parsedMaterial.ambientTexture, scene);
  16962. }
  16963. if (parsedMaterial.opacityTexture) {
  16964. material.opacityTexture = loadTexture(rootUrl, parsedMaterial.opacityTexture, scene);
  16965. }
  16966. if (parsedMaterial.opacityFresnelParameters) {
  16967. material.opacityFresnelParameters = parseFresnelParameters(parsedMaterial.opacityFresnelParameters);
  16968. }
  16969. if (parsedMaterial.reflectionTexture) {
  16970. material.reflectionTexture = loadTexture(rootUrl, parsedMaterial.reflectionTexture, scene);
  16971. }
  16972. if (parsedMaterial.reflectionFresnelParameters) {
  16973. material.reflectionFresnelParameters = parseFresnelParameters(parsedMaterial.reflectionFresnelParameters);
  16974. }
  16975. if (parsedMaterial.emissiveTexture) {
  16976. material.emissiveTexture = loadTexture(rootUrl, parsedMaterial.emissiveTexture, scene);
  16977. }
  16978. if (parsedMaterial.emissiveFresnelParameters) {
  16979. material.emissiveFresnelParameters = parseFresnelParameters(parsedMaterial.emissiveFresnelParameters);
  16980. }
  16981. if (parsedMaterial.specularTexture) {
  16982. material.specularTexture = loadTexture(rootUrl, parsedMaterial.specularTexture, scene);
  16983. }
  16984. if (parsedMaterial.bumpTexture) {
  16985. material.bumpTexture = loadTexture(rootUrl, parsedMaterial.bumpTexture, scene);
  16986. }
  16987. return material;
  16988. };
  16989. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  16990. for (var index = 0; index < parsedData.materials.length; index++) {
  16991. var parsedMaterial = parsedData.materials[index];
  16992. if (parsedMaterial.id === id) {
  16993. return parseMaterial(parsedMaterial, scene, rootUrl);
  16994. }
  16995. }
  16996. return null;
  16997. };
  16998. var parseMultiMaterial = function (parsedMultiMaterial, scene) {
  16999. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  17000. multiMaterial.id = parsedMultiMaterial.id;
  17001. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  17002. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  17003. var subMatId = parsedMultiMaterial.materials[matIndex];
  17004. if (subMatId) {
  17005. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  17006. } else {
  17007. multiMaterial.subMaterials.push(null);
  17008. }
  17009. }
  17010. return multiMaterial;
  17011. };
  17012. var parseLensFlareSystem = function (parsedLensFlareSystem, scene, rootUrl) {
  17013. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  17014. var lensFlareSystem = new BABYLON.LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  17015. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  17016. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  17017. var parsedFlare = parsedLensFlareSystem.flares[index];
  17018. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  17019. }
  17020. return lensFlareSystem;
  17021. };
  17022. var parseParticleSystem = function (parsedParticleSystem, scene, rootUrl) {
  17023. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  17024. var particleSystem = new BABYLON.ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  17025. if (parsedParticleSystem.textureName) {
  17026. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  17027. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  17028. }
  17029. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  17030. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  17031. particleSystem.minSize = parsedParticleSystem.minSize;
  17032. particleSystem.maxSize = parsedParticleSystem.maxSize;
  17033. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  17034. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  17035. particleSystem.emitter = emitter;
  17036. particleSystem.emitRate = parsedParticleSystem.emitRate;
  17037. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  17038. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  17039. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  17040. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  17041. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  17042. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  17043. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  17044. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  17045. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  17046. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  17047. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  17048. particleSystem.blendMode = parsedParticleSystem.blendMode;
  17049. particleSystem.start();
  17050. return particleSystem;
  17051. };
  17052. var parseShadowGenerator = function (parsedShadowGenerator, scene) {
  17053. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  17054. var shadowGenerator = new BABYLON.ShadowGenerator(parsedShadowGenerator.mapSize, light);
  17055. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  17056. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  17057. shadowGenerator.getShadowMap().renderList.push(mesh);
  17058. }
  17059. if (parsedShadowGenerator.usePoissonSampling) {
  17060. shadowGenerator.usePoissonSampling = true;
  17061. } else {
  17062. shadowGenerator.useVarianceShadowMap = parsedShadowGenerator.useVarianceShadowMap;
  17063. }
  17064. return shadowGenerator;
  17065. };
  17066. var parseAnimation = function (parsedAnimation) {
  17067. var animation = new BABYLON.Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  17068. var dataType = parsedAnimation.dataType;
  17069. var keys = [];
  17070. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  17071. var key = parsedAnimation.keys[index];
  17072. var data;
  17073. switch (dataType) {
  17074. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  17075. data = key.values[0];
  17076. break;
  17077. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  17078. data = BABYLON.Quaternion.FromArray(key.values);
  17079. break;
  17080. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  17081. data = BABYLON.Matrix.FromArray(key.values);
  17082. break;
  17083. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  17084. default:
  17085. data = BABYLON.Vector3.FromArray(key.values);
  17086. break;
  17087. }
  17088. keys.push({
  17089. frame: key.frame,
  17090. value: data
  17091. });
  17092. }
  17093. animation.setKeys(keys);
  17094. return animation;
  17095. };
  17096. var parseLight = function (parsedLight, scene) {
  17097. var light;
  17098. switch (parsedLight.type) {
  17099. case 0:
  17100. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  17101. break;
  17102. case 1:
  17103. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  17104. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  17105. break;
  17106. case 2:
  17107. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  17108. break;
  17109. case 3:
  17110. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  17111. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  17112. break;
  17113. }
  17114. light.id = parsedLight.id;
  17115. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  17116. if (parsedLight.intensity !== undefined) {
  17117. light.intensity = parsedLight.intensity;
  17118. }
  17119. if (parsedLight.range) {
  17120. light.range = parsedLight.range;
  17121. }
  17122. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  17123. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  17124. if (parsedLight.excludedMeshesIds) {
  17125. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  17126. }
  17127. // Parent
  17128. if (parsedLight.parentId) {
  17129. light._waitingParentId = parsedLight.parentId;
  17130. }
  17131. if (parsedLight.includedOnlyMeshesIds) {
  17132. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  17133. }
  17134. // Animations
  17135. if (parsedLight.animations) {
  17136. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  17137. var parsedAnimation = parsedLight.animations[animationIndex];
  17138. light.animations.push(parseAnimation(parsedAnimation));
  17139. }
  17140. }
  17141. if (parsedLight.autoAnimate) {
  17142. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  17143. }
  17144. };
  17145. var parseCamera = function (parsedCamera, scene) {
  17146. var camera;
  17147. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  17148. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  17149. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  17150. var alpha = parsedCamera.alpha;
  17151. var beta = parsedCamera.beta;
  17152. var radius = parsedCamera.radius;
  17153. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  17154. var eye_space = parsedCamera.eye_space;
  17155. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, eye_space, scene);
  17156. } else {
  17157. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  17158. }
  17159. } else if (parsedCamera.type === "AnaglyphFreeCamera") {
  17160. var eye_space = parsedCamera.eye_space;
  17161. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, eye_space, scene);
  17162. } else if (parsedCamera.type === "DeviceOrientationCamera") {
  17163. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  17164. } else if (parsedCamera.type === "FollowCamera") {
  17165. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  17166. camera.heightOffset = parsedCamera.heightOffset;
  17167. camera.radius = parsedCamera.radius;
  17168. camera.rotationOffset = parsedCamera.rotationOffset;
  17169. if (lockedTargetMesh)
  17170. camera.target = lockedTargetMesh;
  17171. } else if (parsedCamera.type === "GamepadCamera") {
  17172. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  17173. } else if (parsedCamera.type === "OculusCamera") {
  17174. camera = new BABYLON.OculusCamera(parsedCamera.name, position, scene);
  17175. } else if (parsedCamera.type === "OculusGamepadCamera") {
  17176. camera = new BABYLON.OculusGamepadCamera(parsedCamera.name, position, scene);
  17177. } else if (parsedCamera.type === "TouchCamera") {
  17178. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  17179. } else if (parsedCamera.type === "VirtualJoysticksCamera") {
  17180. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  17181. } else if (parsedCamera.type === "WebVRCamera") {
  17182. camera = new BABYLON.WebVRCamera(parsedCamera.name, position, scene);
  17183. } else if (parsedCamera.type === "VRDeviceOrientationCamera") {
  17184. camera = new BABYLON.VRDeviceOrientationCamera(parsedCamera.name, position, scene);
  17185. } else {
  17186. // Free Camera is the default value
  17187. camera = new BABYLON.FreeCamera(parsedCamera.name, position, scene);
  17188. }
  17189. // Test for lockedTargetMesh & FreeCamera outside of if-else-if nest, since things like GamepadCamera extend FreeCamera
  17190. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  17191. camera.lockedTarget = lockedTargetMesh;
  17192. }
  17193. camera.id = parsedCamera.id;
  17194. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  17195. // Parent
  17196. if (parsedCamera.parentId) {
  17197. camera._waitingParentId = parsedCamera.parentId;
  17198. }
  17199. // Target
  17200. if (parsedCamera.target) {
  17201. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  17202. } else {
  17203. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  17204. }
  17205. camera.fov = parsedCamera.fov;
  17206. camera.minZ = parsedCamera.minZ;
  17207. camera.maxZ = parsedCamera.maxZ;
  17208. camera.speed = parsedCamera.speed;
  17209. camera.inertia = parsedCamera.inertia;
  17210. camera.checkCollisions = parsedCamera.checkCollisions;
  17211. camera.applyGravity = parsedCamera.applyGravity;
  17212. if (parsedCamera.ellipsoid) {
  17213. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  17214. }
  17215. // Animations
  17216. if (parsedCamera.animations) {
  17217. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  17218. var parsedAnimation = parsedCamera.animations[animationIndex];
  17219. camera.animations.push(parseAnimation(parsedAnimation));
  17220. }
  17221. }
  17222. if (parsedCamera.autoAnimate) {
  17223. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  17224. }
  17225. // Layer Mask
  17226. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  17227. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  17228. } else {
  17229. camera.layerMask = 0xFFFFFFFF;
  17230. }
  17231. return camera;
  17232. };
  17233. var parseGeometry = function (parsedGeometry, scene) {
  17234. var id = parsedGeometry.id;
  17235. return scene.getGeometryByID(id);
  17236. };
  17237. var parseBox = function (parsedBox, scene) {
  17238. if (parseGeometry(parsedBox, scene)) {
  17239. return null;
  17240. }
  17241. var box = new BABYLON.Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  17242. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  17243. scene.pushGeometry(box, true);
  17244. return box;
  17245. };
  17246. var parseSphere = function (parsedSphere, scene) {
  17247. if (parseGeometry(parsedSphere, scene)) {
  17248. return null;
  17249. }
  17250. var sphere = new BABYLON.Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  17251. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  17252. scene.pushGeometry(sphere, true);
  17253. return sphere;
  17254. };
  17255. var parseCylinder = function (parsedCylinder, scene) {
  17256. if (parseGeometry(parsedCylinder, scene)) {
  17257. return null;
  17258. }
  17259. var cylinder = new BABYLON.Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  17260. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  17261. scene.pushGeometry(cylinder, true);
  17262. return cylinder;
  17263. };
  17264. var parseTorus = function (parsedTorus, scene) {
  17265. if (parseGeometry(parsedTorus, scene)) {
  17266. return null;
  17267. }
  17268. var torus = new BABYLON.Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  17269. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  17270. scene.pushGeometry(torus, true);
  17271. return torus;
  17272. };
  17273. var parseGround = function (parsedGround, scene) {
  17274. if (parseGeometry(parsedGround, scene)) {
  17275. return null;
  17276. }
  17277. var ground = new BABYLON.Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  17278. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  17279. scene.pushGeometry(ground, true);
  17280. return ground;
  17281. };
  17282. var parsePlane = function (parsedPlane, scene) {
  17283. if (parseGeometry(parsedPlane, scene)) {
  17284. return null;
  17285. }
  17286. var plane = new BABYLON.Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  17287. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  17288. scene.pushGeometry(plane, true);
  17289. return plane;
  17290. };
  17291. var parseTorusKnot = function (parsedTorusKnot, scene) {
  17292. if (parseGeometry(parsedTorusKnot, scene)) {
  17293. return null;
  17294. }
  17295. 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);
  17296. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  17297. scene.pushGeometry(torusKnot, true);
  17298. return torusKnot;
  17299. };
  17300. var parseVertexData = function (parsedVertexData, scene, rootUrl) {
  17301. if (parseGeometry(parsedVertexData, scene)) {
  17302. return null;
  17303. }
  17304. var geometry = new BABYLON.Geometry(parsedVertexData.id, scene);
  17305. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  17306. if (parsedVertexData.delayLoadingFile) {
  17307. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  17308. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  17309. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  17310. geometry._delayInfo = [];
  17311. if (parsedVertexData.hasUVs) {
  17312. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  17313. }
  17314. if (parsedVertexData.hasUVs2) {
  17315. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  17316. }
  17317. if (parsedVertexData.hasColors) {
  17318. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  17319. }
  17320. if (parsedVertexData.hasMatricesIndices) {
  17321. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  17322. }
  17323. if (parsedVertexData.hasMatricesWeights) {
  17324. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  17325. }
  17326. geometry._delayLoadingFunction = importVertexData;
  17327. } else {
  17328. importVertexData(parsedVertexData, geometry);
  17329. }
  17330. scene.pushGeometry(geometry, true);
  17331. return geometry;
  17332. };
  17333. var parseMesh = function (parsedMesh, scene, rootUrl) {
  17334. var mesh = new BABYLON.Mesh(parsedMesh.name, scene);
  17335. mesh.id = parsedMesh.id;
  17336. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  17337. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  17338. if (parsedMesh.rotationQuaternion) {
  17339. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  17340. } else if (parsedMesh.rotation) {
  17341. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  17342. }
  17343. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  17344. if (parsedMesh.localMatrix) {
  17345. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  17346. } else if (parsedMesh.pivotMatrix) {
  17347. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  17348. }
  17349. mesh.setEnabled(parsedMesh.isEnabled);
  17350. mesh.isVisible = parsedMesh.isVisible;
  17351. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  17352. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  17353. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  17354. if (parsedMesh.applyFog !== undefined) {
  17355. mesh.applyFog = parsedMesh.applyFog;
  17356. }
  17357. if (parsedMesh.pickable !== undefined) {
  17358. mesh.isPickable = parsedMesh.pickable;
  17359. }
  17360. if (parsedMesh.alphaIndex !== undefined) {
  17361. mesh.alphaIndex = parsedMesh.alphaIndex;
  17362. }
  17363. mesh.receiveShadows = parsedMesh.receiveShadows;
  17364. mesh.billboardMode = parsedMesh.billboardMode;
  17365. if (parsedMesh.visibility !== undefined) {
  17366. mesh.visibility = parsedMesh.visibility;
  17367. }
  17368. mesh.checkCollisions = parsedMesh.checkCollisions;
  17369. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  17370. // Parent
  17371. if (parsedMesh.parentId) {
  17372. mesh._waitingParentId = parsedMesh.parentId;
  17373. }
  17374. // Geometry
  17375. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  17376. if (parsedMesh.delayLoadingFile) {
  17377. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  17378. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  17379. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  17380. if (parsedMesh._binaryInfo) {
  17381. mesh._binaryInfo = parsedMesh._binaryInfo;
  17382. }
  17383. mesh._delayInfo = [];
  17384. if (parsedMesh.hasUVs) {
  17385. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  17386. }
  17387. if (parsedMesh.hasUVs2) {
  17388. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  17389. }
  17390. if (parsedMesh.hasColors) {
  17391. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  17392. }
  17393. if (parsedMesh.hasMatricesIndices) {
  17394. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  17395. }
  17396. if (parsedMesh.hasMatricesWeights) {
  17397. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  17398. }
  17399. mesh._delayLoadingFunction = importGeometry;
  17400. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  17401. mesh._checkDelayState();
  17402. }
  17403. } else {
  17404. importGeometry(parsedMesh, mesh);
  17405. }
  17406. // Material
  17407. if (parsedMesh.materialId) {
  17408. mesh.setMaterialByID(parsedMesh.materialId);
  17409. } else {
  17410. mesh.material = null;
  17411. }
  17412. // Skeleton
  17413. if (parsedMesh.skeletonId > -1) {
  17414. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  17415. }
  17416. // Physics
  17417. if (parsedMesh.physicsImpostor) {
  17418. if (!scene.isPhysicsEnabled()) {
  17419. scene.enablePhysics();
  17420. }
  17421. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  17422. }
  17423. // Animations
  17424. if (parsedMesh.animations) {
  17425. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  17426. var parsedAnimation = parsedMesh.animations[animationIndex];
  17427. mesh.animations.push(parseAnimation(parsedAnimation));
  17428. }
  17429. }
  17430. if (parsedMesh.autoAnimate) {
  17431. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  17432. }
  17433. // Layer Mask
  17434. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  17435. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  17436. } else {
  17437. mesh.layerMask = 0xFFFFFFFF;
  17438. }
  17439. // Instances
  17440. if (parsedMesh.instances) {
  17441. for (var index = 0; index < parsedMesh.instances.length; index++) {
  17442. var parsedInstance = parsedMesh.instances[index];
  17443. var instance = mesh.createInstance(parsedInstance.name);
  17444. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  17445. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  17446. if (parsedInstance.rotationQuaternion) {
  17447. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  17448. } else if (parsedInstance.rotation) {
  17449. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  17450. }
  17451. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  17452. instance.checkCollisions = mesh.checkCollisions;
  17453. if (parsedMesh.animations) {
  17454. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  17455. parsedAnimation = parsedMesh.animations[animationIndex];
  17456. instance.animations.push(parseAnimation(parsedAnimation));
  17457. }
  17458. }
  17459. }
  17460. }
  17461. return mesh;
  17462. };
  17463. var isDescendantOf = function (mesh, names, hierarchyIds) {
  17464. names = (names instanceof Array) ? names : [names];
  17465. for (var i in names) {
  17466. if (mesh.name === names[i]) {
  17467. hierarchyIds.push(mesh.id);
  17468. return true;
  17469. }
  17470. }
  17471. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  17472. hierarchyIds.push(mesh.id);
  17473. return true;
  17474. }
  17475. return false;
  17476. };
  17477. var importVertexData = function (parsedVertexData, geometry) {
  17478. var vertexData = new BABYLON.VertexData();
  17479. // positions
  17480. var positions = parsedVertexData.positions;
  17481. if (positions) {
  17482. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  17483. }
  17484. // normals
  17485. var normals = parsedVertexData.normals;
  17486. if (normals) {
  17487. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  17488. }
  17489. // uvs
  17490. var uvs = parsedVertexData.uvs;
  17491. if (uvs) {
  17492. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  17493. }
  17494. // uv2s
  17495. var uv2s = parsedVertexData.uv2s;
  17496. if (uv2s) {
  17497. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  17498. }
  17499. // colors
  17500. var colors = parsedVertexData.colors;
  17501. if (colors) {
  17502. vertexData.set(checkColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  17503. }
  17504. // matricesIndices
  17505. var matricesIndices = parsedVertexData.matricesIndices;
  17506. if (matricesIndices) {
  17507. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  17508. }
  17509. // matricesWeights
  17510. var matricesWeights = parsedVertexData.matricesWeights;
  17511. if (matricesWeights) {
  17512. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  17513. }
  17514. // indices
  17515. var indices = parsedVertexData.indices;
  17516. if (indices) {
  17517. vertexData.indices = indices;
  17518. }
  17519. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  17520. };
  17521. var importGeometry = function (parsedGeometry, mesh) {
  17522. var scene = mesh.getScene();
  17523. // Geometry
  17524. var geometryId = parsedGeometry.geometryId;
  17525. if (geometryId) {
  17526. var geometry = scene.getGeometryByID(geometryId);
  17527. if (geometry) {
  17528. geometry.applyToMesh(mesh);
  17529. }
  17530. } else if (parsedGeometry instanceof ArrayBuffer) {
  17531. var binaryInfo = mesh._binaryInfo;
  17532. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  17533. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  17534. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  17535. }
  17536. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  17537. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  17538. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  17539. }
  17540. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  17541. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  17542. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  17543. }
  17544. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  17545. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  17546. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  17547. }
  17548. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  17549. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  17550. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false);
  17551. }
  17552. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  17553. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  17554. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  17555. }
  17556. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  17557. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  17558. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  17559. }
  17560. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  17561. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  17562. mesh.setIndices(indicesData);
  17563. }
  17564. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  17565. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  17566. mesh.subMeshes = [];
  17567. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  17568. var materialIndex = subMeshesData[(i * 5) + 0];
  17569. var verticesStart = subMeshesData[(i * 5) + 1];
  17570. var verticesCount = subMeshesData[(i * 5) + 2];
  17571. var indexStart = subMeshesData[(i * 5) + 3];
  17572. var indexCount = subMeshesData[(i * 5) + 4];
  17573. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  17574. }
  17575. }
  17576. } else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  17577. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  17578. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  17579. if (parsedGeometry.uvs) {
  17580. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  17581. }
  17582. if (parsedGeometry.uvs2) {
  17583. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  17584. }
  17585. if (parsedGeometry.colors) {
  17586. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, checkColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  17587. }
  17588. if (parsedGeometry.matricesIndices) {
  17589. if (!parsedGeometry.matricesIndices._isExpanded) {
  17590. var floatIndices = [];
  17591. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  17592. var matricesIndex = parsedGeometry.matricesIndices[i];
  17593. floatIndices.push(matricesIndex & 0x000000FF);
  17594. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  17595. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  17596. floatIndices.push(matricesIndex >> 24);
  17597. }
  17598. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  17599. } else {
  17600. delete parsedGeometry.matricesIndices._isExpanded;
  17601. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  17602. }
  17603. }
  17604. if (parsedGeometry.matricesWeights) {
  17605. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  17606. }
  17607. mesh.setIndices(parsedGeometry.indices);
  17608. // SubMeshes
  17609. if (parsedGeometry.subMeshes) {
  17610. mesh.subMeshes = [];
  17611. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  17612. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  17613. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  17614. }
  17615. }
  17616. }
  17617. // Flat shading
  17618. if (mesh._shouldGenerateFlatShading) {
  17619. mesh.convertToFlatShadedMesh();
  17620. delete mesh._shouldGenerateFlatShading;
  17621. }
  17622. // Update
  17623. mesh.computeWorldMatrix(true);
  17624. // Octree
  17625. if (scene._selectionOctree) {
  17626. scene._selectionOctree.addMesh(mesh);
  17627. }
  17628. };
  17629. BABYLON.SceneLoader.RegisterPlugin({
  17630. extensions: ".babylon",
  17631. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  17632. var parsedData = JSON.parse(data);
  17633. var loadedSkeletonsIds = [];
  17634. var loadedMaterialsIds = [];
  17635. var hierarchyIds = [];
  17636. for (var index = 0; index < parsedData.meshes.length; index++) {
  17637. var parsedMesh = parsedData.meshes[index];
  17638. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  17639. if (meshesNames instanceof Array) {
  17640. // Remove found mesh name from list.
  17641. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  17642. }
  17643. // Material ?
  17644. if (parsedMesh.materialId) {
  17645. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  17646. if (!materialFound) {
  17647. for (var multimatIndex = 0; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
  17648. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  17649. if (parsedMultiMaterial.id == parsedMesh.materialId) {
  17650. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  17651. var subMatId = parsedMultiMaterial.materials[matIndex];
  17652. loadedMaterialsIds.push(subMatId);
  17653. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  17654. }
  17655. loadedMaterialsIds.push(parsedMultiMaterial.id);
  17656. parseMultiMaterial(parsedMultiMaterial, scene);
  17657. materialFound = true;
  17658. break;
  17659. }
  17660. }
  17661. }
  17662. if (!materialFound) {
  17663. loadedMaterialsIds.push(parsedMesh.materialId);
  17664. parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  17665. }
  17666. }
  17667. // Skeleton ?
  17668. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  17669. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  17670. if (!skeletonAlreadyLoaded) {
  17671. for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
  17672. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  17673. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  17674. skeletons.push(parseSkeleton(parsedSkeleton, scene));
  17675. loadedSkeletonsIds.push(parsedSkeleton.id);
  17676. }
  17677. }
  17678. }
  17679. }
  17680. var mesh = parseMesh(parsedMesh, scene, rootUrl);
  17681. meshes.push(mesh);
  17682. }
  17683. }
  17684. for (index = 0; index < scene.meshes.length; index++) {
  17685. var currentMesh = scene.meshes[index];
  17686. if (currentMesh._waitingParentId) {
  17687. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  17688. currentMesh._waitingParentId = undefined;
  17689. }
  17690. }
  17691. // Particles
  17692. if (parsedData.particleSystems) {
  17693. for (index = 0; index < parsedData.particleSystems.length; index++) {
  17694. var parsedParticleSystem = parsedData.particleSystems[index];
  17695. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  17696. particleSystems.push(parseParticleSystem(parsedParticleSystem, scene, rootUrl));
  17697. }
  17698. }
  17699. }
  17700. return true;
  17701. },
  17702. load: function (scene, data, rootUrl) {
  17703. var parsedData = JSON.parse(data);
  17704. // Scene
  17705. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  17706. scene.autoClear = parsedData.autoClear;
  17707. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  17708. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  17709. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  17710. // Fog
  17711. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  17712. scene.fogMode = parsedData.fogMode;
  17713. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  17714. scene.fogStart = parsedData.fogStart;
  17715. scene.fogEnd = parsedData.fogEnd;
  17716. scene.fogDensity = parsedData.fogDensity;
  17717. }
  17718. for (var index = 0; index < parsedData.lights.length; index++) {
  17719. var parsedLight = parsedData.lights[index];
  17720. parseLight(parsedLight, scene);
  17721. }
  17722. // Materials
  17723. if (parsedData.materials) {
  17724. for (index = 0; index < parsedData.materials.length; index++) {
  17725. var parsedMaterial = parsedData.materials[index];
  17726. parseMaterial(parsedMaterial, scene, rootUrl);
  17727. }
  17728. }
  17729. if (parsedData.multiMaterials) {
  17730. for (index = 0; index < parsedData.multiMaterials.length; index++) {
  17731. var parsedMultiMaterial = parsedData.multiMaterials[index];
  17732. parseMultiMaterial(parsedMultiMaterial, scene);
  17733. }
  17734. }
  17735. // Skeletons
  17736. if (parsedData.skeletons) {
  17737. for (index = 0; index < parsedData.skeletons.length; index++) {
  17738. var parsedSkeleton = parsedData.skeletons[index];
  17739. parseSkeleton(parsedSkeleton, scene);
  17740. }
  17741. }
  17742. // Geometries
  17743. var geometries = parsedData.geometries;
  17744. if (geometries) {
  17745. // Boxes
  17746. var boxes = geometries.boxes;
  17747. if (boxes) {
  17748. for (index = 0; index < boxes.length; index++) {
  17749. var parsedBox = boxes[index];
  17750. parseBox(parsedBox, scene);
  17751. }
  17752. }
  17753. // Spheres
  17754. var spheres = geometries.spheres;
  17755. if (spheres) {
  17756. for (index = 0; index < spheres.length; index++) {
  17757. var parsedSphere = spheres[index];
  17758. parseSphere(parsedSphere, scene);
  17759. }
  17760. }
  17761. // Cylinders
  17762. var cylinders = geometries.cylinders;
  17763. if (cylinders) {
  17764. for (index = 0; index < cylinders.length; index++) {
  17765. var parsedCylinder = cylinders[index];
  17766. parseCylinder(parsedCylinder, scene);
  17767. }
  17768. }
  17769. // Toruses
  17770. var toruses = geometries.toruses;
  17771. if (toruses) {
  17772. for (index = 0; index < toruses.length; index++) {
  17773. var parsedTorus = toruses[index];
  17774. parseTorus(parsedTorus, scene);
  17775. }
  17776. }
  17777. // Grounds
  17778. var grounds = geometries.grounds;
  17779. if (grounds) {
  17780. for (index = 0; index < grounds.length; index++) {
  17781. var parsedGround = grounds[index];
  17782. parseGround(parsedGround, scene);
  17783. }
  17784. }
  17785. // Planes
  17786. var planes = geometries.planes;
  17787. if (planes) {
  17788. for (index = 0; index < planes.length; index++) {
  17789. var parsedPlane = planes[index];
  17790. parsePlane(parsedPlane, scene);
  17791. }
  17792. }
  17793. // TorusKnots
  17794. var torusKnots = geometries.torusKnots;
  17795. if (torusKnots) {
  17796. for (index = 0; index < torusKnots.length; index++) {
  17797. var parsedTorusKnot = torusKnots[index];
  17798. parseTorusKnot(parsedTorusKnot, scene);
  17799. }
  17800. }
  17801. // VertexData
  17802. var vertexData = geometries.vertexData;
  17803. if (vertexData) {
  17804. for (index = 0; index < vertexData.length; index++) {
  17805. var parsedVertexData = vertexData[index];
  17806. parseVertexData(parsedVertexData, scene, rootUrl);
  17807. }
  17808. }
  17809. }
  17810. for (index = 0; index < parsedData.meshes.length; index++) {
  17811. var parsedMesh = parsedData.meshes[index];
  17812. parseMesh(parsedMesh, scene, rootUrl);
  17813. }
  17814. for (index = 0; index < parsedData.cameras.length; index++) {
  17815. var parsedCamera = parsedData.cameras[index];
  17816. parseCamera(parsedCamera, scene);
  17817. }
  17818. if (parsedData.activeCameraID) {
  17819. scene.setActiveCameraByID(parsedData.activeCameraID);
  17820. }
  17821. for (index = 0; index < scene.cameras.length; index++) {
  17822. var camera = scene.cameras[index];
  17823. if (camera._waitingParentId) {
  17824. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  17825. camera._waitingParentId = undefined;
  17826. }
  17827. }
  17828. for (index = 0; index < scene.lights.length; index++) {
  17829. var light = scene.lights[index];
  17830. if (light._waitingParentId) {
  17831. light.parent = scene.getLastEntryByID(light._waitingParentId);
  17832. light._waitingParentId = undefined;
  17833. }
  17834. }
  17835. for (index = 0; index < scene.meshes.length; index++) {
  17836. var mesh = scene.meshes[index];
  17837. if (mesh._waitingParentId) {
  17838. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  17839. mesh._waitingParentId = undefined;
  17840. }
  17841. }
  17842. // Particles Systems
  17843. if (parsedData.particleSystems) {
  17844. for (index = 0; index < parsedData.particleSystems.length; index++) {
  17845. var parsedParticleSystem = parsedData.particleSystems[index];
  17846. parseParticleSystem(parsedParticleSystem, scene, rootUrl);
  17847. }
  17848. }
  17849. // Lens flares
  17850. if (parsedData.lensFlareSystems) {
  17851. for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
  17852. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  17853. parseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
  17854. }
  17855. }
  17856. // Shadows
  17857. if (parsedData.shadowGenerators) {
  17858. for (index = 0; index < parsedData.shadowGenerators.length; index++) {
  17859. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  17860. parseShadowGenerator(parsedShadowGenerator, scene);
  17861. }
  17862. }
  17863. // Finish
  17864. return true;
  17865. }
  17866. });
  17867. })(BABYLON.Internals || (BABYLON.Internals = {}));
  17868. var Internals = BABYLON.Internals;
  17869. })(BABYLON || (BABYLON = {}));
  17870. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  17871. var BABYLON;
  17872. (function (BABYLON) {
  17873. // Unique ID when we import meshes from Babylon to CSG
  17874. var currentCSGMeshId = 0;
  17875. // # class Vertex
  17876. // Represents a vertex of a polygon. Use your own vertex class instead of this
  17877. // one to provide additional features like texture coordinates and vertex
  17878. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  17879. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  17880. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  17881. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  17882. // is not used anywhere else.
  17883. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  17884. var Vertex = (function () {
  17885. function Vertex(pos, normal, uv) {
  17886. this.pos = pos;
  17887. this.normal = normal;
  17888. this.uv = uv;
  17889. }
  17890. Vertex.prototype.clone = function () {
  17891. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  17892. };
  17893. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  17894. // orientation of a polygon is flipped.
  17895. Vertex.prototype.flip = function () {
  17896. this.normal = this.normal.scale(-1);
  17897. };
  17898. // Create a new vertex between this vertex and `other` by linearly
  17899. // interpolating all properties using a parameter of `t`. Subclasses should
  17900. // override this to interpolate additional properties.
  17901. Vertex.prototype.interpolate = function (other, t) {
  17902. 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));
  17903. };
  17904. return Vertex;
  17905. })();
  17906. // # class Plane
  17907. // Represents a plane in 3D space.
  17908. var Plane = (function () {
  17909. function Plane(normal, w) {
  17910. this.normal = normal;
  17911. this.w = w;
  17912. }
  17913. Plane.FromPoints = function (a, b, c) {
  17914. var v0 = c.subtract(a);
  17915. var v1 = b.subtract(a);
  17916. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  17917. return null;
  17918. }
  17919. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  17920. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  17921. };
  17922. Plane.prototype.clone = function () {
  17923. return new Plane(this.normal.clone(), this.w);
  17924. };
  17925. Plane.prototype.flip = function () {
  17926. this.normal.scaleInPlace(-1);
  17927. this.w = -this.w;
  17928. };
  17929. // Split `polygon` by this plane if needed, then put the polygon or polygon
  17930. // fragments in the appropriate lists. Coplanar polygons go into either
  17931. // `coplanarFront` or `coplanarBack` depending on their orientation with
  17932. // respect to this plane. Polygons in front or in back of this plane go into
  17933. // either `front` or `back`.
  17934. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  17935. var COPLANAR = 0;
  17936. var FRONT = 1;
  17937. var BACK = 2;
  17938. var SPANNING = 3;
  17939. // Classify each point as well as the entire polygon into one of the above
  17940. // four classes.
  17941. var polygonType = 0;
  17942. var types = [];
  17943. for (var i = 0; i < polygon.vertices.length; i++) {
  17944. var t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  17945. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  17946. polygonType |= type;
  17947. types.push(type);
  17948. }
  17949. switch (polygonType) {
  17950. case COPLANAR:
  17951. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  17952. break;
  17953. case FRONT:
  17954. front.push(polygon);
  17955. break;
  17956. case BACK:
  17957. back.push(polygon);
  17958. break;
  17959. case SPANNING:
  17960. var f = [], b = [];
  17961. for (i = 0; i < polygon.vertices.length; i++) {
  17962. var j = (i + 1) % polygon.vertices.length;
  17963. var ti = types[i], tj = types[j];
  17964. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  17965. if (ti != BACK)
  17966. f.push(vi);
  17967. if (ti != FRONT)
  17968. b.push(ti != BACK ? vi.clone() : vi);
  17969. if ((ti | tj) == SPANNING) {
  17970. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  17971. var v = vi.interpolate(vj, t);
  17972. f.push(v);
  17973. b.push(v.clone());
  17974. }
  17975. }
  17976. if (f.length >= 3) {
  17977. var poly = new Polygon(f, polygon.shared);
  17978. if (poly.plane)
  17979. front.push(poly);
  17980. }
  17981. if (b.length >= 3) {
  17982. poly = new Polygon(b, polygon.shared);
  17983. if (poly.plane)
  17984. back.push(poly);
  17985. }
  17986. break;
  17987. }
  17988. };
  17989. Plane.EPSILON = 1e-5;
  17990. return Plane;
  17991. })();
  17992. // # class Polygon
  17993. // Represents a convex polygon. The vertices used to initialize a polygon must
  17994. // be coplanar and form a convex loop.
  17995. //
  17996. // Each convex polygon has a `shared` property, which is shared between all
  17997. // polygons that are clones of each other or were split from the same polygon.
  17998. // This can be used to define per-polygon properties (such as surface color).
  17999. var Polygon = (function () {
  18000. function Polygon(vertices, shared) {
  18001. this.vertices = vertices;
  18002. this.shared = shared;
  18003. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  18004. }
  18005. Polygon.prototype.clone = function () {
  18006. var vertices = this.vertices.map(function (v) {
  18007. return v.clone();
  18008. });
  18009. return new Polygon(vertices, this.shared);
  18010. };
  18011. Polygon.prototype.flip = function () {
  18012. this.vertices.reverse().map(function (v) {
  18013. v.flip();
  18014. });
  18015. this.plane.flip();
  18016. };
  18017. return Polygon;
  18018. })();
  18019. // # class Node
  18020. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  18021. // by picking a polygon to split along. That polygon (and all other coplanar
  18022. // polygons) are added directly to that node and the other polygons are added to
  18023. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  18024. // no distinction between internal and leaf nodes.
  18025. var Node = (function () {
  18026. function Node(polygons) {
  18027. this.plane = null;
  18028. this.front = null;
  18029. this.back = null;
  18030. this.polygons = [];
  18031. if (polygons) {
  18032. this.build(polygons);
  18033. }
  18034. }
  18035. Node.prototype.clone = function () {
  18036. var node = new Node();
  18037. node.plane = this.plane && this.plane.clone();
  18038. node.front = this.front && this.front.clone();
  18039. node.back = this.back && this.back.clone();
  18040. node.polygons = this.polygons.map(function (p) {
  18041. return p.clone();
  18042. });
  18043. return node;
  18044. };
  18045. // Convert solid space to empty space and empty space to solid space.
  18046. Node.prototype.invert = function () {
  18047. for (var i = 0; i < this.polygons.length; i++) {
  18048. this.polygons[i].flip();
  18049. }
  18050. if (this.plane) {
  18051. this.plane.flip();
  18052. }
  18053. if (this.front) {
  18054. this.front.invert();
  18055. }
  18056. if (this.back) {
  18057. this.back.invert();
  18058. }
  18059. var temp = this.front;
  18060. this.front = this.back;
  18061. this.back = temp;
  18062. };
  18063. // Recursively remove all polygons in `polygons` that are inside this BSP
  18064. // tree.
  18065. Node.prototype.clipPolygons = function (polygons) {
  18066. if (!this.plane)
  18067. return polygons.slice();
  18068. var front = [], back = [];
  18069. for (var i = 0; i < polygons.length; i++) {
  18070. this.plane.splitPolygon(polygons[i], front, back, front, back);
  18071. }
  18072. if (this.front) {
  18073. front = this.front.clipPolygons(front);
  18074. }
  18075. if (this.back) {
  18076. back = this.back.clipPolygons(back);
  18077. } else {
  18078. back = [];
  18079. }
  18080. return front.concat(back);
  18081. };
  18082. // Remove all polygons in this BSP tree that are inside the other BSP tree
  18083. // `bsp`.
  18084. Node.prototype.clipTo = function (bsp) {
  18085. this.polygons = bsp.clipPolygons(this.polygons);
  18086. if (this.front)
  18087. this.front.clipTo(bsp);
  18088. if (this.back)
  18089. this.back.clipTo(bsp);
  18090. };
  18091. // Return a list of all polygons in this BSP tree.
  18092. Node.prototype.allPolygons = function () {
  18093. var polygons = this.polygons.slice();
  18094. if (this.front)
  18095. polygons = polygons.concat(this.front.allPolygons());
  18096. if (this.back)
  18097. polygons = polygons.concat(this.back.allPolygons());
  18098. return polygons;
  18099. };
  18100. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  18101. // new polygons are filtered down to the bottom of the tree and become new
  18102. // nodes there. Each set of polygons is partitioned using the first polygon
  18103. // (no heuristic is used to pick a good split).
  18104. Node.prototype.build = function (polygons) {
  18105. if (!polygons.length)
  18106. return;
  18107. if (!this.plane)
  18108. this.plane = polygons[0].plane.clone();
  18109. var front = [], back = [];
  18110. for (var i = 0; i < polygons.length; i++) {
  18111. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  18112. }
  18113. if (front.length) {
  18114. if (!this.front)
  18115. this.front = new Node();
  18116. this.front.build(front);
  18117. }
  18118. if (back.length) {
  18119. if (!this.back)
  18120. this.back = new Node();
  18121. this.back.build(back);
  18122. }
  18123. };
  18124. return Node;
  18125. })();
  18126. var CSG = (function () {
  18127. function CSG() {
  18128. this.polygons = new Array();
  18129. }
  18130. // Convert BABYLON.Mesh to BABYLON.CSG
  18131. CSG.FromMesh = function (mesh) {
  18132. var vertex, normal, uv, position, polygon, polygons = [], vertices;
  18133. if (mesh instanceof BABYLON.Mesh) {
  18134. mesh.computeWorldMatrix(true);
  18135. var matrix = mesh.getWorldMatrix();
  18136. var meshPosition = mesh.position.clone();
  18137. var meshRotation = mesh.rotation.clone();
  18138. var meshScaling = mesh.scaling.clone();
  18139. } else {
  18140. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  18141. }
  18142. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  18143. var subMeshes = mesh.subMeshes;
  18144. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  18145. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  18146. vertices = [];
  18147. for (var j = 0; j < 3; j++) {
  18148. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  18149. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  18150. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  18151. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  18152. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  18153. vertex = new Vertex(position, normal, uv);
  18154. vertices.push(vertex);
  18155. }
  18156. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  18157. // To handle the case of degenerated triangle
  18158. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  18159. if (polygon.plane)
  18160. polygons.push(polygon);
  18161. }
  18162. }
  18163. var csg = CSG.FromPolygons(polygons);
  18164. csg.matrix = matrix;
  18165. csg.position = meshPosition;
  18166. csg.rotation = meshRotation;
  18167. csg.scaling = meshScaling;
  18168. currentCSGMeshId++;
  18169. return csg;
  18170. };
  18171. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  18172. CSG.FromPolygons = function (polygons) {
  18173. var csg = new BABYLON.CSG();
  18174. csg.polygons = polygons;
  18175. return csg;
  18176. };
  18177. CSG.prototype.clone = function () {
  18178. var csg = new BABYLON.CSG();
  18179. csg.polygons = this.polygons.map(function (p) {
  18180. return p.clone();
  18181. });
  18182. csg.copyTransformAttributes(this);
  18183. return csg;
  18184. };
  18185. CSG.prototype.toPolygons = function () {
  18186. return this.polygons;
  18187. };
  18188. CSG.prototype.union = function (csg) {
  18189. var a = new Node(this.clone().polygons);
  18190. var b = new Node(csg.clone().polygons);
  18191. a.clipTo(b);
  18192. b.clipTo(a);
  18193. b.invert();
  18194. b.clipTo(a);
  18195. b.invert();
  18196. a.build(b.allPolygons());
  18197. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  18198. };
  18199. CSG.prototype.unionInPlace = function (csg) {
  18200. var a = new Node(this.polygons);
  18201. var b = new Node(csg.polygons);
  18202. a.clipTo(b);
  18203. b.clipTo(a);
  18204. b.invert();
  18205. b.clipTo(a);
  18206. b.invert();
  18207. a.build(b.allPolygons());
  18208. this.polygons = a.allPolygons();
  18209. };
  18210. CSG.prototype.subtract = function (csg) {
  18211. var a = new Node(this.clone().polygons);
  18212. var b = new Node(csg.clone().polygons);
  18213. a.invert();
  18214. a.clipTo(b);
  18215. b.clipTo(a);
  18216. b.invert();
  18217. b.clipTo(a);
  18218. b.invert();
  18219. a.build(b.allPolygons());
  18220. a.invert();
  18221. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  18222. };
  18223. CSG.prototype.subtractInPlace = function (csg) {
  18224. var a = new Node(this.polygons);
  18225. var b = new Node(csg.polygons);
  18226. a.invert();
  18227. a.clipTo(b);
  18228. b.clipTo(a);
  18229. b.invert();
  18230. b.clipTo(a);
  18231. b.invert();
  18232. a.build(b.allPolygons());
  18233. a.invert();
  18234. this.polygons = a.allPolygons();
  18235. };
  18236. CSG.prototype.intersect = function (csg) {
  18237. var a = new Node(this.clone().polygons);
  18238. var b = new Node(csg.clone().polygons);
  18239. a.invert();
  18240. b.clipTo(a);
  18241. b.invert();
  18242. a.clipTo(b);
  18243. b.clipTo(a);
  18244. a.build(b.allPolygons());
  18245. a.invert();
  18246. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  18247. };
  18248. CSG.prototype.intersectInPlace = function (csg) {
  18249. var a = new Node(this.polygons);
  18250. var b = new Node(csg.polygons);
  18251. a.invert();
  18252. b.clipTo(a);
  18253. b.invert();
  18254. a.clipTo(b);
  18255. b.clipTo(a);
  18256. a.build(b.allPolygons());
  18257. a.invert();
  18258. this.polygons = a.allPolygons();
  18259. };
  18260. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  18261. // not modified.
  18262. CSG.prototype.inverse = function () {
  18263. var csg = this.clone();
  18264. csg.inverseInPlace();
  18265. return csg;
  18266. };
  18267. CSG.prototype.inverseInPlace = function () {
  18268. this.polygons.map(function (p) {
  18269. p.flip();
  18270. });
  18271. };
  18272. // This is used to keep meshes transformations so they can be restored
  18273. // when we build back a Babylon Mesh
  18274. // NB : All CSG operations are performed in world coordinates
  18275. CSG.prototype.copyTransformAttributes = function (csg) {
  18276. this.matrix = csg.matrix;
  18277. this.position = csg.position;
  18278. this.rotation = csg.rotation;
  18279. this.scaling = csg.scaling;
  18280. return this;
  18281. };
  18282. // Build Raw mesh from CSG
  18283. // Coordinates here are in world space
  18284. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  18285. var matrix = this.matrix.clone();
  18286. matrix.invert();
  18287. 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;
  18288. if (keepSubMeshes) {
  18289. // Sort Polygons, since subMeshes are indices range
  18290. polygons.sort(function (a, b) {
  18291. if (a.shared.meshId === b.shared.meshId) {
  18292. return a.shared.subMeshId - b.shared.subMeshId;
  18293. } else {
  18294. return a.shared.meshId - b.shared.meshId;
  18295. }
  18296. });
  18297. }
  18298. for (var i = 0, il = polygons.length; i < il; i++) {
  18299. polygon = polygons[i];
  18300. // Building SubMeshes
  18301. if (!subMesh_dict[polygon.shared.meshId]) {
  18302. subMesh_dict[polygon.shared.meshId] = {};
  18303. }
  18304. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  18305. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  18306. indexStart: +Infinity,
  18307. indexEnd: -Infinity,
  18308. materialIndex: polygon.shared.materialIndex
  18309. };
  18310. }
  18311. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  18312. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  18313. polygonIndices[0] = 0;
  18314. polygonIndices[1] = j - 1;
  18315. polygonIndices[2] = j;
  18316. for (var k = 0; k < 3; k++) {
  18317. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  18318. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  18319. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  18320. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  18321. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  18322. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  18323. // Check if 2 points can be merged
  18324. 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)) {
  18325. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  18326. uvs.push(uv.x, uv.y);
  18327. normals.push(normal.x, normal.y, normal.z);
  18328. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  18329. }
  18330. indices.push(vertex_idx);
  18331. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  18332. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  18333. currentIndex++;
  18334. }
  18335. }
  18336. }
  18337. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  18338. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  18339. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  18340. mesh.setIndices(indices);
  18341. if (keepSubMeshes) {
  18342. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  18343. var materialIndexOffset = 0, materialMaxIndex;
  18344. mesh.subMeshes.length = 0;
  18345. for (var m in subMesh_dict) {
  18346. materialMaxIndex = -1;
  18347. for (var sm in subMesh_dict[m]) {
  18348. subMesh_obj = subMesh_dict[m][sm];
  18349. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  18350. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  18351. }
  18352. materialIndexOffset += ++materialMaxIndex;
  18353. }
  18354. }
  18355. return mesh;
  18356. };
  18357. // Build Mesh from CSG taking material and transforms into account
  18358. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  18359. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  18360. mesh.material = material;
  18361. mesh.position.copyFrom(this.position);
  18362. mesh.rotation.copyFrom(this.rotation);
  18363. mesh.scaling.copyFrom(this.scaling);
  18364. mesh.computeWorldMatrix(true);
  18365. return mesh;
  18366. };
  18367. return CSG;
  18368. })();
  18369. BABYLON.CSG = CSG;
  18370. })(BABYLON || (BABYLON = {}));
  18371. //# sourceMappingURL=babylon.csg.js.map
  18372. var BABYLON;
  18373. (function (BABYLON) {
  18374. var OculusDistortionCorrectionPostProcess = (function (_super) {
  18375. __extends(OculusDistortionCorrectionPostProcess, _super);
  18376. //ANY
  18377. function OculusDistortionCorrectionPostProcess(name, camera, isRightEye, cameraSettings) {
  18378. var _this = this;
  18379. _super.call(this, name, "oculusDistortionCorrection", [
  18380. 'LensCenter',
  18381. 'Scale',
  18382. 'ScaleIn',
  18383. 'HmdWarpParam'
  18384. ], null, cameraSettings.PostProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  18385. this._isRightEye = isRightEye;
  18386. this._distortionFactors = cameraSettings.DistortionK;
  18387. this._postProcessScaleFactor = cameraSettings.PostProcessScaleFactor;
  18388. this._lensCenterOffset = cameraSettings.LensCenterOffset;
  18389. this.onSizeChanged = function () {
  18390. _this.aspectRatio = _this.width * .5 / _this.height;
  18391. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  18392. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  18393. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  18394. };
  18395. this.onApply = function (effect) {
  18396. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  18397. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  18398. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  18399. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  18400. };
  18401. }
  18402. return OculusDistortionCorrectionPostProcess;
  18403. })(BABYLON.PostProcess);
  18404. BABYLON.OculusDistortionCorrectionPostProcess = OculusDistortionCorrectionPostProcess;
  18405. })(BABYLON || (BABYLON = {}));
  18406. //# sourceMappingURL=babylon.oculusDistortionCorrectionPostProcess.js.map
  18407. // Mainly based on these 2 articles :
  18408. // 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
  18409. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  18410. var BABYLON;
  18411. (function (BABYLON) {
  18412. (function (JoystickAxis) {
  18413. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  18414. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  18415. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  18416. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  18417. var JoystickAxis = BABYLON.JoystickAxis;
  18418. var VirtualJoystick = (function () {
  18419. function VirtualJoystick(leftJoystick) {
  18420. var _this = this;
  18421. if (leftJoystick) {
  18422. this._leftJoystick = true;
  18423. } else {
  18424. this._leftJoystick = false;
  18425. }
  18426. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  18427. VirtualJoystick._globalJoystickIndex++;
  18428. // By default left & right arrow keys are moving the X
  18429. // and up & down keys are moving the Y
  18430. this._axisTargetedByLeftAndRight = 0 /* X */;
  18431. this._axisTargetedByUpAndDown = 1 /* Y */;
  18432. this.reverseLeftRight = false;
  18433. this.reverseUpDown = false;
  18434. // collections of pointers
  18435. this._touches = new BABYLON.VirtualJoystick.Collection();
  18436. this.deltaPosition = BABYLON.Vector3.Zero();
  18437. this._joystickSensibility = 25;
  18438. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  18439. this._rotationSpeed = 25;
  18440. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  18441. this._rotateOnAxisRelativeToMesh = false;
  18442. // injecting a canvas element on top of the canvas 3D game
  18443. if (!VirtualJoystick.vjCanvas) {
  18444. window.addEventListener("resize", function () {
  18445. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  18446. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  18447. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  18448. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  18449. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  18450. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  18451. }, false);
  18452. VirtualJoystick.vjCanvas = document.createElement("canvas");
  18453. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  18454. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  18455. VirtualJoystick.vjCanvas.width = window.innerWidth;
  18456. VirtualJoystick.vjCanvas.height = window.innerHeight;
  18457. VirtualJoystick.vjCanvas.style.width = "100%";
  18458. VirtualJoystick.vjCanvas.style.height = "100%";
  18459. VirtualJoystick.vjCanvas.style.position = "absolute";
  18460. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  18461. VirtualJoystick.vjCanvas.style.top = "0px";
  18462. VirtualJoystick.vjCanvas.style.left = "0px";
  18463. VirtualJoystick.vjCanvas.style.zIndex = "5";
  18464. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  18465. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  18466. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  18467. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  18468. document.body.appendChild(VirtualJoystick.vjCanvas);
  18469. }
  18470. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  18471. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  18472. this.pressed = false;
  18473. // default joystick color
  18474. this._joystickColor = "cyan";
  18475. this._joystickPointerID = -1;
  18476. // current joystick position
  18477. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  18478. // origin joystick position
  18479. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  18480. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  18481. VirtualJoystick.vjCanvas.addEventListener('pointerdown', function (evt) {
  18482. _this._onPointerDown(evt);
  18483. }, false);
  18484. VirtualJoystick.vjCanvas.addEventListener('pointermove', function (evt) {
  18485. _this._onPointerMove(evt);
  18486. }, false);
  18487. VirtualJoystick.vjCanvas.addEventListener('pointerup', function (evt) {
  18488. _this._onPointerUp(evt);
  18489. }, false);
  18490. VirtualJoystick.vjCanvas.addEventListener('pointerout', function (evt) {
  18491. _this._onPointerUp(evt);
  18492. }, false);
  18493. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  18494. evt.preventDefault(); // Disables system menu
  18495. }, false);
  18496. requestAnimationFrame(function () {
  18497. _this._drawVirtualJoystick();
  18498. });
  18499. }
  18500. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  18501. this._joystickSensibility = newJoystickSensibility;
  18502. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  18503. };
  18504. VirtualJoystick.prototype._onPointerDown = function (e) {
  18505. var positionOnScreenCondition;
  18506. e.preventDefault();
  18507. if (this._leftJoystick === true) {
  18508. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  18509. } else {
  18510. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  18511. }
  18512. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  18513. // First contact will be dedicated to the virtual joystick
  18514. this._joystickPointerID = e.pointerId;
  18515. this._joystickPointerStartPos.x = e.clientX;
  18516. this._joystickPointerStartPos.y = e.clientY;
  18517. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  18518. this._deltaJoystickVector.x = 0;
  18519. this._deltaJoystickVector.y = 0;
  18520. this.pressed = true;
  18521. this._touches.add(e.pointerId.toString(), e);
  18522. } else {
  18523. // You can only trigger the action buttons with a joystick declared
  18524. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  18525. this._action();
  18526. this._touches.add(e.pointerId.toString(), e);
  18527. }
  18528. }
  18529. };
  18530. VirtualJoystick.prototype._onPointerMove = function (e) {
  18531. // If the current pointer is the one associated to the joystick (first touch contact)
  18532. if (this._joystickPointerID == e.pointerId) {
  18533. this._joystickPointerPos.x = e.clientX;
  18534. this._joystickPointerPos.y = e.clientY;
  18535. this._deltaJoystickVector = this._joystickPointerPos.clone();
  18536. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  18537. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  18538. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  18539. switch (this._axisTargetedByLeftAndRight) {
  18540. case 0 /* X */:
  18541. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  18542. break;
  18543. case 1 /* Y */:
  18544. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  18545. break;
  18546. case 2 /* Z */:
  18547. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  18548. break;
  18549. }
  18550. var directionUpDown = this.reverseUpDown ? 1 : -1;
  18551. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  18552. switch (this._axisTargetedByUpAndDown) {
  18553. case 0 /* X */:
  18554. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  18555. break;
  18556. case 1 /* Y */:
  18557. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  18558. break;
  18559. case 2 /* Z */:
  18560. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  18561. break;
  18562. }
  18563. } else {
  18564. if (this._touches.item(e.pointerId.toString())) {
  18565. this._touches.item(e.pointerId.toString()).x = e.clientX;
  18566. this._touches.item(e.pointerId.toString()).y = e.clientY;
  18567. }
  18568. }
  18569. };
  18570. VirtualJoystick.prototype._onPointerUp = function (e) {
  18571. this._clearCanvas();
  18572. if (this._joystickPointerID == e.pointerId) {
  18573. this._joystickPointerID = -1;
  18574. this.pressed = false;
  18575. }
  18576. this._deltaJoystickVector.x = 0;
  18577. this._deltaJoystickVector.y = 0;
  18578. this._touches.remove(e.pointerId.toString());
  18579. };
  18580. /**
  18581. * Change the color of the virtual joystick
  18582. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  18583. */
  18584. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  18585. this._joystickColor = newColor;
  18586. };
  18587. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  18588. this._action = action;
  18589. };
  18590. // Define which axis you'd like to control for left & right
  18591. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  18592. switch (axis) {
  18593. case 0 /* X */:
  18594. case 1 /* Y */:
  18595. case 2 /* Z */:
  18596. this._axisTargetedByLeftAndRight = axis;
  18597. break;
  18598. default:
  18599. this._axisTargetedByLeftAndRight = 0 /* X */;
  18600. break;
  18601. }
  18602. };
  18603. // Define which axis you'd like to control for up & down
  18604. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  18605. switch (axis) {
  18606. case 0 /* X */:
  18607. case 1 /* Y */:
  18608. case 2 /* Z */:
  18609. this._axisTargetedByUpAndDown = axis;
  18610. break;
  18611. default:
  18612. this._axisTargetedByUpAndDown = 1 /* Y */;
  18613. break;
  18614. }
  18615. };
  18616. VirtualJoystick.prototype._clearCanvas = function () {
  18617. if (this._leftJoystick) {
  18618. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  18619. } else {
  18620. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  18621. }
  18622. };
  18623. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  18624. var _this = this;
  18625. if (this.pressed) {
  18626. this._clearCanvas();
  18627. this._touches.forEach(function (touch) {
  18628. if (touch.pointerId === _this._joystickPointerID) {
  18629. VirtualJoystick.vjCanvasContext.beginPath();
  18630. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  18631. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  18632. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  18633. VirtualJoystick.vjCanvasContext.stroke();
  18634. VirtualJoystick.vjCanvasContext.beginPath();
  18635. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  18636. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  18637. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  18638. VirtualJoystick.vjCanvasContext.stroke();
  18639. VirtualJoystick.vjCanvasContext.beginPath();
  18640. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  18641. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  18642. VirtualJoystick.vjCanvasContext.stroke();
  18643. } else {
  18644. VirtualJoystick.vjCanvasContext.beginPath();
  18645. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  18646. VirtualJoystick.vjCanvasContext.beginPath();
  18647. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  18648. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  18649. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  18650. VirtualJoystick.vjCanvasContext.stroke();
  18651. }
  18652. ;
  18653. });
  18654. }
  18655. requestAnimationFrame(function () {
  18656. _this._drawVirtualJoystick();
  18657. });
  18658. };
  18659. VirtualJoystick.prototype.releaseCanvas = function () {
  18660. if (VirtualJoystick.vjCanvas) {
  18661. document.body.removeChild(VirtualJoystick.vjCanvas);
  18662. VirtualJoystick.vjCanvas = null;
  18663. }
  18664. };
  18665. VirtualJoystick._globalJoystickIndex = 0;
  18666. return VirtualJoystick;
  18667. })();
  18668. BABYLON.VirtualJoystick = VirtualJoystick;
  18669. })(BABYLON || (BABYLON = {}));
  18670. var BABYLON;
  18671. (function (BABYLON) {
  18672. (function (VirtualJoystick) {
  18673. var Collection = (function () {
  18674. function Collection() {
  18675. this._count = 0;
  18676. this._collection = new Array();
  18677. }
  18678. Collection.prototype.Count = function () {
  18679. return this._count;
  18680. };
  18681. Collection.prototype.add = function (key, item) {
  18682. if (this._collection[key] != undefined) {
  18683. return undefined;
  18684. }
  18685. this._collection[key] = item;
  18686. return ++this._count;
  18687. };
  18688. Collection.prototype.remove = function (key) {
  18689. if (this._collection[key] == undefined) {
  18690. return undefined;
  18691. }
  18692. delete this._collection[key];
  18693. return --this._count;
  18694. };
  18695. Collection.prototype.item = function (key) {
  18696. return this._collection[key];
  18697. };
  18698. Collection.prototype.forEach = function (block) {
  18699. var key;
  18700. for (key in this._collection) {
  18701. if (this._collection.hasOwnProperty(key)) {
  18702. block(this._collection[key]);
  18703. }
  18704. }
  18705. };
  18706. return Collection;
  18707. })();
  18708. VirtualJoystick.Collection = Collection;
  18709. })(BABYLON.VirtualJoystick || (BABYLON.VirtualJoystick = {}));
  18710. var VirtualJoystick = BABYLON.VirtualJoystick;
  18711. })(BABYLON || (BABYLON = {}));
  18712. //# sourceMappingURL=babylon.virtualJoystick.js.map
  18713. var BABYLON;
  18714. (function (BABYLON) {
  18715. var OculusRiftDevKit2013_Metric = {
  18716. HResolution: 1280,
  18717. VResolution: 800,
  18718. HScreenSize: 0.149759993,
  18719. VScreenSize: 0.0935999975,
  18720. VScreenCenter: 0.0467999987,
  18721. EyeToScreenDistance: 0.0410000011,
  18722. LensSeparationDistance: 0.0635000020,
  18723. InterpupillaryDistance: 0.0640000030,
  18724. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  18725. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  18726. PostProcessScaleFactor: 1.714605507808412,
  18727. LensCenterOffset: 0.151976421
  18728. };
  18729. var _OculusInnerCamera = (function (_super) {
  18730. __extends(_OculusInnerCamera, _super);
  18731. function _OculusInnerCamera(name, position, scene, isLeftEye) {
  18732. _super.call(this, name, position, scene);
  18733. this._workMatrix = new BABYLON.Matrix();
  18734. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  18735. // Constants
  18736. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  18737. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  18738. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  18739. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  18740. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  18741. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  18742. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  18743. // Postprocess
  18744. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  18745. }
  18746. _OculusInnerCamera.prototype.getProjectionMatrix = function () {
  18747. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  18748. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  18749. return this._projectionMatrix;
  18750. };
  18751. _OculusInnerCamera.prototype._getViewMatrix = function () {
  18752. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  18753. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  18754. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  18755. // Computing target and final matrix
  18756. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  18757. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  18758. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  18759. return this._viewMatrix;
  18760. };
  18761. return _OculusInnerCamera;
  18762. })(BABYLON.FreeCamera);
  18763. var OculusCamera = (function (_super) {
  18764. __extends(OculusCamera, _super);
  18765. function OculusCamera(name, position, scene) {
  18766. _super.call(this, name, position, scene);
  18767. this._leftCamera = new _OculusInnerCamera(name + "_left", position.clone(), scene, true);
  18768. this._rightCamera = new _OculusInnerCamera(name + "_right", position.clone(), scene, false);
  18769. this.subCameras.push(this._leftCamera);
  18770. this.subCameras.push(this._rightCamera);
  18771. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  18772. }
  18773. OculusCamera.prototype._update = function () {
  18774. this._leftCamera.position.copyFrom(this.position);
  18775. this._rightCamera.position.copyFrom(this.position);
  18776. this._updateCamera(this._leftCamera);
  18777. this._updateCamera(this._rightCamera);
  18778. _super.prototype._update.call(this);
  18779. };
  18780. OculusCamera.prototype._updateCamera = function (camera) {
  18781. camera.minZ = this.minZ;
  18782. camera.maxZ = this.maxZ;
  18783. camera.rotation.x = this.rotation.x;
  18784. camera.rotation.y = this.rotation.y;
  18785. camera.rotation.z = this.rotation.z;
  18786. };
  18787. // Oculus events
  18788. OculusCamera.prototype._onOrientationEvent = function (evt) {
  18789. var yaw = evt.alpha / 180 * Math.PI;
  18790. var pitch = evt.beta / 180 * Math.PI;
  18791. var roll = evt.gamma / 180 * Math.PI;
  18792. if (!this._offsetOrientation) {
  18793. this._offsetOrientation = {
  18794. yaw: yaw,
  18795. pitch: pitch,
  18796. roll: roll
  18797. };
  18798. return;
  18799. } else {
  18800. this.rotation.y += yaw - this._offsetOrientation.yaw;
  18801. this.rotation.x += pitch - this._offsetOrientation.pitch;
  18802. this.rotation.z += this._offsetOrientation.roll - roll;
  18803. this._offsetOrientation.yaw = yaw;
  18804. this._offsetOrientation.pitch = pitch;
  18805. this._offsetOrientation.roll = roll;
  18806. }
  18807. };
  18808. OculusCamera.prototype.attachControl = function (element, noPreventDefault) {
  18809. _super.prototype.attachControl.call(this, element, noPreventDefault);
  18810. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  18811. };
  18812. OculusCamera.prototype.detachControl = function (element) {
  18813. _super.prototype.detachControl.call(this, element);
  18814. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  18815. };
  18816. return OculusCamera;
  18817. })(BABYLON.FreeCamera);
  18818. BABYLON.OculusCamera = OculusCamera;
  18819. })(BABYLON || (BABYLON = {}));
  18820. //# sourceMappingURL=babylon.oculusCamera.js.map
  18821. var BABYLON;
  18822. (function (BABYLON) {
  18823. var OculusRiftDevKit2013_Metric = {
  18824. HResolution: 1280,
  18825. VResolution: 800,
  18826. HScreenSize: 0.149759993,
  18827. VScreenSize: 0.0935999975,
  18828. VScreenCenter: 0.0467999987,
  18829. EyeToScreenDistance: 0.0410000011,
  18830. LensSeparationDistance: 0.0635000020,
  18831. InterpupillaryDistance: 0.0640000030,
  18832. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  18833. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  18834. PostProcessScaleFactor: 1.714605507808412,
  18835. LensCenterOffset: 0.151976421
  18836. };
  18837. var _OculusInnerGamepadCamera = (function (_super) {
  18838. __extends(_OculusInnerGamepadCamera, _super);
  18839. function _OculusInnerGamepadCamera(name, position, scene, isLeftEye) {
  18840. _super.call(this, name, position, scene);
  18841. this._workMatrix = new BABYLON.Matrix();
  18842. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  18843. // Constants
  18844. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  18845. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  18846. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  18847. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  18848. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  18849. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  18850. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  18851. // Postprocess
  18852. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  18853. }
  18854. _OculusInnerGamepadCamera.prototype.getProjectionMatrix = function () {
  18855. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  18856. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  18857. return this._projectionMatrix;
  18858. };
  18859. _OculusInnerGamepadCamera.prototype._getViewMatrix = function () {
  18860. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  18861. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  18862. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  18863. // Computing target and final matrix
  18864. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  18865. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  18866. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  18867. return this._viewMatrix;
  18868. };
  18869. return _OculusInnerGamepadCamera;
  18870. })(BABYLON.FreeCamera);
  18871. var OculusGamepadCamera = (function (_super) {
  18872. __extends(OculusGamepadCamera, _super);
  18873. function OculusGamepadCamera(name, position, scene) {
  18874. var _this = this;
  18875. _super.call(this, name, position, scene);
  18876. this.angularSensibility = 200;
  18877. this.moveSensibility = 75;
  18878. this._leftCamera = new _OculusInnerGamepadCamera(name + "_left", position.clone(), scene, true);
  18879. this._rightCamera = new _OculusInnerGamepadCamera(name + "_right", position.clone(), scene, false);
  18880. this.subCameras.push(this._leftCamera);
  18881. this.subCameras.push(this._rightCamera);
  18882. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  18883. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  18884. _this._onNewGameConnected(gamepad);
  18885. });
  18886. }
  18887. OculusGamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  18888. // Only the first gamepad can control the camera
  18889. if (gamepad.index === 0) {
  18890. this._gamepad = gamepad;
  18891. }
  18892. };
  18893. OculusGamepadCamera.prototype._update = function () {
  18894. this._leftCamera.position.copyFrom(this.position);
  18895. this._rightCamera.position.copyFrom(this.position);
  18896. this._updateCamera(this._leftCamera);
  18897. this._updateCamera(this._rightCamera);
  18898. _super.prototype._update.call(this);
  18899. };
  18900. OculusGamepadCamera.prototype._checkInputs = function () {
  18901. if (!this._gamepad) {
  18902. return;
  18903. }
  18904. var LSValues = this._gamepad.leftStick;
  18905. var normalizedLX = LSValues.x / this.moveSensibility;
  18906. var normalizedLY = LSValues.y / this.moveSensibility;
  18907. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  18908. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  18909. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  18910. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x, 0, -LSValues.y), cameraTransform);
  18911. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  18912. };
  18913. OculusGamepadCamera.prototype._updateCamera = function (camera) {
  18914. camera.minZ = this.minZ;
  18915. camera.maxZ = this.maxZ;
  18916. camera.rotation.x = this.rotation.x;
  18917. camera.rotation.y = this.rotation.y;
  18918. camera.rotation.z = this.rotation.z;
  18919. };
  18920. // Oculus events
  18921. OculusGamepadCamera.prototype._onOrientationEvent = function (evt) {
  18922. var yaw = evt.alpha / 180 * Math.PI;
  18923. var pitch = evt.beta / 180 * Math.PI;
  18924. var roll = evt.gamma / 180 * Math.PI;
  18925. if (!this._offsetOrientation) {
  18926. this._offsetOrientation = {
  18927. yaw: yaw,
  18928. pitch: pitch,
  18929. roll: roll
  18930. };
  18931. return;
  18932. } else {
  18933. this.rotation.y += yaw - this._offsetOrientation.yaw;
  18934. this.rotation.x += pitch - this._offsetOrientation.pitch;
  18935. this.rotation.z += this._offsetOrientation.roll - roll;
  18936. this._offsetOrientation.yaw = yaw;
  18937. this._offsetOrientation.pitch = pitch;
  18938. this._offsetOrientation.roll = roll;
  18939. }
  18940. };
  18941. OculusGamepadCamera.prototype.attachControl = function (element, noPreventDefault) {
  18942. _super.prototype.attachControl.call(this, element, noPreventDefault);
  18943. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  18944. };
  18945. OculusGamepadCamera.prototype.detachControl = function (element) {
  18946. _super.prototype.detachControl.call(this, element);
  18947. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  18948. };
  18949. OculusGamepadCamera.prototype.dispose = function () {
  18950. this._gamepads.dispose();
  18951. _super.prototype.dispose.call(this);
  18952. };
  18953. return OculusGamepadCamera;
  18954. })(BABYLON.FreeCamera);
  18955. BABYLON.OculusGamepadCamera = OculusGamepadCamera;
  18956. })(BABYLON || (BABYLON = {}));
  18957. //# sourceMappingURL=babylon.oculusGamepadCamera.js.map
  18958. var BABYLON;
  18959. (function (BABYLON) {
  18960. // We're mainly based on the logic defined into the FreeCamera code
  18961. var VirtualJoysticksCamera = (function (_super) {
  18962. __extends(VirtualJoysticksCamera, _super);
  18963. function VirtualJoysticksCamera(name, position, scene) {
  18964. _super.call(this, name, position, scene);
  18965. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  18966. this._leftjoystick.setAxisForUpDown(2 /* Z */);
  18967. this._leftjoystick.setAxisForLeftRight(0 /* X */);
  18968. this._leftjoystick.setJoystickSensibility(0.15);
  18969. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  18970. this._rightjoystick.setAxisForUpDown(0 /* X */);
  18971. this._rightjoystick.setAxisForLeftRight(1 /* Y */);
  18972. this._rightjoystick.reverseUpDown = true;
  18973. this._rightjoystick.setJoystickSensibility(0.05);
  18974. this._rightjoystick.setJoystickColor("yellow");
  18975. }
  18976. VirtualJoysticksCamera.prototype._checkInputs = function () {
  18977. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  18978. var deltaTransform = BABYLON.Vector3.TransformCoordinates(this._leftjoystick.deltaPosition, cameraTransform);
  18979. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  18980. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  18981. if (!this._leftjoystick.pressed) {
  18982. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  18983. }
  18984. if (!this._rightjoystick.pressed) {
  18985. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  18986. }
  18987. };
  18988. VirtualJoysticksCamera.prototype.dispose = function () {
  18989. this._leftjoystick.releaseCanvas();
  18990. _super.prototype.dispose.call(this);
  18991. };
  18992. return VirtualJoysticksCamera;
  18993. })(BABYLON.FreeCamera);
  18994. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  18995. })(BABYLON || (BABYLON = {}));
  18996. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  18997. var BABYLON;
  18998. (function (BABYLON) {
  18999. var ShaderMaterial = (function (_super) {
  19000. __extends(ShaderMaterial, _super);
  19001. function ShaderMaterial(name, scene, shaderPath, options) {
  19002. _super.call(this, name, scene);
  19003. this._textures = new Array();
  19004. this._floats = new Array();
  19005. this._floatsArrays = {};
  19006. this._colors3 = new Array();
  19007. this._colors4 = new Array();
  19008. this._vectors2 = new Array();
  19009. this._vectors3 = new Array();
  19010. this._matrices = new Array();
  19011. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  19012. this._shaderPath = shaderPath;
  19013. options.needAlphaBlending = options.needAlphaBlending || false;
  19014. options.needAlphaTesting = options.needAlphaTesting || false;
  19015. options.attributes = options.attributes || ["position", "normal", "uv"];
  19016. options.uniforms = options.uniforms || ["worldViewProjection"];
  19017. options.samplers = options.samplers || [];
  19018. this._options = options;
  19019. }
  19020. ShaderMaterial.prototype.needAlphaBlending = function () {
  19021. return this._options.needAlphaBlending;
  19022. };
  19023. ShaderMaterial.prototype.needAlphaTesting = function () {
  19024. return this._options.needAlphaTesting;
  19025. };
  19026. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  19027. if (this._options.uniforms.indexOf(uniformName) === -1) {
  19028. this._options.uniforms.push(uniformName);
  19029. }
  19030. };
  19031. ShaderMaterial.prototype.setTexture = function (name, texture) {
  19032. if (this._options.samplers.indexOf(name) === -1) {
  19033. this._options.samplers.push(name);
  19034. }
  19035. this._textures[name] = texture;
  19036. return this;
  19037. };
  19038. ShaderMaterial.prototype.setFloat = function (name, value) {
  19039. this._checkUniform(name);
  19040. this._floats[name] = value;
  19041. return this;
  19042. };
  19043. ShaderMaterial.prototype.setFloats = function (name, value) {
  19044. this._checkUniform(name);
  19045. this._floatsArrays[name] = value;
  19046. return this;
  19047. };
  19048. ShaderMaterial.prototype.setColor3 = function (name, value) {
  19049. this._checkUniform(name);
  19050. this._colors3[name] = value;
  19051. return this;
  19052. };
  19053. ShaderMaterial.prototype.setColor4 = function (name, value) {
  19054. this._checkUniform(name);
  19055. this._colors4[name] = value;
  19056. return this;
  19057. };
  19058. ShaderMaterial.prototype.setVector2 = function (name, value) {
  19059. this._checkUniform(name);
  19060. this._vectors2[name] = value;
  19061. return this;
  19062. };
  19063. ShaderMaterial.prototype.setVector3 = function (name, value) {
  19064. this._checkUniform(name);
  19065. this._vectors3[name] = value;
  19066. return this;
  19067. };
  19068. ShaderMaterial.prototype.setMatrix = function (name, value) {
  19069. this._checkUniform(name);
  19070. this._matrices[name] = value;
  19071. return this;
  19072. };
  19073. ShaderMaterial.prototype.isReady = function () {
  19074. var scene = this.getScene();
  19075. var engine = scene.getEngine();
  19076. if (!this.checkReadyOnEveryCall) {
  19077. if (this._renderId === scene.getRenderId()) {
  19078. return true;
  19079. }
  19080. }
  19081. var previousEffect = this._effect;
  19082. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, "", null, this.onCompiled, this.onError);
  19083. if (!this._effect.isReady()) {
  19084. return false;
  19085. }
  19086. if (previousEffect !== this._effect) {
  19087. scene.resetCachedMaterial();
  19088. }
  19089. this._renderId = scene.getRenderId();
  19090. return true;
  19091. };
  19092. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  19093. var scene = this.getScene();
  19094. if (this._options.uniforms.indexOf("world") !== -1) {
  19095. this._effect.setMatrix("world", world);
  19096. }
  19097. if (this._options.uniforms.indexOf("worldView") !== -1) {
  19098. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  19099. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  19100. }
  19101. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  19102. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  19103. }
  19104. };
  19105. ShaderMaterial.prototype.bind = function (world) {
  19106. // Std values
  19107. this.bindOnlyWorldMatrix(world);
  19108. if (this.getScene().getCachedMaterial() !== this) {
  19109. if (this._options.uniforms.indexOf("view") !== -1) {
  19110. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  19111. }
  19112. if (this._options.uniforms.indexOf("projection") !== -1) {
  19113. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  19114. }
  19115. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  19116. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  19117. }
  19118. for (var name in this._textures) {
  19119. this._effect.setTexture(name, this._textures[name]);
  19120. }
  19121. for (name in this._floats) {
  19122. this._effect.setFloat(name, this._floats[name]);
  19123. }
  19124. for (name in this._floatsArrays) {
  19125. this._effect.setArray(name, this._floatsArrays[name]);
  19126. }
  19127. for (name in this._colors3) {
  19128. this._effect.setColor3(name, this._colors3[name]);
  19129. }
  19130. for (name in this._colors4) {
  19131. var color = this._colors4[name];
  19132. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  19133. }
  19134. for (name in this._vectors2) {
  19135. this._effect.setVector2(name, this._vectors2[name]);
  19136. }
  19137. for (name in this._vectors3) {
  19138. this._effect.setVector3(name, this._vectors3[name]);
  19139. }
  19140. for (name in this._matrices) {
  19141. this._effect.setMatrix(name, this._matrices[name]);
  19142. }
  19143. }
  19144. _super.prototype.bind.call(this, world, null);
  19145. };
  19146. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  19147. for (var name in this._textures) {
  19148. this._textures[name].dispose();
  19149. }
  19150. this._textures = [];
  19151. _super.prototype.dispose.call(this, forceDisposeEffect);
  19152. };
  19153. return ShaderMaterial;
  19154. })(BABYLON.Material);
  19155. BABYLON.ShaderMaterial = ShaderMaterial;
  19156. })(BABYLON || (BABYLON = {}));
  19157. //# sourceMappingURL=babylon.shaderMaterial.js.map
  19158. var BABYLON;
  19159. (function (BABYLON) {
  19160. var VertexData = (function () {
  19161. function VertexData() {
  19162. }
  19163. VertexData.prototype.set = function (data, kind) {
  19164. switch (kind) {
  19165. case BABYLON.VertexBuffer.PositionKind:
  19166. this.positions = data;
  19167. break;
  19168. case BABYLON.VertexBuffer.NormalKind:
  19169. this.normals = data;
  19170. break;
  19171. case BABYLON.VertexBuffer.UVKind:
  19172. this.uvs = data;
  19173. break;
  19174. case BABYLON.VertexBuffer.UV2Kind:
  19175. this.uv2s = data;
  19176. break;
  19177. case BABYLON.VertexBuffer.ColorKind:
  19178. this.colors = data;
  19179. break;
  19180. case BABYLON.VertexBuffer.MatricesIndicesKind:
  19181. this.matricesIndices = data;
  19182. break;
  19183. case BABYLON.VertexBuffer.MatricesWeightsKind:
  19184. this.matricesWeights = data;
  19185. break;
  19186. }
  19187. };
  19188. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  19189. this._applyTo(mesh, updatable);
  19190. };
  19191. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  19192. this._applyTo(geometry, updatable);
  19193. };
  19194. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  19195. this._update(mesh);
  19196. };
  19197. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  19198. this._update(geometry);
  19199. };
  19200. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  19201. if (this.positions) {
  19202. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  19203. }
  19204. if (this.normals) {
  19205. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  19206. }
  19207. if (this.uvs) {
  19208. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  19209. }
  19210. if (this.uv2s) {
  19211. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updatable);
  19212. }
  19213. if (this.colors) {
  19214. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  19215. }
  19216. if (this.matricesIndices) {
  19217. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  19218. }
  19219. if (this.matricesWeights) {
  19220. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  19221. }
  19222. if (this.indices) {
  19223. meshOrGeometry.setIndices(this.indices);
  19224. }
  19225. };
  19226. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  19227. if (this.positions) {
  19228. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  19229. }
  19230. if (this.normals) {
  19231. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  19232. }
  19233. if (this.uvs) {
  19234. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  19235. }
  19236. if (this.uv2s) {
  19237. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updateExtends, makeItUnique);
  19238. }
  19239. if (this.colors) {
  19240. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  19241. }
  19242. if (this.matricesIndices) {
  19243. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  19244. }
  19245. if (this.matricesWeights) {
  19246. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  19247. }
  19248. if (this.indices) {
  19249. meshOrGeometry.setIndices(this.indices);
  19250. }
  19251. };
  19252. VertexData.prototype.transform = function (matrix) {
  19253. var transformed = BABYLON.Vector3.Zero();
  19254. if (this.positions) {
  19255. var position = BABYLON.Vector3.Zero();
  19256. for (var index = 0; index < this.positions.length; index += 3) {
  19257. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  19258. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  19259. this.positions[index] = transformed.x;
  19260. this.positions[index + 1] = transformed.y;
  19261. this.positions[index + 2] = transformed.z;
  19262. }
  19263. }
  19264. if (this.normals) {
  19265. var normal = BABYLON.Vector3.Zero();
  19266. for (index = 0; index < this.normals.length; index += 3) {
  19267. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  19268. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  19269. this.normals[index] = transformed.x;
  19270. this.normals[index + 1] = transformed.y;
  19271. this.normals[index + 2] = transformed.z;
  19272. }
  19273. }
  19274. };
  19275. VertexData.prototype.merge = function (other) {
  19276. if (other.indices) {
  19277. if (!this.indices) {
  19278. this.indices = [];
  19279. }
  19280. var offset = this.positions ? this.positions.length / 3 : 0;
  19281. for (var index = 0; index < other.indices.length; index++) {
  19282. this.indices.push(other.indices[index] + offset);
  19283. }
  19284. }
  19285. if (other.positions) {
  19286. if (!this.positions) {
  19287. this.positions = [];
  19288. }
  19289. for (index = 0; index < other.positions.length; index++) {
  19290. this.positions.push(other.positions[index]);
  19291. }
  19292. }
  19293. if (other.normals) {
  19294. if (!this.normals) {
  19295. this.normals = [];
  19296. }
  19297. for (index = 0; index < other.normals.length; index++) {
  19298. this.normals.push(other.normals[index]);
  19299. }
  19300. }
  19301. if (other.uvs) {
  19302. if (!this.uvs) {
  19303. this.uvs = [];
  19304. }
  19305. for (index = 0; index < other.uvs.length; index++) {
  19306. this.uvs.push(other.uvs[index]);
  19307. }
  19308. }
  19309. if (other.uv2s) {
  19310. if (!this.uv2s) {
  19311. this.uv2s = [];
  19312. }
  19313. for (index = 0; index < other.uv2s.length; index++) {
  19314. this.uv2s.push(other.uv2s[index]);
  19315. }
  19316. }
  19317. if (other.matricesIndices) {
  19318. if (!this.matricesIndices) {
  19319. this.matricesIndices = [];
  19320. }
  19321. for (index = 0; index < other.matricesIndices.length; index++) {
  19322. this.matricesIndices.push(other.matricesIndices[index]);
  19323. }
  19324. }
  19325. if (other.matricesWeights) {
  19326. if (!this.matricesWeights) {
  19327. this.matricesWeights = [];
  19328. }
  19329. for (index = 0; index < other.matricesWeights.length; index++) {
  19330. this.matricesWeights.push(other.matricesWeights[index]);
  19331. }
  19332. }
  19333. if (other.colors) {
  19334. if (!this.colors) {
  19335. this.colors = [];
  19336. }
  19337. for (index = 0; index < other.colors.length; index++) {
  19338. this.colors.push(other.colors[index]);
  19339. }
  19340. }
  19341. };
  19342. // Statics
  19343. VertexData.ExtractFromMesh = function (mesh) {
  19344. return VertexData._ExtractFrom(mesh);
  19345. };
  19346. VertexData.ExtractFromGeometry = function (geometry) {
  19347. return VertexData._ExtractFrom(geometry);
  19348. };
  19349. VertexData._ExtractFrom = function (meshOrGeometry) {
  19350. var result = new BABYLON.VertexData();
  19351. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  19352. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19353. }
  19354. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  19355. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19356. }
  19357. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  19358. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind);
  19359. }
  19360. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  19361. result.uv2s = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  19362. }
  19363. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  19364. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  19365. }
  19366. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  19367. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  19368. }
  19369. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  19370. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  19371. }
  19372. result.indices = meshOrGeometry.getIndices();
  19373. return result;
  19374. };
  19375. VertexData.CreateBox = function (size) {
  19376. var normalsSource = [
  19377. new BABYLON.Vector3(0, 0, 1),
  19378. new BABYLON.Vector3(0, 0, -1),
  19379. new BABYLON.Vector3(1, 0, 0),
  19380. new BABYLON.Vector3(-1, 0, 0),
  19381. new BABYLON.Vector3(0, 1, 0),
  19382. new BABYLON.Vector3(0, -1, 0)
  19383. ];
  19384. var indices = [];
  19385. var positions = [];
  19386. var normals = [];
  19387. var uvs = [];
  19388. size = size || 1;
  19389. for (var index = 0; index < normalsSource.length; index++) {
  19390. var normal = normalsSource[index];
  19391. // Get two vectors perpendicular to the face normal and to each other.
  19392. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  19393. var side2 = BABYLON.Vector3.Cross(normal, side1);
  19394. // Six indices (two triangles) per face.
  19395. var verticesLength = positions.length / 3;
  19396. indices.push(verticesLength);
  19397. indices.push(verticesLength + 1);
  19398. indices.push(verticesLength + 2);
  19399. indices.push(verticesLength);
  19400. indices.push(verticesLength + 2);
  19401. indices.push(verticesLength + 3);
  19402. // Four vertices per face.
  19403. var vertex = normal.subtract(side1).subtract(side2).scale(size / 2);
  19404. positions.push(vertex.x, vertex.y, vertex.z);
  19405. normals.push(normal.x, normal.y, normal.z);
  19406. uvs.push(1.0, 1.0);
  19407. vertex = normal.subtract(side1).add(side2).scale(size / 2);
  19408. positions.push(vertex.x, vertex.y, vertex.z);
  19409. normals.push(normal.x, normal.y, normal.z);
  19410. uvs.push(0.0, 1.0);
  19411. vertex = normal.add(side1).add(side2).scale(size / 2);
  19412. positions.push(vertex.x, vertex.y, vertex.z);
  19413. normals.push(normal.x, normal.y, normal.z);
  19414. uvs.push(0.0, 0.0);
  19415. vertex = normal.add(side1).subtract(side2).scale(size / 2);
  19416. positions.push(vertex.x, vertex.y, vertex.z);
  19417. normals.push(normal.x, normal.y, normal.z);
  19418. uvs.push(1.0, 0.0);
  19419. }
  19420. // Result
  19421. var vertexData = new BABYLON.VertexData();
  19422. vertexData.indices = indices;
  19423. vertexData.positions = positions;
  19424. vertexData.normals = normals;
  19425. vertexData.uvs = uvs;
  19426. return vertexData;
  19427. };
  19428. VertexData.CreateSphere = function (segments, diameter) {
  19429. segments = segments || 32;
  19430. diameter = diameter || 1;
  19431. var radius = diameter / 2;
  19432. var totalZRotationSteps = 2 + segments;
  19433. var totalYRotationSteps = 2 * totalZRotationSteps;
  19434. var indices = [];
  19435. var positions = [];
  19436. var normals = [];
  19437. var uvs = [];
  19438. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  19439. var normalizedZ = zRotationStep / totalZRotationSteps;
  19440. var angleZ = (normalizedZ * Math.PI);
  19441. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  19442. var normalizedY = yRotationStep / totalYRotationSteps;
  19443. var angleY = normalizedY * Math.PI * 2;
  19444. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  19445. var rotationY = BABYLON.Matrix.RotationY(angleY);
  19446. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  19447. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  19448. var vertex = complete.scale(radius);
  19449. var normal = BABYLON.Vector3.Normalize(vertex);
  19450. positions.push(vertex.x, vertex.y, vertex.z);
  19451. normals.push(normal.x, normal.y, normal.z);
  19452. uvs.push(normalizedZ, normalizedY);
  19453. }
  19454. if (zRotationStep > 0) {
  19455. var verticesCount = positions.length / 3;
  19456. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  19457. indices.push((firstIndex));
  19458. indices.push((firstIndex + 1));
  19459. indices.push(firstIndex + totalYRotationSteps + 1);
  19460. indices.push((firstIndex + totalYRotationSteps + 1));
  19461. indices.push((firstIndex + 1));
  19462. indices.push((firstIndex + totalYRotationSteps + 2));
  19463. }
  19464. }
  19465. }
  19466. // Result
  19467. var vertexData = new BABYLON.VertexData();
  19468. vertexData.indices = indices;
  19469. vertexData.positions = positions;
  19470. vertexData.normals = normals;
  19471. vertexData.uvs = uvs;
  19472. return vertexData;
  19473. };
  19474. VertexData.CreateCylinder = function (height, diameterTop, diameterBottom, tessellation, subdivisions) {
  19475. if (typeof subdivisions === "undefined") { subdivisions = 1; }
  19476. var radiusTop = diameterTop / 2;
  19477. var radiusBottom = diameterBottom / 2;
  19478. var indices = [];
  19479. var positions = [];
  19480. var normals = [];
  19481. var uvs = [];
  19482. height = height || 1;
  19483. diameterTop = diameterTop || 0.5;
  19484. diameterBottom = diameterBottom || 1;
  19485. tessellation = tessellation || 16;
  19486. subdivisions = subdivisions || 1;
  19487. subdivisions = (subdivisions < 1) ? 1 : subdivisions;
  19488. var getCircleVector = function (i) {
  19489. var angle = (i * 2.0 * Math.PI / tessellation);
  19490. var dx = Math.cos(angle);
  19491. var dz = Math.sin(angle);
  19492. return new BABYLON.Vector3(dx, 0, dz);
  19493. };
  19494. var createCylinderCap = function (isTop) {
  19495. var radius = isTop ? radiusTop : radiusBottom;
  19496. if (radius == 0) {
  19497. return;
  19498. }
  19499. var vbase = positions.length / 3;
  19500. var offset = new BABYLON.Vector3(0, height / 2, 0);
  19501. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  19502. if (!isTop) {
  19503. offset.scaleInPlace(-1);
  19504. textureScale.x = -textureScale.x;
  19505. }
  19506. for (i = 0; i < tessellation; i++) {
  19507. var circleVector = getCircleVector(i);
  19508. var position = circleVector.scale(radius).add(offset);
  19509. var textureCoordinate = new BABYLON.Vector2(circleVector.x * textureScale.x + 0.5, circleVector.z * textureScale.y + 0.5);
  19510. positions.push(position.x, position.y, position.z);
  19511. uvs.push(textureCoordinate.x, textureCoordinate.y);
  19512. }
  19513. for (var i = 0; i < tessellation - 2; i++) {
  19514. if (!isTop) {
  19515. indices.push(vbase);
  19516. indices.push(vbase + (i + 2) % tessellation);
  19517. indices.push(vbase + (i + 1) % tessellation);
  19518. } else {
  19519. indices.push(vbase);
  19520. indices.push(vbase + (i + 1) % tessellation);
  19521. indices.push(vbase + (i + 2) % tessellation);
  19522. }
  19523. }
  19524. };
  19525. var base = new BABYLON.Vector3(0, -1, 0).scale(height / 2);
  19526. var offset = new BABYLON.Vector3(0, 1, 0).scale(height / subdivisions);
  19527. var stride = tessellation + 1;
  19528. for (var i = 0; i <= tessellation; i++) {
  19529. var circleVector = getCircleVector(i);
  19530. var textureCoordinate = new BABYLON.Vector2(i / tessellation, 0);
  19531. var position, radius = radiusBottom;
  19532. for (var s = 0; s <= subdivisions; s++) {
  19533. // Update variables
  19534. position = circleVector.scale(radius);
  19535. position.addInPlace(base.add(offset.scale(s)));
  19536. textureCoordinate.y += 1 / subdivisions;
  19537. radius += (radiusTop - radiusBottom) / subdivisions;
  19538. // Push in arrays
  19539. positions.push(position.x, position.y, position.z);
  19540. uvs.push(textureCoordinate.x, textureCoordinate.y);
  19541. }
  19542. }
  19543. subdivisions += 1;
  19544. for (var s = 0; s < subdivisions - 1; s++) {
  19545. for (var i = 0; i <= tessellation; i++) {
  19546. indices.push(i * subdivisions + s);
  19547. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  19548. indices.push(i * subdivisions + (s + 1));
  19549. indices.push(i * subdivisions + (s + 1));
  19550. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  19551. indices.push((i * subdivisions + (s + subdivisions + 1)) % (stride * subdivisions));
  19552. }
  19553. }
  19554. // Create flat triangle fan caps to seal the top and bottom.
  19555. createCylinderCap(true);
  19556. createCylinderCap(false);
  19557. // Normals
  19558. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  19559. // Result
  19560. var vertexData = new BABYLON.VertexData();
  19561. vertexData.indices = indices;
  19562. vertexData.positions = positions;
  19563. vertexData.normals = normals;
  19564. vertexData.uvs = uvs;
  19565. return vertexData;
  19566. };
  19567. VertexData.CreateTorus = function (diameter, thickness, tessellation) {
  19568. var indices = [];
  19569. var positions = [];
  19570. var normals = [];
  19571. var uvs = [];
  19572. diameter = diameter || 1;
  19573. thickness = thickness || 0.5;
  19574. tessellation = tessellation || 16;
  19575. var stride = tessellation + 1;
  19576. for (var i = 0; i <= tessellation; i++) {
  19577. var u = i / tessellation;
  19578. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  19579. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  19580. for (var j = 0; j <= tessellation; j++) {
  19581. var v = 1 - j / tessellation;
  19582. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  19583. var dx = Math.cos(innerAngle);
  19584. var dy = Math.sin(innerAngle);
  19585. // Create a vertex.
  19586. var normal = new BABYLON.Vector3(dx, dy, 0);
  19587. var position = normal.scale(thickness / 2);
  19588. var textureCoordinate = new BABYLON.Vector2(u, v);
  19589. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  19590. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  19591. positions.push(position.x, position.y, position.z);
  19592. normals.push(normal.x, normal.y, normal.z);
  19593. uvs.push(textureCoordinate.x, textureCoordinate.y);
  19594. // And create indices for two triangles.
  19595. var nextI = (i + 1) % stride;
  19596. var nextJ = (j + 1) % stride;
  19597. indices.push(i * stride + j);
  19598. indices.push(i * stride + nextJ);
  19599. indices.push(nextI * stride + j);
  19600. indices.push(i * stride + nextJ);
  19601. indices.push(nextI * stride + nextJ);
  19602. indices.push(nextI * stride + j);
  19603. }
  19604. }
  19605. // Result
  19606. var vertexData = new BABYLON.VertexData();
  19607. vertexData.indices = indices;
  19608. vertexData.positions = positions;
  19609. vertexData.normals = normals;
  19610. vertexData.uvs = uvs;
  19611. return vertexData;
  19612. };
  19613. VertexData.CreateLines = function (points) {
  19614. var indices = [];
  19615. var positions = [];
  19616. for (var index = 0; index < points.length; index++) {
  19617. positions.push(points[index].x, points[index].y, points[index].z);
  19618. if (index > 0) {
  19619. indices.push(index - 1);
  19620. indices.push(index);
  19621. }
  19622. }
  19623. // Result
  19624. var vertexData = new BABYLON.VertexData();
  19625. vertexData.indices = indices;
  19626. vertexData.positions = positions;
  19627. return vertexData;
  19628. };
  19629. VertexData.CreateGround = function (width, height, subdivisions) {
  19630. var indices = [];
  19631. var positions = [];
  19632. var normals = [];
  19633. var uvs = [];
  19634. var row, col;
  19635. width = width || 1;
  19636. height = height || 1;
  19637. subdivisions = subdivisions || 1;
  19638. for (row = 0; row <= subdivisions; row++) {
  19639. for (col = 0; col <= subdivisions; col++) {
  19640. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  19641. var normal = new BABYLON.Vector3(0, 1.0, 0);
  19642. positions.push(position.x, position.y, position.z);
  19643. normals.push(normal.x, normal.y, normal.z);
  19644. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  19645. }
  19646. }
  19647. for (row = 0; row < subdivisions; row++) {
  19648. for (col = 0; col < subdivisions; col++) {
  19649. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  19650. indices.push(col + 1 + row * (subdivisions + 1));
  19651. indices.push(col + row * (subdivisions + 1));
  19652. indices.push(col + (row + 1) * (subdivisions + 1));
  19653. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  19654. indices.push(col + row * (subdivisions + 1));
  19655. }
  19656. }
  19657. // Result
  19658. var vertexData = new BABYLON.VertexData();
  19659. vertexData.indices = indices;
  19660. vertexData.positions = positions;
  19661. vertexData.normals = normals;
  19662. vertexData.uvs = uvs;
  19663. return vertexData;
  19664. };
  19665. VertexData.CreateTiledGround = function (xmin, zmin, xmax, zmax, subdivisions, precision) {
  19666. if (typeof subdivisions === "undefined") { subdivisions = { w: 1, h: 1 }; }
  19667. if (typeof precision === "undefined") { precision = { w: 1, h: 1 }; }
  19668. var indices = [];
  19669. var positions = [];
  19670. var normals = [];
  19671. var uvs = [];
  19672. var row, col, tileRow, tileCol;
  19673. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  19674. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  19675. precision.w = (precision.w < 1) ? 1 : precision.w;
  19676. precision.h = (precision.h < 1) ? 1 : precision.h;
  19677. var tileSize = {
  19678. 'w': (xmax - xmin) / subdivisions.w,
  19679. 'h': (zmax - zmin) / subdivisions.h
  19680. };
  19681. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  19682. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  19683. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  19684. }
  19685. }
  19686. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  19687. // Indices
  19688. var base = positions.length / 3;
  19689. var rowLength = precision.w + 1;
  19690. for (row = 0; row < precision.h; row++) {
  19691. for (col = 0; col < precision.w; col++) {
  19692. var square = [
  19693. base + col + row * rowLength,
  19694. base + (col + 1) + row * rowLength,
  19695. base + (col + 1) + (row + 1) * rowLength,
  19696. base + col + (row + 1) * rowLength
  19697. ];
  19698. indices.push(square[1]);
  19699. indices.push(square[2]);
  19700. indices.push(square[3]);
  19701. indices.push(square[0]);
  19702. indices.push(square[1]);
  19703. indices.push(square[3]);
  19704. }
  19705. }
  19706. // Position, normals and uvs
  19707. var position = BABYLON.Vector3.Zero();
  19708. var normal = new BABYLON.Vector3(0, 1.0, 0);
  19709. for (row = 0; row <= precision.h; row++) {
  19710. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  19711. for (col = 0; col <= precision.w; col++) {
  19712. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  19713. position.y = 0;
  19714. positions.push(position.x, position.y, position.z);
  19715. normals.push(normal.x, normal.y, normal.z);
  19716. uvs.push(col / precision.w, row / precision.h);
  19717. }
  19718. }
  19719. }
  19720. // Result
  19721. var vertexData = new BABYLON.VertexData();
  19722. vertexData.indices = indices;
  19723. vertexData.positions = positions;
  19724. vertexData.normals = normals;
  19725. vertexData.uvs = uvs;
  19726. return vertexData;
  19727. };
  19728. VertexData.CreateGroundFromHeightMap = function (width, height, subdivisions, minHeight, maxHeight, buffer, bufferWidth, bufferHeight) {
  19729. var indices = [];
  19730. var positions = [];
  19731. var normals = [];
  19732. var uvs = [];
  19733. var row, col;
  19734. for (row = 0; row <= subdivisions; row++) {
  19735. for (col = 0; col <= subdivisions; col++) {
  19736. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  19737. // Compute height
  19738. var heightMapX = (((position.x + width / 2) / width) * (bufferWidth - 1)) | 0;
  19739. var heightMapY = ((1.0 - (position.z + height / 2) / height) * (bufferHeight - 1)) | 0;
  19740. var pos = (heightMapX + heightMapY * bufferWidth) * 4;
  19741. var r = buffer[pos] / 255.0;
  19742. var g = buffer[pos + 1] / 255.0;
  19743. var b = buffer[pos + 2] / 255.0;
  19744. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  19745. position.y = minHeight + (maxHeight - minHeight) * gradient;
  19746. // Add vertex
  19747. positions.push(position.x, position.y, position.z);
  19748. normals.push(0, 0, 0);
  19749. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  19750. }
  19751. }
  19752. for (row = 0; row < subdivisions; row++) {
  19753. for (col = 0; col < subdivisions; col++) {
  19754. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  19755. indices.push(col + 1 + row * (subdivisions + 1));
  19756. indices.push(col + row * (subdivisions + 1));
  19757. indices.push(col + (row + 1) * (subdivisions + 1));
  19758. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  19759. indices.push(col + row * (subdivisions + 1));
  19760. }
  19761. }
  19762. // Normals
  19763. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  19764. // Result
  19765. var vertexData = new BABYLON.VertexData();
  19766. vertexData.indices = indices;
  19767. vertexData.positions = positions;
  19768. vertexData.normals = normals;
  19769. vertexData.uvs = uvs;
  19770. return vertexData;
  19771. };
  19772. VertexData.CreatePlane = function (size) {
  19773. var indices = [];
  19774. var positions = [];
  19775. var normals = [];
  19776. var uvs = [];
  19777. size = size || 1;
  19778. // Vertices
  19779. var halfSize = size / 2.0;
  19780. positions.push(-halfSize, -halfSize, 0);
  19781. normals.push(0, 0, -1.0);
  19782. uvs.push(0.0, 0.0);
  19783. positions.push(halfSize, -halfSize, 0);
  19784. normals.push(0, 0, -1.0);
  19785. uvs.push(1.0, 0.0);
  19786. positions.push(halfSize, halfSize, 0);
  19787. normals.push(0, 0, -1.0);
  19788. uvs.push(1.0, 1.0);
  19789. positions.push(-halfSize, halfSize, 0);
  19790. normals.push(0, 0, -1.0);
  19791. uvs.push(0.0, 1.0);
  19792. // Indices
  19793. indices.push(0);
  19794. indices.push(1);
  19795. indices.push(2);
  19796. indices.push(0);
  19797. indices.push(2);
  19798. indices.push(3);
  19799. // Result
  19800. var vertexData = new BABYLON.VertexData();
  19801. vertexData.indices = indices;
  19802. vertexData.positions = positions;
  19803. vertexData.normals = normals;
  19804. vertexData.uvs = uvs;
  19805. return vertexData;
  19806. };
  19807. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  19808. VertexData.CreateTorusKnot = function (radius, tube, radialSegments, tubularSegments, p, q) {
  19809. var indices = [];
  19810. var positions = [];
  19811. var normals = [];
  19812. var uvs = [];
  19813. radius = radius || 2;
  19814. tube = tube || 0.5;
  19815. radialSegments = radialSegments || 32;
  19816. tubularSegments = tubularSegments || 32;
  19817. p = p || 2;
  19818. q = q || 3;
  19819. // Helper
  19820. var getPos = function (angle) {
  19821. var cu = Math.cos(angle);
  19822. var su = Math.sin(angle);
  19823. var quOverP = q / p * angle;
  19824. var cs = Math.cos(quOverP);
  19825. var tx = radius * (2 + cs) * 0.5 * cu;
  19826. var ty = radius * (2 + cs) * su * 0.5;
  19827. var tz = radius * Math.sin(quOverP) * 0.5;
  19828. return new BABYLON.Vector3(tx, ty, tz);
  19829. };
  19830. for (var i = 0; i <= radialSegments; i++) {
  19831. var modI = i % radialSegments;
  19832. var u = modI / radialSegments * 2 * p * Math.PI;
  19833. var p1 = getPos(u);
  19834. var p2 = getPos(u + 0.01);
  19835. var tang = p2.subtract(p1);
  19836. var n = p2.add(p1);
  19837. var bitan = BABYLON.Vector3.Cross(tang, n);
  19838. n = BABYLON.Vector3.Cross(bitan, tang);
  19839. bitan.normalize();
  19840. n.normalize();
  19841. for (var j = 0; j < tubularSegments; j++) {
  19842. var modJ = j % tubularSegments;
  19843. var v = modJ / tubularSegments * 2 * Math.PI;
  19844. var cx = -tube * Math.cos(v);
  19845. var cy = tube * Math.sin(v);
  19846. positions.push(p1.x + cx * n.x + cy * bitan.x);
  19847. positions.push(p1.y + cx * n.y + cy * bitan.y);
  19848. positions.push(p1.z + cx * n.z + cy * bitan.z);
  19849. uvs.push(i / radialSegments);
  19850. uvs.push(j / tubularSegments);
  19851. }
  19852. }
  19853. for (i = 0; i < radialSegments; i++) {
  19854. for (j = 0; j < tubularSegments; j++) {
  19855. var jNext = (j + 1) % tubularSegments;
  19856. var a = i * tubularSegments + j;
  19857. var b = (i + 1) * tubularSegments + j;
  19858. var c = (i + 1) * tubularSegments + jNext;
  19859. var d = i * tubularSegments + jNext;
  19860. indices.push(d);
  19861. indices.push(b);
  19862. indices.push(a);
  19863. indices.push(d);
  19864. indices.push(c);
  19865. indices.push(b);
  19866. }
  19867. }
  19868. // Normals
  19869. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  19870. // Result
  19871. var vertexData = new BABYLON.VertexData();
  19872. vertexData.indices = indices;
  19873. vertexData.positions = positions;
  19874. vertexData.normals = normals;
  19875. vertexData.uvs = uvs;
  19876. return vertexData;
  19877. };
  19878. // Tools
  19879. VertexData.ComputeNormals = function (positions, indices, normals) {
  19880. var positionVectors = [];
  19881. var facesOfVertices = [];
  19882. var index;
  19883. for (index = 0; index < positions.length; index += 3) {
  19884. var vector3 = new BABYLON.Vector3(positions[index], positions[index + 1], positions[index + 2]);
  19885. positionVectors.push(vector3);
  19886. facesOfVertices.push([]);
  19887. }
  19888. // Compute normals
  19889. var facesNormals = [];
  19890. for (index = 0; index < indices.length / 3; index++) {
  19891. var i1 = indices[index * 3];
  19892. var i2 = indices[index * 3 + 1];
  19893. var i3 = indices[index * 3 + 2];
  19894. var p1 = positionVectors[i1];
  19895. var p2 = positionVectors[i2];
  19896. var p3 = positionVectors[i3];
  19897. var p1p2 = p1.subtract(p2);
  19898. var p3p2 = p3.subtract(p2);
  19899. facesNormals[index] = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  19900. facesOfVertices[i1].push(index);
  19901. facesOfVertices[i2].push(index);
  19902. facesOfVertices[i3].push(index);
  19903. }
  19904. for (index = 0; index < positionVectors.length; index++) {
  19905. var faces = facesOfVertices[index];
  19906. var normal = BABYLON.Vector3.Zero();
  19907. for (var faceIndex = 0; faceIndex < faces.length; faceIndex++) {
  19908. normal.addInPlace(facesNormals[faces[faceIndex]]);
  19909. }
  19910. normal = BABYLON.Vector3.Normalize(normal.scale(1.0 / faces.length));
  19911. normals[index * 3] = normal.x;
  19912. normals[index * 3 + 1] = normal.y;
  19913. normals[index * 3 + 2] = normal.z;
  19914. }
  19915. };
  19916. return VertexData;
  19917. })();
  19918. BABYLON.VertexData = VertexData;
  19919. })(BABYLON || (BABYLON = {}));
  19920. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  19921. var BABYLON;
  19922. (function (BABYLON) {
  19923. var buildCamera = function (that, name) {
  19924. that._leftCamera.isIntermediate = true;
  19925. that.subCameras.push(that._leftCamera);
  19926. that.subCameras.push(that._rightCamera);
  19927. that._leftTexture = new BABYLON.PassPostProcess(name + "_leftTexture", 1.0, that._leftCamera);
  19928. that._anaglyphPostProcess = new BABYLON.AnaglyphPostProcess(name + "_anaglyph", 1.0, that._rightCamera);
  19929. that._anaglyphPostProcess.onApply = function (effect) {
  19930. effect.setTextureFromPostProcess("leftSampler", that._leftTexture);
  19931. };
  19932. that._update();
  19933. };
  19934. var AnaglyphArcRotateCamera = (function (_super) {
  19935. __extends(AnaglyphArcRotateCamera, _super);
  19936. // ANY
  19937. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, eyeSpace, scene) {
  19938. _super.call(this, name, alpha, beta, radius, target, scene);
  19939. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  19940. this._leftCamera = new BABYLON.ArcRotateCamera(name + "_left", alpha - this._eyeSpace, beta, radius, target, scene);
  19941. this._rightCamera = new BABYLON.ArcRotateCamera(name + "_right", alpha + this._eyeSpace, beta, radius, target, scene);
  19942. buildCamera(this, name);
  19943. }
  19944. AnaglyphArcRotateCamera.prototype._update = function () {
  19945. this._updateCamera(this._leftCamera);
  19946. this._updateCamera(this._rightCamera);
  19947. this._leftCamera.alpha = this.alpha - this._eyeSpace;
  19948. this._rightCamera.alpha = this.alpha + this._eyeSpace;
  19949. _super.prototype._update.call(this);
  19950. };
  19951. AnaglyphArcRotateCamera.prototype._updateCamera = function (camera) {
  19952. camera.beta = this.beta;
  19953. camera.radius = this.radius;
  19954. camera.minZ = this.minZ;
  19955. camera.maxZ = this.maxZ;
  19956. camera.fov = this.fov;
  19957. camera.target = this.target;
  19958. };
  19959. return AnaglyphArcRotateCamera;
  19960. })(BABYLON.ArcRotateCamera);
  19961. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  19962. var AnaglyphFreeCamera = (function (_super) {
  19963. __extends(AnaglyphFreeCamera, _super);
  19964. function AnaglyphFreeCamera(name, position, eyeSpace, scene) {
  19965. _super.call(this, name, position, scene);
  19966. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  19967. this._transformMatrix = new BABYLON.Matrix();
  19968. this._leftCamera = new BABYLON.FreeCamera(name + "_left", position.clone(), scene);
  19969. this._rightCamera = new BABYLON.FreeCamera(name + "_right", position.clone(), scene);
  19970. buildCamera(this, name);
  19971. }
  19972. AnaglyphFreeCamera.prototype._getSubCameraPosition = function (eyeSpace, result) {
  19973. var target = this.getTarget();
  19974. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(eyeSpace), this._transformMatrix);
  19975. this._transformMatrix = this._transformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  19976. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._transformMatrix, result);
  19977. };
  19978. AnaglyphFreeCamera.prototype._update = function () {
  19979. this._getSubCameraPosition(-this._eyeSpace, this._leftCamera.position);
  19980. this._getSubCameraPosition(this._eyeSpace, this._rightCamera.position);
  19981. this._updateCamera(this._leftCamera);
  19982. this._updateCamera(this._rightCamera);
  19983. _super.prototype._update.call(this);
  19984. };
  19985. AnaglyphFreeCamera.prototype._updateCamera = function (camera) {
  19986. camera.minZ = this.minZ;
  19987. camera.maxZ = this.maxZ;
  19988. camera.fov = this.fov;
  19989. camera.viewport = this.viewport;
  19990. camera.setTarget(this.getTarget());
  19991. };
  19992. return AnaglyphFreeCamera;
  19993. })(BABYLON.FreeCamera);
  19994. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  19995. })(BABYLON || (BABYLON = {}));
  19996. //# sourceMappingURL=babylon.anaglyphCamera.js.map
  19997. var BABYLON;
  19998. (function (BABYLON) {
  19999. var AnaglyphPostProcess = (function (_super) {
  20000. __extends(AnaglyphPostProcess, _super);
  20001. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  20002. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  20003. }
  20004. return AnaglyphPostProcess;
  20005. })(BABYLON.PostProcess);
  20006. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  20007. })(BABYLON || (BABYLON = {}));
  20008. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  20009. var BABYLON;
  20010. (function (BABYLON) {
  20011. var Tags = (function () {
  20012. function Tags() {
  20013. }
  20014. Tags.EnableFor = function (obj) {
  20015. obj._tags = obj._tags || {};
  20016. obj.hasTags = function () {
  20017. return Tags.HasTags(obj);
  20018. };
  20019. obj.addTags = function (tagsString) {
  20020. return Tags.AddTagsTo(obj, tagsString);
  20021. };
  20022. obj.removeTags = function (tagsString) {
  20023. return Tags.RemoveTagsFrom(obj, tagsString);
  20024. };
  20025. obj.matchesTagsQuery = function (tagsQuery) {
  20026. return Tags.MatchesQuery(obj, tagsQuery);
  20027. };
  20028. };
  20029. Tags.DisableFor = function (obj) {
  20030. delete obj._tags;
  20031. delete obj.hasTags;
  20032. delete obj.addTags;
  20033. delete obj.removeTags;
  20034. delete obj.matchesTagsQuery;
  20035. };
  20036. Tags.HasTags = function (obj) {
  20037. if (!obj._tags) {
  20038. return false;
  20039. }
  20040. return !BABYLON.Tools.IsEmpty(obj._tags);
  20041. };
  20042. Tags.GetTags = function (obj) {
  20043. if (!obj._tags) {
  20044. return null;
  20045. }
  20046. return obj._tags;
  20047. };
  20048. // the tags 'true' and 'false' are reserved and cannot be used as tags
  20049. // a tag cannot start with '||', '&&', and '!'
  20050. // it cannot contain whitespaces
  20051. Tags.AddTagsTo = function (obj, tagsString) {
  20052. if (!tagsString) {
  20053. return;
  20054. }
  20055. var tags = tagsString.split(" ");
  20056. for (var t in tags) {
  20057. Tags._AddTagTo(obj, tags[t]);
  20058. }
  20059. };
  20060. Tags._AddTagTo = function (obj, tag) {
  20061. tag = tag.trim();
  20062. if (tag === "" || tag === "true" || tag === "false") {
  20063. return;
  20064. }
  20065. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  20066. return;
  20067. }
  20068. Tags.EnableFor(obj);
  20069. obj._tags[tag] = true;
  20070. };
  20071. Tags.RemoveTagsFrom = function (obj, tagsString) {
  20072. if (!Tags.HasTags(obj)) {
  20073. return;
  20074. }
  20075. var tags = tagsString.split(" ");
  20076. for (var t in tags) {
  20077. Tags._RemoveTagFrom(obj, tags[t]);
  20078. }
  20079. };
  20080. Tags._RemoveTagFrom = function (obj, tag) {
  20081. delete obj._tags[tag];
  20082. };
  20083. Tags.MatchesQuery = function (obj, tagsQuery) {
  20084. if (tagsQuery === undefined) {
  20085. return true;
  20086. }
  20087. if (tagsQuery === "") {
  20088. return Tags.HasTags(obj);
  20089. }
  20090. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) {
  20091. return Tags.HasTags(obj) && obj._tags[r];
  20092. });
  20093. };
  20094. return Tags;
  20095. })();
  20096. BABYLON.Tags = Tags;
  20097. })(BABYLON || (BABYLON = {}));
  20098. //# sourceMappingURL=babylon.tags.js.map
  20099. var BABYLON;
  20100. (function (BABYLON) {
  20101. (function (Internals) {
  20102. var AndOrNotEvaluator = (function () {
  20103. function AndOrNotEvaluator() {
  20104. }
  20105. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  20106. if (!query.match(/\([^\(\)]*\)/g)) {
  20107. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  20108. } else {
  20109. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  20110. // remove parenthesis
  20111. r = r.slice(1, r.length - 1);
  20112. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  20113. });
  20114. }
  20115. if (query === "true") {
  20116. return true;
  20117. }
  20118. if (query === "false") {
  20119. return false;
  20120. }
  20121. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  20122. };
  20123. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  20124. evaluateCallback = evaluateCallback || (function (r) {
  20125. return r === "true" ? true : false;
  20126. });
  20127. var result;
  20128. var or = parenthesisContent.split("||");
  20129. for (var i in or) {
  20130. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  20131. var and = ori.split("&&");
  20132. if (and.length > 1) {
  20133. for (var j = 0; j < and.length; ++j) {
  20134. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  20135. if (andj !== "true" && andj !== "false") {
  20136. if (andj[0] === "!") {
  20137. result = !evaluateCallback(andj.substring(1));
  20138. } else {
  20139. result = evaluateCallback(andj);
  20140. }
  20141. } else {
  20142. result = andj === "true" ? true : false;
  20143. }
  20144. if (!result) {
  20145. ori = "false";
  20146. break;
  20147. }
  20148. }
  20149. }
  20150. if (result || ori === "true") {
  20151. result = true;
  20152. break;
  20153. }
  20154. // result equals false (or undefined)
  20155. if (ori !== "true" && ori !== "false") {
  20156. if (ori[0] === "!") {
  20157. result = !evaluateCallback(ori.substring(1));
  20158. } else {
  20159. result = evaluateCallback(ori);
  20160. }
  20161. } else {
  20162. result = ori === "true" ? true : false;
  20163. }
  20164. }
  20165. // the whole parenthesis scope is replaced by 'true' or 'false'
  20166. return result ? "true" : "false";
  20167. };
  20168. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  20169. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  20170. // remove whitespaces
  20171. r = r.replace(/[\s]/g, function () {
  20172. return "";
  20173. });
  20174. return r.length % 2 ? "!" : "";
  20175. });
  20176. booleanString = booleanString.trim();
  20177. if (booleanString === "!true") {
  20178. booleanString = "false";
  20179. } else if (booleanString === "!false") {
  20180. booleanString = "true";
  20181. }
  20182. return booleanString;
  20183. };
  20184. return AndOrNotEvaluator;
  20185. })();
  20186. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  20187. })(BABYLON.Internals || (BABYLON.Internals = {}));
  20188. var Internals = BABYLON.Internals;
  20189. })(BABYLON || (BABYLON = {}));
  20190. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  20191. var BABYLON;
  20192. (function (BABYLON) {
  20193. var PostProcessRenderPass = (function () {
  20194. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  20195. this._enabled = true;
  20196. this._refCount = 0;
  20197. this._name = name;
  20198. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  20199. this.setRenderList(renderList);
  20200. this._renderTexture.onBeforeRender = beforeRender;
  20201. this._renderTexture.onAfterRender = afterRender;
  20202. this._scene = scene;
  20203. this._renderList = renderList;
  20204. }
  20205. // private
  20206. PostProcessRenderPass.prototype._incRefCount = function () {
  20207. if (this._refCount === 0) {
  20208. this._scene.customRenderTargets.push(this._renderTexture);
  20209. }
  20210. return ++this._refCount;
  20211. };
  20212. PostProcessRenderPass.prototype._decRefCount = function () {
  20213. this._refCount--;
  20214. if (this._refCount <= 0) {
  20215. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  20216. }
  20217. return this._refCount;
  20218. };
  20219. PostProcessRenderPass.prototype._update = function () {
  20220. this.setRenderList(this._renderList);
  20221. };
  20222. // public
  20223. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  20224. this._renderTexture.renderList = renderList;
  20225. };
  20226. PostProcessRenderPass.prototype.getRenderTexture = function () {
  20227. return this._renderTexture;
  20228. };
  20229. return PostProcessRenderPass;
  20230. })();
  20231. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  20232. })(BABYLON || (BABYLON = {}));
  20233. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  20234. var BABYLON;
  20235. (function (BABYLON) {
  20236. var PostProcessRenderEffect = (function () {
  20237. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  20238. this._engine = engine;
  20239. this._name = name;
  20240. this._singleInstance = singleInstance || true;
  20241. this._getPostProcess = getPostProcess;
  20242. this._cameras = [];
  20243. this._indicesForCamera = [];
  20244. this._postProcesses = {};
  20245. this._renderPasses = {};
  20246. this._renderEffectAsPasses = {};
  20247. }
  20248. PostProcessRenderEffect.prototype._update = function () {
  20249. for (var renderPassName in this._renderPasses) {
  20250. this._renderPasses[renderPassName]._update();
  20251. }
  20252. };
  20253. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  20254. this._renderPasses[renderPass._name] = renderPass;
  20255. this._linkParameters();
  20256. };
  20257. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  20258. delete this._renderPasses[renderPass._name];
  20259. this._linkParameters();
  20260. };
  20261. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  20262. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  20263. this._linkParameters();
  20264. };
  20265. PostProcessRenderEffect.prototype.getPass = function (passName) {
  20266. for (var renderPassName in this._renderPasses) {
  20267. if (renderPassName === passName) {
  20268. return this._renderPasses[passName];
  20269. }
  20270. }
  20271. };
  20272. PostProcessRenderEffect.prototype.emptyPasses = function () {
  20273. this._renderPasses = {};
  20274. this._linkParameters();
  20275. };
  20276. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  20277. var cameraKey;
  20278. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  20279. for (var i = 0; i < _cam.length; i++) {
  20280. var camera = _cam[i];
  20281. var cameraName = camera.name;
  20282. if (this._singleInstance) {
  20283. cameraKey = 0;
  20284. } else {
  20285. cameraKey = cameraName;
  20286. }
  20287. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  20288. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  20289. if (!this._indicesForCamera[cameraName]) {
  20290. this._indicesForCamera[cameraName] = [];
  20291. }
  20292. this._indicesForCamera[cameraName].push(index);
  20293. if (this._cameras.indexOf(camera) === -1) {
  20294. this._cameras[cameraName] = camera;
  20295. }
  20296. for (var passName in this._renderPasses) {
  20297. this._renderPasses[passName]._incRefCount();
  20298. }
  20299. }
  20300. this._linkParameters();
  20301. };
  20302. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  20303. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  20304. for (var i = 0; i < _cam.length; i++) {
  20305. var camera = _cam[i];
  20306. var cameraName = camera.name;
  20307. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  20308. var index = this._cameras.indexOf(cameraName);
  20309. this._indicesForCamera.splice(index, 1);
  20310. this._cameras.splice(index, 1);
  20311. for (var passName in this._renderPasses) {
  20312. this._renderPasses[passName]._decRefCount();
  20313. }
  20314. }
  20315. };
  20316. PostProcessRenderEffect.prototype._enable = function (cameras) {
  20317. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  20318. for (var i = 0; i < _cam.length; i++) {
  20319. var camera = _cam[i];
  20320. var cameraName = camera.name;
  20321. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  20322. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  20323. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  20324. }
  20325. }
  20326. for (var passName in this._renderPasses) {
  20327. this._renderPasses[passName]._incRefCount();
  20328. }
  20329. }
  20330. };
  20331. PostProcessRenderEffect.prototype._disable = function (cameras) {
  20332. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  20333. for (var i = 0; i < _cam.length; i++) {
  20334. var camera = _cam[i];
  20335. var cameraName = camera.Name;
  20336. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  20337. for (var passName in this._renderPasses) {
  20338. this._renderPasses[passName]._decRefCount();
  20339. }
  20340. }
  20341. };
  20342. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  20343. if (this._singleInstance) {
  20344. return this._postProcesses[0];
  20345. } else {
  20346. return this._postProcesses[camera.name];
  20347. }
  20348. };
  20349. PostProcessRenderEffect.prototype._linkParameters = function () {
  20350. var _this = this;
  20351. for (var index in this._postProcesses) {
  20352. if (this.applyParameters) {
  20353. this.applyParameters(this._postProcesses[index]);
  20354. }
  20355. this._postProcesses[index].onBeforeRender = function (effect) {
  20356. _this._linkTextures(effect);
  20357. };
  20358. }
  20359. };
  20360. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  20361. for (var renderPassName in this._renderPasses) {
  20362. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  20363. }
  20364. for (var renderEffectName in this._renderEffectAsPasses) {
  20365. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  20366. }
  20367. };
  20368. return PostProcessRenderEffect;
  20369. })();
  20370. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  20371. })(BABYLON || (BABYLON = {}));
  20372. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  20373. var BABYLON;
  20374. (function (BABYLON) {
  20375. var PostProcessRenderPipeline = (function () {
  20376. function PostProcessRenderPipeline(engine, name) {
  20377. this._engine = engine;
  20378. this._name = name;
  20379. this._renderEffects = {};
  20380. this._renderEffectsForIsolatedPass = {};
  20381. this._cameras = [];
  20382. }
  20383. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  20384. this._renderEffects[renderEffect._name] = renderEffect;
  20385. };
  20386. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  20387. var renderEffects = this._renderEffects[renderEffectName];
  20388. if (!renderEffects) {
  20389. return;
  20390. }
  20391. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  20392. };
  20393. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  20394. var renderEffects = this._renderEffects[renderEffectName];
  20395. if (!renderEffects) {
  20396. return;
  20397. }
  20398. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  20399. };
  20400. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  20401. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  20402. var indicesToDelete = [];
  20403. for (var i = 0; i < _cam.length; i++) {
  20404. var camera = _cam[i];
  20405. var cameraName = camera.name;
  20406. if (this._cameras.indexOf(camera) === -1) {
  20407. this._cameras[cameraName] = camera;
  20408. } else if (unique) {
  20409. indicesToDelete.push(i);
  20410. }
  20411. }
  20412. for (var i = 0; i < indicesToDelete.length; i++) {
  20413. cameras.splice(indicesToDelete[i], 1);
  20414. }
  20415. for (var renderEffectName in this._renderEffects) {
  20416. this._renderEffects[renderEffectName]._attachCameras(_cam);
  20417. }
  20418. };
  20419. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  20420. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  20421. for (var renderEffectName in this._renderEffects) {
  20422. this._renderEffects[renderEffectName]._detachCameras(_cam);
  20423. }
  20424. for (var i = 0; i < _cam.length; i++) {
  20425. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  20426. }
  20427. };
  20428. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  20429. var _this = this;
  20430. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  20431. var pass = null;
  20432. for (var renderEffectName in this._renderEffects) {
  20433. pass = this._renderEffects[renderEffectName].getPass(passName);
  20434. if (pass != null) {
  20435. break;
  20436. }
  20437. }
  20438. if (pass === null) {
  20439. return;
  20440. }
  20441. for (var renderEffectName in this._renderEffects) {
  20442. this._renderEffects[renderEffectName]._disable(_cam);
  20443. }
  20444. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  20445. for (var i = 0; i < _cam.length; i++) {
  20446. var camera = _cam[i];
  20447. var cameraName = camera.name;
  20448. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  20449. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  20450. });
  20451. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  20452. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  20453. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  20454. }
  20455. };
  20456. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  20457. var _this = this;
  20458. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  20459. for (var i = 0; i < _cam.length; i++) {
  20460. var camera = _cam[i];
  20461. var cameraName = camera.name;
  20462. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  20463. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  20464. });
  20465. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  20466. }
  20467. for (var renderEffectName in this._renderEffects) {
  20468. this._renderEffects[renderEffectName]._enable(_cam);
  20469. }
  20470. };
  20471. PostProcessRenderPipeline.prototype._update = function () {
  20472. for (var renderEffectName in this._renderEffects) {
  20473. this._renderEffects[renderEffectName]._update();
  20474. }
  20475. for (var i = 0; i < this._cameras.length; i++) {
  20476. var cameraName = this._cameras[i].name;
  20477. if (this._renderEffectsForIsolatedPass[cameraName]) {
  20478. this._renderEffectsForIsolatedPass[cameraName]._update();
  20479. }
  20480. }
  20481. };
  20482. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  20483. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  20484. return PostProcessRenderPipeline;
  20485. })();
  20486. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  20487. })(BABYLON || (BABYLON = {}));
  20488. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  20489. var BABYLON;
  20490. (function (BABYLON) {
  20491. var PostProcessRenderPipelineManager = (function () {
  20492. function PostProcessRenderPipelineManager() {
  20493. this._renderPipelines = {};
  20494. }
  20495. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  20496. this._renderPipelines[renderPipeline._name] = renderPipeline;
  20497. };
  20498. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  20499. var renderPipeline = this._renderPipelines[renderPipelineName];
  20500. if (!renderPipeline) {
  20501. return;
  20502. }
  20503. renderPipeline._attachCameras(cameras, unique);
  20504. };
  20505. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  20506. var renderPipeline = this._renderPipelines[renderPipelineName];
  20507. if (!renderPipeline) {
  20508. return;
  20509. }
  20510. renderPipeline._detachCameras(cameras);
  20511. };
  20512. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  20513. var renderPipeline = this._renderPipelines[renderPipelineName];
  20514. if (!renderPipeline) {
  20515. return;
  20516. }
  20517. renderPipeline._enableEffect(renderEffectName, cameras);
  20518. };
  20519. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  20520. var renderPipeline = this._renderPipelines[renderPipelineName];
  20521. if (!renderPipeline) {
  20522. return;
  20523. }
  20524. renderPipeline._disableEffect(renderEffectName, cameras);
  20525. };
  20526. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  20527. var renderPipeline = this._renderPipelines[renderPipelineName];
  20528. if (!renderPipeline) {
  20529. return;
  20530. }
  20531. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  20532. };
  20533. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  20534. var renderPipeline = this._renderPipelines[renderPipelineName];
  20535. if (!renderPipeline) {
  20536. return;
  20537. }
  20538. renderPipeline._disableDisplayOnlyPass(cameras);
  20539. };
  20540. PostProcessRenderPipelineManager.prototype.update = function () {
  20541. for (var renderPipelineName in this._renderPipelines) {
  20542. this._renderPipelines[renderPipelineName]._update();
  20543. }
  20544. };
  20545. return PostProcessRenderPipelineManager;
  20546. })();
  20547. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  20548. })(BABYLON || (BABYLON = {}));
  20549. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  20550. var BABYLON;
  20551. (function (BABYLON) {
  20552. var DisplayPassPostProcess = (function (_super) {
  20553. __extends(DisplayPassPostProcess, _super);
  20554. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  20555. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  20556. }
  20557. return DisplayPassPostProcess;
  20558. })(BABYLON.PostProcess);
  20559. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  20560. })(BABYLON || (BABYLON = {}));
  20561. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  20562. var BABYLON;
  20563. (function (BABYLON) {
  20564. var BoundingBoxRenderer = (function () {
  20565. function BoundingBoxRenderer(scene) {
  20566. this.frontColor = new BABYLON.Color3(1, 1, 1);
  20567. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  20568. this.showBackLines = true;
  20569. this.renderList = new BABYLON.SmartArray(32);
  20570. this._scene = scene;
  20571. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  20572. attributes: ["position"],
  20573. uniforms: ["worldViewProjection", "color"]
  20574. });
  20575. var engine = this._scene.getEngine();
  20576. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  20577. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  20578. 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]);
  20579. }
  20580. BoundingBoxRenderer.prototype.reset = function () {
  20581. this.renderList.reset();
  20582. };
  20583. BoundingBoxRenderer.prototype.render = function () {
  20584. if (this.renderList.length === 0 || !this._colorShader.isReady()) {
  20585. return;
  20586. }
  20587. var engine = this._scene.getEngine();
  20588. engine.setDepthWrite(false);
  20589. this._colorShader._preBind();
  20590. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  20591. var boundingBox = this.renderList.data[boundingBoxIndex];
  20592. var min = boundingBox.minimum;
  20593. var max = boundingBox.maximum;
  20594. var diff = max.subtract(min);
  20595. var median = min.add(diff.scale(0.5));
  20596. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z).multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z)).multiply(boundingBox.getWorldMatrix());
  20597. // VBOs
  20598. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  20599. if (this.showBackLines) {
  20600. // Back
  20601. engine.setDepthFunctionToGreaterOrEqual();
  20602. this._scene.resetCachedMaterial();
  20603. this._colorShader.setColor4("color", this.backColor.toColor4());
  20604. this._colorShader.bind(worldMatrix);
  20605. // Draw order
  20606. engine.draw(false, 0, 24);
  20607. }
  20608. // Front
  20609. engine.setDepthFunctionToLess();
  20610. this._scene.resetCachedMaterial();
  20611. this._colorShader.setColor4("color", this.frontColor.toColor4());
  20612. this._colorShader.bind(worldMatrix);
  20613. // Draw order
  20614. engine.draw(false, 0, 24);
  20615. }
  20616. this._colorShader.unbind();
  20617. engine.setDepthFunctionToLessOrEqual();
  20618. engine.setDepthWrite(true);
  20619. };
  20620. BoundingBoxRenderer.prototype.dispose = function () {
  20621. this._colorShader.dispose();
  20622. this._vb.dispose();
  20623. this._scene.getEngine()._releaseBuffer(this._ib);
  20624. };
  20625. return BoundingBoxRenderer;
  20626. })();
  20627. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  20628. })(BABYLON || (BABYLON = {}));
  20629. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  20630. /**
  20631. * Based on jsTGALoader - Javascript loader for TGA file
  20632. * By Vincent Thibault
  20633. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  20634. */
  20635. var BABYLON;
  20636. (function (BABYLON) {
  20637. (function (Internals) {
  20638. var TGATools = (function () {
  20639. function TGATools() {
  20640. }
  20641. TGATools.GetTGAHeader = function (data) {
  20642. var offset = 0;
  20643. var header = {
  20644. id_length: data[offset++],
  20645. colormap_type: data[offset++],
  20646. image_type: data[offset++],
  20647. colormap_index: data[offset++] | data[offset++] << 8,
  20648. colormap_length: data[offset++] | data[offset++] << 8,
  20649. colormap_size: data[offset++],
  20650. origin: [
  20651. data[offset++] | data[offset++] << 8,
  20652. data[offset++] | data[offset++] << 8
  20653. ],
  20654. width: data[offset++] | data[offset++] << 8,
  20655. height: data[offset++] | data[offset++] << 8,
  20656. pixel_size: data[offset++],
  20657. flags: data[offset++]
  20658. };
  20659. return header;
  20660. };
  20661. TGATools.UploadContent = function (gl, data) {
  20662. // Not enough data to contain header ?
  20663. if (data.length < 19) {
  20664. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  20665. return;
  20666. }
  20667. // Read Header
  20668. var offset = 18;
  20669. var header = TGATools.GetTGAHeader(data);
  20670. // Assume it's a valid Targa file.
  20671. if (header.id_length + offset > data.length) {
  20672. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  20673. return;
  20674. }
  20675. // Skip not needed data
  20676. offset += header.id_length;
  20677. var use_rle = false;
  20678. var use_pal = false;
  20679. var use_rgb = false;
  20680. var use_grey = false;
  20681. switch (header.image_type) {
  20682. case TGATools._TYPE_RLE_INDEXED:
  20683. use_rle = true;
  20684. case TGATools._TYPE_INDEXED:
  20685. use_pal = true;
  20686. break;
  20687. case TGATools._TYPE_RLE_RGB:
  20688. use_rle = true;
  20689. case TGATools._TYPE_RGB:
  20690. use_rgb = true;
  20691. break;
  20692. case TGATools._TYPE_RLE_GREY:
  20693. use_rle = true;
  20694. case TGATools._TYPE_GREY:
  20695. use_grey = true;
  20696. break;
  20697. }
  20698. var pixel_data;
  20699. var numAlphaBits = header.flags & 0xf;
  20700. var pixel_size = header.pixel_size >> 3;
  20701. var pixel_total = header.width * header.height * pixel_size;
  20702. // Read palettes
  20703. var palettes;
  20704. if (use_pal) {
  20705. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  20706. }
  20707. // Read LRE
  20708. if (use_rle) {
  20709. pixel_data = new Uint8Array(pixel_total);
  20710. var c, count, i;
  20711. var localOffset = 0;
  20712. var pixels = new Uint8Array(pixel_size);
  20713. while (offset < pixel_total && localOffset < pixel_total) {
  20714. c = data[offset++];
  20715. count = (c & 0x7f) + 1;
  20716. // RLE pixels
  20717. if (c & 0x80) {
  20718. for (i = 0; i < pixel_size; ++i) {
  20719. pixels[i] = data[offset++];
  20720. }
  20721. for (i = 0; i < count; ++i) {
  20722. pixel_data.set(pixels, localOffset + i * pixel_size);
  20723. }
  20724. localOffset += pixel_size * count;
  20725. } else {
  20726. count *= pixel_size;
  20727. for (i = 0; i < count; ++i) {
  20728. pixel_data[localOffset + i] = data[offset++];
  20729. }
  20730. localOffset += count;
  20731. }
  20732. }
  20733. } else {
  20734. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  20735. }
  20736. // Load to texture
  20737. var x_start, y_start, x_step, y_step, y_end, x_end;
  20738. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  20739. default:
  20740. case TGATools._ORIGIN_UL:
  20741. x_start = 0;
  20742. x_step = 1;
  20743. x_end = header.width;
  20744. y_start = 0;
  20745. y_step = 1;
  20746. y_end = header.height;
  20747. break;
  20748. case TGATools._ORIGIN_BL:
  20749. x_start = 0;
  20750. x_step = 1;
  20751. x_end = header.width;
  20752. y_start = header.height - 1;
  20753. y_step = -1;
  20754. y_end = -1;
  20755. break;
  20756. case TGATools._ORIGIN_UR:
  20757. x_start = header.width - 1;
  20758. x_step = -1;
  20759. x_end = -1;
  20760. y_start = 0;
  20761. y_step = 1;
  20762. y_end = header.height;
  20763. break;
  20764. case TGATools._ORIGIN_BR:
  20765. x_start = header.width - 1;
  20766. x_step = -1;
  20767. x_end = -1;
  20768. y_start = header.height - 1;
  20769. y_step = -1;
  20770. y_end = -1;
  20771. break;
  20772. }
  20773. // Load the specify method
  20774. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  20775. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  20776. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  20777. };
  20778. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  20779. var image = pixel_data, colormap = palettes;
  20780. var width = header.width, height = header.height;
  20781. var color, i = 0, x, y;
  20782. var imageData = new Uint8Array(width * height * 4);
  20783. for (y = y_start; y !== y_end; y += y_step) {
  20784. for (x = x_start; x !== x_end; x += x_step, i++) {
  20785. color = image[i];
  20786. imageData[(x + width * y) * 4 + 3] = 255;
  20787. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  20788. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  20789. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  20790. }
  20791. }
  20792. return imageData;
  20793. };
  20794. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  20795. var image = pixel_data;
  20796. var width = header.width, height = header.height;
  20797. var color, i = 0, x, y;
  20798. var imageData = new Uint8Array(width * height * 4);
  20799. for (y = y_start; y !== y_end; y += y_step) {
  20800. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  20801. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  20802. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  20803. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  20804. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  20805. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  20806. }
  20807. }
  20808. return imageData;
  20809. };
  20810. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  20811. var image = pixel_data;
  20812. var width = header.width, height = header.height;
  20813. var i = 0, x, y;
  20814. var imageData = new Uint8Array(width * height * 4);
  20815. for (y = y_start; y !== y_end; y += y_step) {
  20816. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  20817. imageData[(x + width * y) * 4 + 3] = 255;
  20818. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  20819. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  20820. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  20821. }
  20822. }
  20823. return imageData;
  20824. };
  20825. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  20826. var image = pixel_data;
  20827. var width = header.width, height = header.height;
  20828. var i = 0, x, y;
  20829. var imageData = new Uint8Array(width * height * 4);
  20830. for (y = y_start; y !== y_end; y += y_step) {
  20831. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  20832. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  20833. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  20834. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  20835. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  20836. }
  20837. }
  20838. return imageData;
  20839. };
  20840. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  20841. var image = pixel_data;
  20842. var width = header.width, height = header.height;
  20843. var color, i = 0, x, y;
  20844. var imageData = new Uint8Array(width * height * 4);
  20845. for (y = y_start; y !== y_end; y += y_step) {
  20846. for (x = x_start; x !== x_end; x += x_step, i++) {
  20847. color = image[i];
  20848. imageData[(x + width * y) * 4 + 0] = color;
  20849. imageData[(x + width * y) * 4 + 1] = color;
  20850. imageData[(x + width * y) * 4 + 2] = color;
  20851. imageData[(x + width * y) * 4 + 3] = 255;
  20852. }
  20853. }
  20854. return imageData;
  20855. };
  20856. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  20857. var image = pixel_data;
  20858. var width = header.width, height = header.height;
  20859. var i = 0, x, y;
  20860. var imageData = new Uint8Array(width * height * 4);
  20861. for (y = y_start; y !== y_end; y += y_step) {
  20862. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  20863. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  20864. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  20865. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  20866. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  20867. }
  20868. }
  20869. return imageData;
  20870. };
  20871. TGATools._TYPE_NO_DATA = 0;
  20872. TGATools._TYPE_INDEXED = 1;
  20873. TGATools._TYPE_RGB = 2;
  20874. TGATools._TYPE_GREY = 3;
  20875. TGATools._TYPE_RLE_INDEXED = 9;
  20876. TGATools._TYPE_RLE_RGB = 10;
  20877. TGATools._TYPE_RLE_GREY = 11;
  20878. TGATools._ORIGIN_MASK = 0x30;
  20879. TGATools._ORIGIN_SHIFT = 0x04;
  20880. TGATools._ORIGIN_BL = 0x00;
  20881. TGATools._ORIGIN_BR = 0x01;
  20882. TGATools._ORIGIN_UL = 0x02;
  20883. TGATools._ORIGIN_UR = 0x03;
  20884. return TGATools;
  20885. })();
  20886. Internals.TGATools = TGATools;
  20887. })(BABYLON.Internals || (BABYLON.Internals = {}));
  20888. var Internals = BABYLON.Internals;
  20889. })(BABYLON || (BABYLON = {}));
  20890. //# sourceMappingURL=babylon.tools.tga.js.map
  20891. var BABYLON;
  20892. (function (BABYLON) {
  20893. (function (Internals) {
  20894. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  20895. // All values and structures referenced from:
  20896. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  20897. var DDS_MAGIC = 0x20534444;
  20898. 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;
  20899. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  20900. 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;
  20901. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  20902. function FourCCToInt32(value) {
  20903. return value.charCodeAt(0) + (value.charCodeAt(1) << 8) + (value.charCodeAt(2) << 16) + (value.charCodeAt(3) << 24);
  20904. }
  20905. function Int32ToFourCC(value) {
  20906. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  20907. }
  20908. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  20909. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  20910. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  20911. var headerLengthInt = 31;
  20912. // Offsets into the header array
  20913. var off_magic = 0;
  20914. var off_size = 1;
  20915. var off_flags = 2;
  20916. var off_height = 3;
  20917. var off_width = 4;
  20918. var off_mipmapCount = 7;
  20919. var off_pfFlags = 20;
  20920. var off_pfFourCC = 21;
  20921. var off_RGBbpp = 22;
  20922. var off_RMask = 23;
  20923. var off_GMask = 24;
  20924. var off_BMask = 25;
  20925. var off_AMask = 26;
  20926. var off_caps1 = 27;
  20927. var off_caps2 = 28;
  20928. ;
  20929. var DDSTools = (function () {
  20930. function DDSTools() {
  20931. }
  20932. DDSTools.GetDDSInfo = function (arrayBuffer) {
  20933. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  20934. var mipmapCount = 1;
  20935. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  20936. mipmapCount = Math.max(1, header[off_mipmapCount]);
  20937. }
  20938. return {
  20939. width: header[off_width],
  20940. height: header[off_height],
  20941. mipmapCount: mipmapCount,
  20942. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  20943. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  20944. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  20945. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  20946. };
  20947. };
  20948. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  20949. var byteArray = new Uint8Array(dataLength);
  20950. var srcData = new Uint8Array(arrayBuffer);
  20951. var index = 0;
  20952. for (var y = height - 1; y >= 0; y--) {
  20953. for (var x = 0; x < width; x++) {
  20954. var srcPos = dataOffset + (x + y * width) * 4;
  20955. byteArray[index + 2] = srcData[srcPos];
  20956. byteArray[index + 1] = srcData[srcPos + 1];
  20957. byteArray[index] = srcData[srcPos + 2];
  20958. byteArray[index + 3] = srcData[srcPos + 3];
  20959. index += 4;
  20960. }
  20961. }
  20962. return byteArray;
  20963. };
  20964. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  20965. var byteArray = new Uint8Array(dataLength);
  20966. var srcData = new Uint8Array(arrayBuffer);
  20967. var index = 0;
  20968. for (var y = height - 1; y >= 0; y--) {
  20969. for (var x = 0; x < width; x++) {
  20970. var srcPos = dataOffset + (x + y * width) * 3;
  20971. byteArray[index + 2] = srcData[srcPos];
  20972. byteArray[index + 1] = srcData[srcPos + 1];
  20973. byteArray[index] = srcData[srcPos + 2];
  20974. index += 3;
  20975. }
  20976. }
  20977. return byteArray;
  20978. };
  20979. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  20980. var byteArray = new Uint8Array(dataLength);
  20981. var srcData = new Uint8Array(arrayBuffer);
  20982. var index = 0;
  20983. for (var y = height - 1; y >= 0; y--) {
  20984. for (var x = 0; x < width; x++) {
  20985. var srcPos = dataOffset + (x + y * width);
  20986. byteArray[index] = srcData[srcPos];
  20987. index++;
  20988. }
  20989. }
  20990. return byteArray;
  20991. };
  20992. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  20993. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  20994. if (header[off_magic] != DDS_MAGIC) {
  20995. BABYLON.Tools.Error("Invalid magic number in DDS header");
  20996. return;
  20997. }
  20998. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  20999. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  21000. return;
  21001. }
  21002. if (info.isFourCC) {
  21003. fourCC = header[off_pfFourCC];
  21004. switch (fourCC) {
  21005. case FOURCC_DXT1:
  21006. blockBytes = 8;
  21007. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  21008. break;
  21009. case FOURCC_DXT3:
  21010. blockBytes = 16;
  21011. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  21012. break;
  21013. case FOURCC_DXT5:
  21014. blockBytes = 16;
  21015. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  21016. break;
  21017. default:
  21018. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  21019. return;
  21020. }
  21021. }
  21022. mipmapCount = 1;
  21023. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  21024. mipmapCount = Math.max(1, header[off_mipmapCount]);
  21025. }
  21026. var bpp = header[off_RGBbpp];
  21027. for (var face = 0; face < faces; face++) {
  21028. var sampler = faces == 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  21029. width = header[off_width];
  21030. height = header[off_height];
  21031. dataOffset = header[off_size] + 4;
  21032. for (i = 0; i < mipmapCount; ++i) {
  21033. if (info.isRGB) {
  21034. if (bpp == 24) {
  21035. dataLength = width * height * 3;
  21036. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  21037. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  21038. } else {
  21039. dataLength = width * height * 4;
  21040. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  21041. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  21042. }
  21043. } else if (info.isLuminance) {
  21044. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  21045. var unpaddedRowSize = width;
  21046. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  21047. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  21048. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  21049. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  21050. } else {
  21051. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  21052. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  21053. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  21054. }
  21055. dataOffset += dataLength;
  21056. width *= 0.5;
  21057. height *= 0.5;
  21058. width = Math.max(1.0, width);
  21059. height = Math.max(1.0, height);
  21060. }
  21061. }
  21062. };
  21063. return DDSTools;
  21064. })();
  21065. Internals.DDSTools = DDSTools;
  21066. })(BABYLON.Internals || (BABYLON.Internals = {}));
  21067. var Internals = BABYLON.Internals;
  21068. })(BABYLON || (BABYLON = {}));
  21069. //# sourceMappingURL=babylon.tools.dds.js.map
  21070. var BABYLON;
  21071. (function (BABYLON) {
  21072. var SmartArray = (function () {
  21073. function SmartArray(capacity) {
  21074. this.length = 0;
  21075. this._duplicateId = 0;
  21076. this.data = new Array(capacity);
  21077. this._id = SmartArray._GlobalId++;
  21078. }
  21079. SmartArray.prototype.push = function (value) {
  21080. this.data[this.length++] = value;
  21081. if (this.length > this.data.length) {
  21082. this.data.length *= 2;
  21083. }
  21084. if (!value.__smartArrayFlags) {
  21085. value.__smartArrayFlags = {};
  21086. }
  21087. value.__smartArrayFlags[this._id] = this._duplicateId;
  21088. };
  21089. SmartArray.prototype.pushNoDuplicate = function (value) {
  21090. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  21091. return;
  21092. }
  21093. this.push(value);
  21094. };
  21095. SmartArray.prototype.sort = function (compareFn) {
  21096. this.data.sort(compareFn);
  21097. };
  21098. SmartArray.prototype.reset = function () {
  21099. this.length = 0;
  21100. this._duplicateId++;
  21101. };
  21102. SmartArray.prototype.concat = function (array) {
  21103. if (array.length === 0) {
  21104. return;
  21105. }
  21106. if (this.length + array.length > this.data.length) {
  21107. this.data.length = (this.length + array.length) * 2;
  21108. }
  21109. for (var index = 0; index < array.length; index++) {
  21110. this.data[this.length++] = (array.data || array)[index];
  21111. }
  21112. };
  21113. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  21114. if (array.length === 0) {
  21115. return;
  21116. }
  21117. if (this.length + array.length > this.data.length) {
  21118. this.data.length = (this.length + array.length) * 2;
  21119. }
  21120. for (var index = 0; index < array.length; index++) {
  21121. var item = (array.data || array)[index];
  21122. this.pushNoDuplicate(item);
  21123. }
  21124. };
  21125. SmartArray.prototype.indexOf = function (value) {
  21126. var position = this.data.indexOf(value);
  21127. if (position >= this.length) {
  21128. return -1;
  21129. }
  21130. return position;
  21131. };
  21132. SmartArray._GlobalId = 0;
  21133. return SmartArray;
  21134. })();
  21135. BABYLON.SmartArray = SmartArray;
  21136. })(BABYLON || (BABYLON = {}));
  21137. //# sourceMappingURL=babylon.smartArray.js.map
  21138. var BABYLON;
  21139. (function (BABYLON) {
  21140. var CannonJSPlugin = (function () {
  21141. function CannonJSPlugin() {
  21142. this._registeredMeshes = [];
  21143. this._physicsMaterials = [];
  21144. this.updateBodyPosition = function (mesh) {
  21145. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21146. var registeredMesh = this._registeredMeshes[index];
  21147. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  21148. var body = registeredMesh.body;
  21149. var center = mesh.getBoundingInfo().boundingBox.center;
  21150. body.position.set(center.x, center.z, center.y);
  21151. body.quaternion.x = mesh.rotationQuaternion.x;
  21152. body.quaternion.z = mesh.rotationQuaternion.y;
  21153. body.quaternion.y = mesh.rotationQuaternion.z;
  21154. body.quaternion.w = -mesh.rotationQuaternion.w;
  21155. return;
  21156. }
  21157. }
  21158. };
  21159. }
  21160. CannonJSPlugin.prototype.initialize = function (iterations) {
  21161. if (typeof iterations === "undefined") { iterations = 10; }
  21162. this._world = new CANNON.World();
  21163. this._world.broadphase = new CANNON.NaiveBroadphase();
  21164. this._world.solver.iterations = iterations;
  21165. };
  21166. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  21167. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  21168. };
  21169. CannonJSPlugin.prototype.runOneStep = function (delta) {
  21170. this._world.step(delta);
  21171. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21172. var registeredMesh = this._registeredMeshes[index];
  21173. if (registeredMesh.isChild) {
  21174. continue;
  21175. }
  21176. // Body position
  21177. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  21178. var deltaPos = registeredMesh.delta;
  21179. if (deltaPos) {
  21180. registeredMesh.mesh.position.x = bodyX + deltaPos.x;
  21181. registeredMesh.mesh.position.y = bodyZ + deltaPos.y;
  21182. registeredMesh.mesh.position.z = bodyY + deltaPos.z;
  21183. } else {
  21184. registeredMesh.mesh.position.x = bodyX;
  21185. registeredMesh.mesh.position.y = bodyZ;
  21186. registeredMesh.mesh.position.z = bodyY;
  21187. }
  21188. if (!registeredMesh.mesh.rotationQuaternion) {
  21189. registeredMesh.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  21190. }
  21191. registeredMesh.mesh.rotationQuaternion.x = registeredMesh.body.quaternion.x;
  21192. registeredMesh.mesh.rotationQuaternion.y = registeredMesh.body.quaternion.z;
  21193. registeredMesh.mesh.rotationQuaternion.z = registeredMesh.body.quaternion.y;
  21194. registeredMesh.mesh.rotationQuaternion.w = -registeredMesh.body.quaternion.w;
  21195. }
  21196. };
  21197. CannonJSPlugin.prototype.setGravity = function (gravity) {
  21198. this._world.gravity.set(gravity.x, gravity.z, gravity.y);
  21199. };
  21200. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  21201. this.unregisterMesh(mesh);
  21202. mesh.computeWorldMatrix(true);
  21203. switch (impostor) {
  21204. case BABYLON.PhysicsEngine.SphereImpostor:
  21205. var bbox = mesh.getBoundingInfo().boundingBox;
  21206. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  21207. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  21208. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  21209. return this._createSphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2, mesh, options);
  21210. case BABYLON.PhysicsEngine.BoxImpostor:
  21211. bbox = mesh.getBoundingInfo().boundingBox;
  21212. var min = bbox.minimumWorld;
  21213. var max = bbox.maximumWorld;
  21214. var box = max.subtract(min).scale(0.5);
  21215. return this._createBox(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z), mesh, options);
  21216. case BABYLON.PhysicsEngine.PlaneImpostor:
  21217. return this._createPlane(mesh, options);
  21218. case BABYLON.PhysicsEngine.MeshImpostor:
  21219. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21220. var rawFaces = mesh.getIndices();
  21221. return this._createConvexPolyhedron(rawVerts, rawFaces, mesh, options);
  21222. }
  21223. return null;
  21224. };
  21225. CannonJSPlugin.prototype._createSphere = function (radius, mesh, options) {
  21226. var shape = new CANNON.Sphere(radius);
  21227. if (!options) {
  21228. return shape;
  21229. }
  21230. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  21231. };
  21232. CannonJSPlugin.prototype._createBox = function (x, y, z, mesh, options) {
  21233. var shape = new CANNON.Box(new CANNON.Vec3(x, z, y));
  21234. if (!options) {
  21235. return shape;
  21236. }
  21237. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  21238. };
  21239. CannonJSPlugin.prototype._createPlane = function (mesh, options) {
  21240. var shape = new CANNON.Plane();
  21241. if (!options) {
  21242. return shape;
  21243. }
  21244. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  21245. };
  21246. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh, options) {
  21247. var verts = [], faces = [];
  21248. mesh.computeWorldMatrix(true);
  21249. for (var i = 0; i < rawVerts.length; i += 3) {
  21250. var transformed = BABYLON.Vector3.Zero();
  21251. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  21252. verts.push(new CANNON.Vec3(transformed.x, transformed.z, transformed.y));
  21253. }
  21254. for (var j = 0; j < rawFaces.length; j += 3) {
  21255. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  21256. }
  21257. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  21258. if (!options) {
  21259. return shape;
  21260. }
  21261. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  21262. };
  21263. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  21264. var index;
  21265. var mat;
  21266. for (index = 0; index < this._physicsMaterials.length; index++) {
  21267. mat = this._physicsMaterials[index];
  21268. if (mat.friction === friction && mat.restitution === restitution) {
  21269. return mat;
  21270. }
  21271. }
  21272. var currentMat = new CANNON.Material();
  21273. currentMat.friction = friction;
  21274. currentMat.restitution = restitution;
  21275. this._physicsMaterials.push(currentMat);
  21276. for (index = 0; index < this._physicsMaterials.length; index++) {
  21277. mat = this._physicsMaterials[index];
  21278. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, mat.friction * currentMat.friction, mat.restitution * currentMat.restitution);
  21279. contactMaterial.contactEquationStiffness = 1e10;
  21280. contactMaterial.contactEquationRegularizationTime = 10;
  21281. this._world.addContactMaterial(contactMaterial);
  21282. }
  21283. return currentMat;
  21284. };
  21285. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, mass, friction, restitution) {
  21286. var initialRotation = null;
  21287. if (mesh.rotationQuaternion) {
  21288. initialRotation = mesh.rotationQuaternion.clone();
  21289. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  21290. }
  21291. // The delta between the mesh position and the mesh bounding box center
  21292. var bbox = mesh.getBoundingInfo().boundingBox;
  21293. var deltaPosition = mesh.position.subtract(bbox.center);
  21294. var material = this._addMaterial(friction, restitution);
  21295. var body = new CANNON.RigidBody(mass, shape, material);
  21296. if (initialRotation) {
  21297. body.quaternion.x = initialRotation.x;
  21298. body.quaternion.z = initialRotation.y;
  21299. body.quaternion.y = initialRotation.z;
  21300. body.quaternion.w = -initialRotation.w;
  21301. }
  21302. body.position.set(bbox.center.x, bbox.center.z, bbox.center.y);
  21303. this._world.add(body);
  21304. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition });
  21305. return body;
  21306. };
  21307. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  21308. var compoundShape = new CANNON.Compound();
  21309. for (var index = 0; index < parts.length; index++) {
  21310. var mesh = parts[index].mesh;
  21311. var shape = this.registerMesh(mesh, parts[index].impostor);
  21312. if (index == 0) {
  21313. compoundShape.addChild(shape, new CANNON.Vec3(0, 0, 0));
  21314. } else {
  21315. compoundShape.addChild(shape, new CANNON.Vec3(mesh.position.x, mesh.position.z, mesh.position.y));
  21316. }
  21317. }
  21318. var initialMesh = parts[0].mesh;
  21319. var body = this._createRigidBodyFromShape(compoundShape, initialMesh, options.mass, options.friction, options.restitution);
  21320. body.parts = parts;
  21321. return body;
  21322. };
  21323. CannonJSPlugin.prototype._unbindBody = function (body) {
  21324. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21325. var registeredMesh = this._registeredMeshes[index];
  21326. if (registeredMesh.body === body) {
  21327. registeredMesh.body = null;
  21328. registeredMesh.delta = 0;
  21329. }
  21330. }
  21331. };
  21332. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  21333. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21334. var registeredMesh = this._registeredMeshes[index];
  21335. if (registeredMesh.mesh === mesh) {
  21336. // Remove body
  21337. if (registeredMesh.body) {
  21338. this._world.remove(registeredMesh.body);
  21339. this._unbindBody(registeredMesh.body);
  21340. }
  21341. this._registeredMeshes.splice(index, 1);
  21342. return;
  21343. }
  21344. }
  21345. };
  21346. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  21347. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.z, contactPoint.y);
  21348. var impulse = new CANNON.Vec3(force.x, force.z, force.y);
  21349. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21350. var registeredMesh = this._registeredMeshes[index];
  21351. if (registeredMesh.mesh === mesh) {
  21352. registeredMesh.body.applyImpulse(impulse, worldPoint);
  21353. return;
  21354. }
  21355. }
  21356. };
  21357. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  21358. var body1 = null, body2 = null;
  21359. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21360. var registeredMesh = this._registeredMeshes[index];
  21361. if (registeredMesh.mesh === mesh1) {
  21362. body1 = registeredMesh.body;
  21363. } else if (registeredMesh.mesh === mesh2) {
  21364. body2 = registeredMesh.body;
  21365. }
  21366. }
  21367. if (!body1 || !body2) {
  21368. return false;
  21369. }
  21370. 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));
  21371. this._world.addConstraint(constraint);
  21372. return true;
  21373. };
  21374. CannonJSPlugin.prototype.dispose = function () {
  21375. while (this._registeredMeshes.length) {
  21376. this.unregisterMesh(this._registeredMeshes[0].mesh);
  21377. }
  21378. };
  21379. CannonJSPlugin.prototype.isSupported = function () {
  21380. return window.CANNON !== undefined;
  21381. };
  21382. return CannonJSPlugin;
  21383. })();
  21384. BABYLON.CannonJSPlugin = CannonJSPlugin;
  21385. })(BABYLON || (BABYLON = {}));
  21386. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  21387. var BABYLON;
  21388. (function (BABYLON) {
  21389. var Condition = (function () {
  21390. function Condition(actionManager) {
  21391. this._actionManager = actionManager;
  21392. }
  21393. Condition.prototype.isValid = function () {
  21394. return true;
  21395. };
  21396. Condition.prototype._getProperty = function (propertyPath) {
  21397. return this._actionManager._getProperty(propertyPath);
  21398. };
  21399. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  21400. return this._actionManager._getEffectiveTarget(target, propertyPath);
  21401. };
  21402. return Condition;
  21403. })();
  21404. BABYLON.Condition = Condition;
  21405. var ValueCondition = (function (_super) {
  21406. __extends(ValueCondition, _super);
  21407. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  21408. if (typeof operator === "undefined") { operator = ValueCondition.IsEqual; }
  21409. _super.call(this, actionManager);
  21410. this.propertyPath = propertyPath;
  21411. this.value = value;
  21412. this.operator = operator;
  21413. this._target = this._getEffectiveTarget(target, this.propertyPath);
  21414. this._property = this._getProperty(this.propertyPath);
  21415. }
  21416. Object.defineProperty(ValueCondition, "IsEqual", {
  21417. get: function () {
  21418. return ValueCondition._IsEqual;
  21419. },
  21420. enumerable: true,
  21421. configurable: true
  21422. });
  21423. Object.defineProperty(ValueCondition, "IsDifferent", {
  21424. get: function () {
  21425. return ValueCondition._IsDifferent;
  21426. },
  21427. enumerable: true,
  21428. configurable: true
  21429. });
  21430. Object.defineProperty(ValueCondition, "IsGreater", {
  21431. get: function () {
  21432. return ValueCondition._IsGreater;
  21433. },
  21434. enumerable: true,
  21435. configurable: true
  21436. });
  21437. Object.defineProperty(ValueCondition, "IsLesser", {
  21438. get: function () {
  21439. return ValueCondition._IsLesser;
  21440. },
  21441. enumerable: true,
  21442. configurable: true
  21443. });
  21444. // Methods
  21445. ValueCondition.prototype.isValid = function () {
  21446. switch (this.operator) {
  21447. case ValueCondition.IsGreater:
  21448. return this._target[this._property] > this.value;
  21449. case ValueCondition.IsLesser:
  21450. return this._target[this._property] < this.value;
  21451. case ValueCondition.IsEqual:
  21452. case ValueCondition.IsDifferent:
  21453. var check;
  21454. if (this.value.equals) {
  21455. check = this.value.equals(this._target[this._property]);
  21456. } else {
  21457. check = this.value === this._target[this._property];
  21458. }
  21459. return this.operator === ValueCondition.IsEqual ? check : !check;
  21460. }
  21461. return false;
  21462. };
  21463. ValueCondition._IsEqual = 0;
  21464. ValueCondition._IsDifferent = 1;
  21465. ValueCondition._IsGreater = 2;
  21466. ValueCondition._IsLesser = 3;
  21467. return ValueCondition;
  21468. })(Condition);
  21469. BABYLON.ValueCondition = ValueCondition;
  21470. var PredicateCondition = (function (_super) {
  21471. __extends(PredicateCondition, _super);
  21472. function PredicateCondition(actionManager, predicate) {
  21473. _super.call(this, actionManager);
  21474. this.predicate = predicate;
  21475. }
  21476. PredicateCondition.prototype.isValid = function () {
  21477. return this.predicate();
  21478. };
  21479. return PredicateCondition;
  21480. })(Condition);
  21481. BABYLON.PredicateCondition = PredicateCondition;
  21482. var StateCondition = (function (_super) {
  21483. __extends(StateCondition, _super);
  21484. function StateCondition(actionManager, target, value) {
  21485. _super.call(this, actionManager);
  21486. this.value = value;
  21487. this._target = target;
  21488. }
  21489. // Methods
  21490. StateCondition.prototype.isValid = function () {
  21491. return this._target.state === this.value;
  21492. };
  21493. return StateCondition;
  21494. })(Condition);
  21495. BABYLON.StateCondition = StateCondition;
  21496. })(BABYLON || (BABYLON = {}));
  21497. //# sourceMappingURL=babylon.condition.js.map
  21498. var BABYLON;
  21499. (function (BABYLON) {
  21500. var Action = (function () {
  21501. function Action(triggerOptions, condition) {
  21502. this.triggerOptions = triggerOptions;
  21503. if (triggerOptions.parameter) {
  21504. this.trigger = triggerOptions.trigger;
  21505. this._triggerParameter = triggerOptions.parameter;
  21506. } else {
  21507. this.trigger = triggerOptions;
  21508. }
  21509. this._nextActiveAction = this;
  21510. this._condition = condition;
  21511. }
  21512. // Methods
  21513. Action.prototype._prepare = function () {
  21514. };
  21515. Action.prototype.getTriggerParameter = function () {
  21516. return this._triggerParameter;
  21517. };
  21518. Action.prototype._executeCurrent = function (evt) {
  21519. if (this._condition) {
  21520. var currentRenderId = this._actionManager.getScene().getRenderId();
  21521. // We cache the current evaluation for the current frame
  21522. if (this._condition._evaluationId === currentRenderId) {
  21523. if (!this._condition._currentResult) {
  21524. return;
  21525. }
  21526. } else {
  21527. this._condition._evaluationId = currentRenderId;
  21528. if (!this._condition.isValid()) {
  21529. this._condition._currentResult = false;
  21530. return;
  21531. }
  21532. this._condition._currentResult = true;
  21533. }
  21534. }
  21535. this._nextActiveAction.execute(evt);
  21536. if (this._nextActiveAction._child) {
  21537. if (!this._nextActiveAction._child._actionManager) {
  21538. this._nextActiveAction._child._actionManager = this._actionManager;
  21539. }
  21540. this._nextActiveAction = this._nextActiveAction._child;
  21541. } else {
  21542. this._nextActiveAction = this;
  21543. }
  21544. };
  21545. Action.prototype.execute = function (evt) {
  21546. };
  21547. Action.prototype.then = function (action) {
  21548. this._child = action;
  21549. action._actionManager = this._actionManager;
  21550. action._prepare();
  21551. return action;
  21552. };
  21553. Action.prototype._getProperty = function (propertyPath) {
  21554. return this._actionManager._getProperty(propertyPath);
  21555. };
  21556. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  21557. return this._actionManager._getEffectiveTarget(target, propertyPath);
  21558. };
  21559. return Action;
  21560. })();
  21561. BABYLON.Action = Action;
  21562. })(BABYLON || (BABYLON = {}));
  21563. //# sourceMappingURL=babylon.action.js.map
  21564. var BABYLON;
  21565. (function (BABYLON) {
  21566. var ActionEvent = (function () {
  21567. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent) {
  21568. this.source = source;
  21569. this.pointerX = pointerX;
  21570. this.pointerY = pointerY;
  21571. this.meshUnderPointer = meshUnderPointer;
  21572. this.sourceEvent = sourceEvent;
  21573. }
  21574. ActionEvent.CreateNew = function (source, evt) {
  21575. var scene = source.getScene();
  21576. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  21577. };
  21578. ActionEvent.CreateNewFromScene = function (scene, evt) {
  21579. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  21580. };
  21581. return ActionEvent;
  21582. })();
  21583. BABYLON.ActionEvent = ActionEvent;
  21584. var ActionManager = (function () {
  21585. function ActionManager(scene) {
  21586. // Members
  21587. this.actions = new Array();
  21588. this._scene = scene;
  21589. scene._actionManagers.push(this);
  21590. }
  21591. Object.defineProperty(ActionManager, "NothingTrigger", {
  21592. get: function () {
  21593. return ActionManager._NothingTrigger;
  21594. },
  21595. enumerable: true,
  21596. configurable: true
  21597. });
  21598. Object.defineProperty(ActionManager, "OnPickTrigger", {
  21599. get: function () {
  21600. return ActionManager._OnPickTrigger;
  21601. },
  21602. enumerable: true,
  21603. configurable: true
  21604. });
  21605. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  21606. get: function () {
  21607. return ActionManager._OnLeftPickTrigger;
  21608. },
  21609. enumerable: true,
  21610. configurable: true
  21611. });
  21612. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  21613. get: function () {
  21614. return ActionManager._OnRightPickTrigger;
  21615. },
  21616. enumerable: true,
  21617. configurable: true
  21618. });
  21619. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  21620. get: function () {
  21621. return ActionManager._OnCenterPickTrigger;
  21622. },
  21623. enumerable: true,
  21624. configurable: true
  21625. });
  21626. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  21627. get: function () {
  21628. return ActionManager._OnPointerOverTrigger;
  21629. },
  21630. enumerable: true,
  21631. configurable: true
  21632. });
  21633. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  21634. get: function () {
  21635. return ActionManager._OnPointerOutTrigger;
  21636. },
  21637. enumerable: true,
  21638. configurable: true
  21639. });
  21640. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  21641. get: function () {
  21642. return ActionManager._OnEveryFrameTrigger;
  21643. },
  21644. enumerable: true,
  21645. configurable: true
  21646. });
  21647. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  21648. get: function () {
  21649. return ActionManager._OnIntersectionEnterTrigger;
  21650. },
  21651. enumerable: true,
  21652. configurable: true
  21653. });
  21654. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  21655. get: function () {
  21656. return ActionManager._OnIntersectionExitTrigger;
  21657. },
  21658. enumerable: true,
  21659. configurable: true
  21660. });
  21661. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  21662. get: function () {
  21663. return ActionManager._OnKeyDownTrigger;
  21664. },
  21665. enumerable: true,
  21666. configurable: true
  21667. });
  21668. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  21669. get: function () {
  21670. return ActionManager._OnKeyUpTrigger;
  21671. },
  21672. enumerable: true,
  21673. configurable: true
  21674. });
  21675. // Methods
  21676. ActionManager.prototype.dispose = function () {
  21677. var index = this._scene._actionManagers.indexOf(this);
  21678. if (index > -1) {
  21679. this._scene._actionManagers.splice(index, 1);
  21680. }
  21681. };
  21682. ActionManager.prototype.getScene = function () {
  21683. return this._scene;
  21684. };
  21685. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  21686. for (var index = 0; index < this.actions.length; index++) {
  21687. var action = this.actions[index];
  21688. if (triggers.indexOf(action.trigger) > -1) {
  21689. return true;
  21690. }
  21691. }
  21692. return false;
  21693. };
  21694. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  21695. get: function () {
  21696. for (var index = 0; index < this.actions.length; index++) {
  21697. var action = this.actions[index];
  21698. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  21699. return true;
  21700. }
  21701. }
  21702. return false;
  21703. },
  21704. enumerable: true,
  21705. configurable: true
  21706. });
  21707. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  21708. get: function () {
  21709. for (var index = 0; index < this.actions.length; index++) {
  21710. var action = this.actions[index];
  21711. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  21712. return true;
  21713. }
  21714. }
  21715. return false;
  21716. },
  21717. enumerable: true,
  21718. configurable: true
  21719. });
  21720. ActionManager.prototype.registerAction = function (action) {
  21721. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  21722. if (this.getScene().actionManager !== this) {
  21723. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  21724. return null;
  21725. }
  21726. }
  21727. this.actions.push(action);
  21728. action._actionManager = this;
  21729. action._prepare();
  21730. return action;
  21731. };
  21732. ActionManager.prototype.processTrigger = function (trigger, evt) {
  21733. for (var index = 0; index < this.actions.length; index++) {
  21734. var action = this.actions[index];
  21735. if (action.trigger === trigger) {
  21736. if (trigger === ActionManager.OnKeyUpTrigger || trigger === ActionManager.OnKeyDownTrigger) {
  21737. var parameter = action.getTriggerParameter();
  21738. if (parameter) {
  21739. if (evt.sourceEvent.key !== parameter) {
  21740. continue;
  21741. }
  21742. }
  21743. }
  21744. action._executeCurrent(evt);
  21745. }
  21746. }
  21747. };
  21748. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  21749. var properties = propertyPath.split(".");
  21750. for (var index = 0; index < properties.length - 1; index++) {
  21751. target = target[properties[index]];
  21752. }
  21753. return target;
  21754. };
  21755. ActionManager.prototype._getProperty = function (propertyPath) {
  21756. var properties = propertyPath.split(".");
  21757. return properties[properties.length - 1];
  21758. };
  21759. ActionManager._NothingTrigger = 0;
  21760. ActionManager._OnPickTrigger = 1;
  21761. ActionManager._OnLeftPickTrigger = 2;
  21762. ActionManager._OnRightPickTrigger = 3;
  21763. ActionManager._OnCenterPickTrigger = 4;
  21764. ActionManager._OnPointerOverTrigger = 5;
  21765. ActionManager._OnPointerOutTrigger = 6;
  21766. ActionManager._OnEveryFrameTrigger = 7;
  21767. ActionManager._OnIntersectionEnterTrigger = 8;
  21768. ActionManager._OnIntersectionExitTrigger = 9;
  21769. ActionManager._OnKeyDownTrigger = 10;
  21770. ActionManager._OnKeyUpTrigger = 11;
  21771. return ActionManager;
  21772. })();
  21773. BABYLON.ActionManager = ActionManager;
  21774. })(BABYLON || (BABYLON = {}));
  21775. //# sourceMappingURL=babylon.actionManager.js.map
  21776. var BABYLON;
  21777. (function (BABYLON) {
  21778. var InterpolateValueAction = (function (_super) {
  21779. __extends(InterpolateValueAction, _super);
  21780. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations) {
  21781. if (typeof duration === "undefined") { duration = 1000; }
  21782. _super.call(this, triggerOptions, condition);
  21783. this.propertyPath = propertyPath;
  21784. this.value = value;
  21785. this.duration = duration;
  21786. this.stopOtherAnimations = stopOtherAnimations;
  21787. this._target = target;
  21788. }
  21789. InterpolateValueAction.prototype._prepare = function () {
  21790. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  21791. this._property = this._getProperty(this.propertyPath);
  21792. };
  21793. InterpolateValueAction.prototype.execute = function () {
  21794. var scene = this._actionManager.getScene();
  21795. var keys = [
  21796. {
  21797. frame: 0,
  21798. value: this._target[this._property]
  21799. }, {
  21800. frame: 100,
  21801. value: this.value
  21802. }
  21803. ];
  21804. var dataType;
  21805. if (typeof this.value === "number") {
  21806. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  21807. } else if (this.value instanceof BABYLON.Color3) {
  21808. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  21809. } else if (this.value instanceof BABYLON.Vector3) {
  21810. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  21811. } else if (this.value instanceof BABYLON.Matrix) {
  21812. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  21813. } else if (this.value instanceof BABYLON.Quaternion) {
  21814. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  21815. } else {
  21816. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  21817. return;
  21818. }
  21819. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  21820. animation.setKeys(keys);
  21821. if (this.stopOtherAnimations) {
  21822. scene.stopAnimation(this._target);
  21823. }
  21824. scene.beginDirectAnimation(this._target, [animation], 0, 100);
  21825. };
  21826. return InterpolateValueAction;
  21827. })(BABYLON.Action);
  21828. BABYLON.InterpolateValueAction = InterpolateValueAction;
  21829. })(BABYLON || (BABYLON = {}));
  21830. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  21831. var BABYLON;
  21832. (function (BABYLON) {
  21833. var SwitchBooleanAction = (function (_super) {
  21834. __extends(SwitchBooleanAction, _super);
  21835. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  21836. _super.call(this, triggerOptions, condition);
  21837. this.propertyPath = propertyPath;
  21838. this._target = target;
  21839. }
  21840. SwitchBooleanAction.prototype._prepare = function () {
  21841. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  21842. this._property = this._getProperty(this.propertyPath);
  21843. };
  21844. SwitchBooleanAction.prototype.execute = function () {
  21845. this._target[this._property] = !this._target[this._property];
  21846. };
  21847. return SwitchBooleanAction;
  21848. })(BABYLON.Action);
  21849. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  21850. var SetStateAction = (function (_super) {
  21851. __extends(SetStateAction, _super);
  21852. function SetStateAction(triggerOptions, target, value, condition) {
  21853. _super.call(this, triggerOptions, condition);
  21854. this.value = value;
  21855. this._target = target;
  21856. }
  21857. SetStateAction.prototype.execute = function () {
  21858. this._target.state = this.value;
  21859. };
  21860. return SetStateAction;
  21861. })(BABYLON.Action);
  21862. BABYLON.SetStateAction = SetStateAction;
  21863. var SetValueAction = (function (_super) {
  21864. __extends(SetValueAction, _super);
  21865. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  21866. _super.call(this, triggerOptions, condition);
  21867. this.propertyPath = propertyPath;
  21868. this.value = value;
  21869. this._target = target;
  21870. }
  21871. SetValueAction.prototype._prepare = function () {
  21872. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  21873. this._property = this._getProperty(this.propertyPath);
  21874. };
  21875. SetValueAction.prototype.execute = function () {
  21876. this._target[this._property] = this.value;
  21877. };
  21878. return SetValueAction;
  21879. })(BABYLON.Action);
  21880. BABYLON.SetValueAction = SetValueAction;
  21881. var IncrementValueAction = (function (_super) {
  21882. __extends(IncrementValueAction, _super);
  21883. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  21884. _super.call(this, triggerOptions, condition);
  21885. this.propertyPath = propertyPath;
  21886. this.value = value;
  21887. this._target = target;
  21888. }
  21889. IncrementValueAction.prototype._prepare = function () {
  21890. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  21891. this._property = this._getProperty(this.propertyPath);
  21892. if (typeof this._target[this._property] !== "number") {
  21893. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  21894. }
  21895. };
  21896. IncrementValueAction.prototype.execute = function () {
  21897. this._target[this._property] += this.value;
  21898. };
  21899. return IncrementValueAction;
  21900. })(BABYLON.Action);
  21901. BABYLON.IncrementValueAction = IncrementValueAction;
  21902. var PlayAnimationAction = (function (_super) {
  21903. __extends(PlayAnimationAction, _super);
  21904. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  21905. _super.call(this, triggerOptions, condition);
  21906. this.from = from;
  21907. this.to = to;
  21908. this.loop = loop;
  21909. this._target = target;
  21910. }
  21911. PlayAnimationAction.prototype._prepare = function () {
  21912. };
  21913. PlayAnimationAction.prototype.execute = function () {
  21914. var scene = this._actionManager.getScene();
  21915. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  21916. };
  21917. return PlayAnimationAction;
  21918. })(BABYLON.Action);
  21919. BABYLON.PlayAnimationAction = PlayAnimationAction;
  21920. var StopAnimationAction = (function (_super) {
  21921. __extends(StopAnimationAction, _super);
  21922. function StopAnimationAction(triggerOptions, target, condition) {
  21923. _super.call(this, triggerOptions, condition);
  21924. this._target = target;
  21925. }
  21926. StopAnimationAction.prototype._prepare = function () {
  21927. };
  21928. StopAnimationAction.prototype.execute = function () {
  21929. var scene = this._actionManager.getScene();
  21930. scene.stopAnimation(this._target);
  21931. };
  21932. return StopAnimationAction;
  21933. })(BABYLON.Action);
  21934. BABYLON.StopAnimationAction = StopAnimationAction;
  21935. var DoNothingAction = (function (_super) {
  21936. __extends(DoNothingAction, _super);
  21937. function DoNothingAction(triggerOptions, condition) {
  21938. if (typeof triggerOptions === "undefined") { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  21939. _super.call(this, triggerOptions, condition);
  21940. }
  21941. DoNothingAction.prototype.execute = function () {
  21942. };
  21943. return DoNothingAction;
  21944. })(BABYLON.Action);
  21945. BABYLON.DoNothingAction = DoNothingAction;
  21946. var CombineAction = (function (_super) {
  21947. __extends(CombineAction, _super);
  21948. function CombineAction(triggerOptions, children, condition) {
  21949. _super.call(this, triggerOptions, condition);
  21950. this.children = children;
  21951. }
  21952. CombineAction.prototype._prepare = function () {
  21953. for (var index = 0; index < this.children.length; index++) {
  21954. this.children[index]._actionManager = this._actionManager;
  21955. this.children[index]._prepare();
  21956. }
  21957. };
  21958. CombineAction.prototype.execute = function (evt) {
  21959. for (var index = 0; index < this.children.length; index++) {
  21960. this.children[index].execute(evt);
  21961. }
  21962. };
  21963. return CombineAction;
  21964. })(BABYLON.Action);
  21965. BABYLON.CombineAction = CombineAction;
  21966. var ExecuteCodeAction = (function (_super) {
  21967. __extends(ExecuteCodeAction, _super);
  21968. function ExecuteCodeAction(triggerOptions, func, condition) {
  21969. _super.call(this, triggerOptions, condition);
  21970. this.func = func;
  21971. }
  21972. ExecuteCodeAction.prototype.execute = function (evt) {
  21973. this.func(evt);
  21974. };
  21975. return ExecuteCodeAction;
  21976. })(BABYLON.Action);
  21977. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  21978. var SetParentAction = (function (_super) {
  21979. __extends(SetParentAction, _super);
  21980. function SetParentAction(triggerOptions, target, parent, condition) {
  21981. _super.call(this, triggerOptions, condition);
  21982. this._target = target;
  21983. this._parent = parent;
  21984. }
  21985. SetParentAction.prototype._prepare = function () {
  21986. };
  21987. SetParentAction.prototype.execute = function () {
  21988. if (this._target.parent === this._parent) {
  21989. return;
  21990. }
  21991. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  21992. invertParentWorldMatrix.invert();
  21993. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  21994. this._target.parent = this._parent;
  21995. };
  21996. return SetParentAction;
  21997. })(BABYLON.Action);
  21998. BABYLON.SetParentAction = SetParentAction;
  21999. })(BABYLON || (BABYLON = {}));
  22000. //# sourceMappingURL=babylon.directActions.js.map
  22001. var BABYLON;
  22002. (function (BABYLON) {
  22003. var Geometry = (function () {
  22004. function Geometry(id, scene, vertexData, updatable, mesh) {
  22005. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  22006. this._totalVertices = 0;
  22007. this._indices = [];
  22008. this.id = id;
  22009. this._engine = scene.getEngine();
  22010. this._meshes = [];
  22011. this._scene = scene;
  22012. // vertexData
  22013. if (vertexData) {
  22014. this.setAllVerticesData(vertexData, updatable);
  22015. } else {
  22016. this._totalVertices = 0;
  22017. this._indices = [];
  22018. }
  22019. // applyToMesh
  22020. if (mesh) {
  22021. this.applyToMesh(mesh);
  22022. }
  22023. }
  22024. Geometry.prototype.getScene = function () {
  22025. return this._scene;
  22026. };
  22027. Geometry.prototype.getEngine = function () {
  22028. return this._engine;
  22029. };
  22030. Geometry.prototype.isReady = function () {
  22031. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  22032. };
  22033. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  22034. vertexData.applyToGeometry(this, updatable);
  22035. };
  22036. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  22037. this._vertexBuffers = this._vertexBuffers || {};
  22038. if (this._vertexBuffers[kind]) {
  22039. this._vertexBuffers[kind].dispose();
  22040. }
  22041. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  22042. if (kind === BABYLON.VertexBuffer.PositionKind) {
  22043. stride = this._vertexBuffers[kind].getStrideSize();
  22044. this._totalVertices = data.length / stride;
  22045. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  22046. var meshes = this._meshes;
  22047. var numOfMeshes = meshes.length;
  22048. for (var index = 0; index < numOfMeshes; index++) {
  22049. var mesh = meshes[index];
  22050. mesh._resetPointsArrayCache();
  22051. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  22052. mesh._createGlobalSubMesh();
  22053. mesh.computeWorldMatrix(true);
  22054. }
  22055. }
  22056. };
  22057. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  22058. var vertexBuffer = this.getVertexBuffer(kind);
  22059. if (!vertexBuffer) {
  22060. return;
  22061. }
  22062. vertexBuffer.updateDirectly(data, offset);
  22063. };
  22064. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  22065. var vertexBuffer = this.getVertexBuffer(kind);
  22066. if (!vertexBuffer) {
  22067. return;
  22068. }
  22069. vertexBuffer.update(data);
  22070. if (kind === BABYLON.VertexBuffer.PositionKind) {
  22071. var extend;
  22072. var stride = vertexBuffer.getStrideSize();
  22073. this._totalVertices = data.length / stride;
  22074. if (updateExtends) {
  22075. extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  22076. }
  22077. var meshes = this._meshes;
  22078. var numOfMeshes = meshes.length;
  22079. for (var index = 0; index < numOfMeshes; index++) {
  22080. var mesh = meshes[index];
  22081. mesh._resetPointsArrayCache();
  22082. if (updateExtends) {
  22083. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  22084. }
  22085. }
  22086. }
  22087. };
  22088. Geometry.prototype.getTotalVertices = function () {
  22089. if (!this.isReady()) {
  22090. return 0;
  22091. }
  22092. return this._totalVertices;
  22093. };
  22094. Geometry.prototype.getVerticesData = function (kind) {
  22095. var vertexBuffer = this.getVertexBuffer(kind);
  22096. if (!vertexBuffer) {
  22097. return null;
  22098. }
  22099. return vertexBuffer.getData();
  22100. };
  22101. Geometry.prototype.getVertexBuffer = function (kind) {
  22102. if (!this.isReady()) {
  22103. return null;
  22104. }
  22105. return this._vertexBuffers[kind];
  22106. };
  22107. Geometry.prototype.getVertexBuffers = function () {
  22108. if (!this.isReady()) {
  22109. return null;
  22110. }
  22111. return this._vertexBuffers;
  22112. };
  22113. Geometry.prototype.isVerticesDataPresent = function (kind) {
  22114. if (!this._vertexBuffers) {
  22115. if (this._delayInfo) {
  22116. return this._delayInfo.indexOf(kind) !== -1;
  22117. }
  22118. return false;
  22119. }
  22120. return this._vertexBuffers[kind] !== undefined;
  22121. };
  22122. Geometry.prototype.getVerticesDataKinds = function () {
  22123. var result = [];
  22124. if (!this._vertexBuffers && this._delayInfo) {
  22125. for (var kind in this._delayInfo) {
  22126. result.push(kind);
  22127. }
  22128. } else {
  22129. for (kind in this._vertexBuffers) {
  22130. result.push(kind);
  22131. }
  22132. }
  22133. return result;
  22134. };
  22135. Geometry.prototype.setIndices = function (indices, totalVertices) {
  22136. if (this._indexBuffer) {
  22137. this._engine._releaseBuffer(this._indexBuffer);
  22138. }
  22139. this._indices = indices;
  22140. if (this._meshes.length !== 0 && this._indices) {
  22141. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  22142. }
  22143. if (totalVertices !== undefined) {
  22144. this._totalVertices = totalVertices;
  22145. }
  22146. var meshes = this._meshes;
  22147. var numOfMeshes = meshes.length;
  22148. for (var index = 0; index < numOfMeshes; index++) {
  22149. meshes[index]._createGlobalSubMesh();
  22150. }
  22151. };
  22152. Geometry.prototype.getTotalIndices = function () {
  22153. if (!this.isReady()) {
  22154. return 0;
  22155. }
  22156. return this._indices.length;
  22157. };
  22158. Geometry.prototype.getIndices = function () {
  22159. if (!this.isReady()) {
  22160. return null;
  22161. }
  22162. return this._indices;
  22163. };
  22164. Geometry.prototype.getIndexBuffer = function () {
  22165. if (!this.isReady()) {
  22166. return null;
  22167. }
  22168. return this._indexBuffer;
  22169. };
  22170. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  22171. var meshes = this._meshes;
  22172. var index = meshes.indexOf(mesh);
  22173. if (index === -1) {
  22174. return;
  22175. }
  22176. for (var kind in this._vertexBuffers) {
  22177. this._vertexBuffers[kind].dispose();
  22178. }
  22179. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  22180. this._indexBuffer = null;
  22181. }
  22182. meshes.splice(index, 1);
  22183. mesh._geometry = null;
  22184. if (meshes.length == 0 && shouldDispose) {
  22185. this.dispose();
  22186. }
  22187. };
  22188. Geometry.prototype.applyToMesh = function (mesh) {
  22189. if (mesh._geometry === this) {
  22190. return;
  22191. }
  22192. var previousGeometry = mesh._geometry;
  22193. if (previousGeometry) {
  22194. previousGeometry.releaseForMesh(mesh);
  22195. }
  22196. var meshes = this._meshes;
  22197. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  22198. mesh._geometry = this;
  22199. this._scene.pushGeometry(this);
  22200. meshes.push(mesh);
  22201. if (this.isReady()) {
  22202. this._applyToMesh(mesh);
  22203. } else {
  22204. mesh._boundingInfo = this._boundingInfo;
  22205. }
  22206. };
  22207. Geometry.prototype._applyToMesh = function (mesh) {
  22208. var numOfMeshes = this._meshes.length;
  22209. for (var kind in this._vertexBuffers) {
  22210. if (numOfMeshes === 1) {
  22211. this._vertexBuffers[kind].create();
  22212. }
  22213. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  22214. if (kind === BABYLON.VertexBuffer.PositionKind) {
  22215. mesh._resetPointsArrayCache();
  22216. var extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  22217. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  22218. mesh._createGlobalSubMesh();
  22219. }
  22220. }
  22221. // indexBuffer
  22222. if (numOfMeshes === 1 && this._indices) {
  22223. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  22224. }
  22225. if (this._indexBuffer) {
  22226. this._indexBuffer.references = numOfMeshes;
  22227. }
  22228. };
  22229. Geometry.prototype.load = function (scene, onLoaded) {
  22230. var _this = this;
  22231. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  22232. return;
  22233. }
  22234. if (this.isReady()) {
  22235. if (onLoaded) {
  22236. onLoaded();
  22237. }
  22238. return;
  22239. }
  22240. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  22241. scene._addPendingData(this);
  22242. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  22243. _this._delayLoadingFunction(JSON.parse(data), _this);
  22244. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  22245. _this._delayInfo = [];
  22246. scene._removePendingData(_this);
  22247. var meshes = _this._meshes;
  22248. var numOfMeshes = meshes.length;
  22249. for (var index = 0; index < numOfMeshes; index++) {
  22250. _this._applyToMesh(meshes[index]);
  22251. }
  22252. if (onLoaded) {
  22253. onLoaded();
  22254. }
  22255. }, function () {
  22256. }, scene.database);
  22257. };
  22258. Geometry.prototype.dispose = function () {
  22259. var meshes = this._meshes;
  22260. var numOfMeshes = meshes.length;
  22261. for (var index = 0; index < numOfMeshes; index++) {
  22262. this.releaseForMesh(meshes[index]);
  22263. }
  22264. this._meshes = [];
  22265. for (var kind in this._vertexBuffers) {
  22266. this._vertexBuffers[kind].dispose();
  22267. }
  22268. this._vertexBuffers = [];
  22269. this._totalVertices = 0;
  22270. if (this._indexBuffer) {
  22271. this._engine._releaseBuffer(this._indexBuffer);
  22272. }
  22273. this._indexBuffer = null;
  22274. this._indices = [];
  22275. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  22276. this.delayLoadingFile = null;
  22277. this._delayLoadingFunction = null;
  22278. this._delayInfo = [];
  22279. this._boundingInfo = null; // todo: .dispose()
  22280. var geometries = this._scene.getGeometries();
  22281. index = geometries.indexOf(this);
  22282. if (index > -1) {
  22283. geometries.splice(index, 1);
  22284. }
  22285. };
  22286. Geometry.prototype.copy = function (id) {
  22287. var vertexData = new BABYLON.VertexData();
  22288. vertexData.indices = [];
  22289. var indices = this.getIndices();
  22290. for (var index = 0; index < indices.length; index++) {
  22291. vertexData.indices.push(indices[index]);
  22292. }
  22293. var updatable = false;
  22294. var stopChecking = false;
  22295. for (var kind in this._vertexBuffers) {
  22296. vertexData.set(this.getVerticesData(kind), kind);
  22297. if (!stopChecking) {
  22298. updatable = this.getVertexBuffer(kind).isUpdatable();
  22299. stopChecking = !updatable;
  22300. }
  22301. }
  22302. var geometry = new BABYLON.Geometry(id, this._scene, vertexData, updatable, null);
  22303. geometry.delayLoadState = this.delayLoadState;
  22304. geometry.delayLoadingFile = this.delayLoadingFile;
  22305. geometry._delayLoadingFunction = this._delayLoadingFunction;
  22306. for (kind in this._delayInfo) {
  22307. geometry._delayInfo = geometry._delayInfo || [];
  22308. geometry._delayInfo.push(kind);
  22309. }
  22310. // Bounding info
  22311. var extend = BABYLON.Tools.ExtractMinAndMax(this.getVerticesData(BABYLON.VertexBuffer.PositionKind), 0, this.getTotalVertices());
  22312. geometry._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  22313. return geometry;
  22314. };
  22315. // Statics
  22316. Geometry.ExtractFromMesh = function (mesh, id) {
  22317. var geometry = mesh._geometry;
  22318. if (!geometry) {
  22319. return null;
  22320. }
  22321. return geometry.copy(id);
  22322. };
  22323. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  22324. // be aware Math.random() could cause collisions
  22325. Geometry.RandomId = function () {
  22326. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  22327. var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
  22328. return v.toString(16);
  22329. });
  22330. };
  22331. return Geometry;
  22332. })();
  22333. BABYLON.Geometry = Geometry;
  22334. (function (Geometry) {
  22335. /////// Primitives //////////////////////////////////////////////
  22336. (function (Primitives) {
  22337. /// Abstract class
  22338. var _Primitive = (function (_super) {
  22339. __extends(_Primitive, _super);
  22340. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  22341. this._beingRegenerated = true;
  22342. this._canBeRegenerated = canBeRegenerated;
  22343. _super.call(this, id, scene, vertexData, false, mesh); // updatable = false to be sure not to update vertices
  22344. this._beingRegenerated = false;
  22345. }
  22346. _Primitive.prototype.canBeRegenerated = function () {
  22347. return this._canBeRegenerated;
  22348. };
  22349. _Primitive.prototype.regenerate = function () {
  22350. if (!this._canBeRegenerated) {
  22351. return;
  22352. }
  22353. this._beingRegenerated = true;
  22354. this.setAllVerticesData(this._regenerateVertexData(), false);
  22355. this._beingRegenerated = false;
  22356. };
  22357. _Primitive.prototype.asNewGeometry = function (id) {
  22358. return _super.prototype.copy.call(this, id);
  22359. };
  22360. // overrides
  22361. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  22362. if (!this._beingRegenerated) {
  22363. return;
  22364. }
  22365. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  22366. };
  22367. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  22368. if (!this._beingRegenerated) {
  22369. return;
  22370. }
  22371. _super.prototype.setVerticesData.call(this, kind, data, false);
  22372. };
  22373. // to override
  22374. // protected
  22375. _Primitive.prototype._regenerateVertexData = function () {
  22376. throw new Error("Abstract method");
  22377. };
  22378. _Primitive.prototype.copy = function (id) {
  22379. throw new Error("Must be overriden in sub-classes.");
  22380. };
  22381. return _Primitive;
  22382. })(Geometry);
  22383. Primitives._Primitive = _Primitive;
  22384. var Box = (function (_super) {
  22385. __extends(Box, _super);
  22386. function Box(id, scene, size, canBeRegenerated, mesh) {
  22387. this.size = size;
  22388. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  22389. }
  22390. Box.prototype._regenerateVertexData = function () {
  22391. return BABYLON.VertexData.CreateBox(this.size);
  22392. };
  22393. Box.prototype.copy = function (id) {
  22394. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null);
  22395. };
  22396. return Box;
  22397. })(_Primitive);
  22398. Primitives.Box = Box;
  22399. var Sphere = (function (_super) {
  22400. __extends(Sphere, _super);
  22401. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh) {
  22402. this.segments = segments;
  22403. this.diameter = diameter;
  22404. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  22405. }
  22406. Sphere.prototype._regenerateVertexData = function () {
  22407. return BABYLON.VertexData.CreateSphere(this.segments, this.diameter);
  22408. };
  22409. Sphere.prototype.copy = function (id) {
  22410. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null);
  22411. };
  22412. return Sphere;
  22413. })(_Primitive);
  22414. Primitives.Sphere = Sphere;
  22415. var Cylinder = (function (_super) {
  22416. __extends(Cylinder, _super);
  22417. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh) {
  22418. if (typeof subdivisions === "undefined") { subdivisions = 1; }
  22419. this.height = height;
  22420. this.diameterTop = diameterTop;
  22421. this.diameterBottom = diameterBottom;
  22422. this.tessellation = tessellation;
  22423. this.subdivisions = subdivisions;
  22424. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  22425. }
  22426. Cylinder.prototype._regenerateVertexData = function () {
  22427. return BABYLON.VertexData.CreateCylinder(this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions);
  22428. };
  22429. Cylinder.prototype.copy = function (id) {
  22430. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null);
  22431. };
  22432. return Cylinder;
  22433. })(_Primitive);
  22434. Primitives.Cylinder = Cylinder;
  22435. var Torus = (function (_super) {
  22436. __extends(Torus, _super);
  22437. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh) {
  22438. this.diameter = diameter;
  22439. this.thickness = thickness;
  22440. this.tessellation = tessellation;
  22441. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  22442. }
  22443. Torus.prototype._regenerateVertexData = function () {
  22444. return BABYLON.VertexData.CreateTorus(this.diameter, this.thickness, this.tessellation);
  22445. };
  22446. Torus.prototype.copy = function (id) {
  22447. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null);
  22448. };
  22449. return Torus;
  22450. })(_Primitive);
  22451. Primitives.Torus = Torus;
  22452. var Ground = (function (_super) {
  22453. __extends(Ground, _super);
  22454. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  22455. this.width = width;
  22456. this.height = height;
  22457. this.subdivisions = subdivisions;
  22458. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  22459. }
  22460. Ground.prototype._regenerateVertexData = function () {
  22461. return BABYLON.VertexData.CreateGround(this.width, this.height, this.subdivisions);
  22462. };
  22463. Ground.prototype.copy = function (id) {
  22464. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  22465. };
  22466. return Ground;
  22467. })(_Primitive);
  22468. Primitives.Ground = Ground;
  22469. var TiledGround = (function (_super) {
  22470. __extends(TiledGround, _super);
  22471. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  22472. this.xmin = xmin;
  22473. this.zmin = zmin;
  22474. this.xmax = xmax;
  22475. this.zmax = zmax;
  22476. this.subdivisions = subdivisions;
  22477. this.precision = precision;
  22478. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  22479. }
  22480. TiledGround.prototype._regenerateVertexData = function () {
  22481. return BABYLON.VertexData.CreateTiledGround(this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision);
  22482. };
  22483. TiledGround.prototype.copy = function (id) {
  22484. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  22485. };
  22486. return TiledGround;
  22487. })(_Primitive);
  22488. Primitives.TiledGround = TiledGround;
  22489. var Plane = (function (_super) {
  22490. __extends(Plane, _super);
  22491. function Plane(id, scene, size, canBeRegenerated, mesh) {
  22492. this.size = size;
  22493. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  22494. }
  22495. Plane.prototype._regenerateVertexData = function () {
  22496. return BABYLON.VertexData.CreatePlane(this.size);
  22497. };
  22498. Plane.prototype.copy = function (id) {
  22499. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null);
  22500. };
  22501. return Plane;
  22502. })(_Primitive);
  22503. Primitives.Plane = Plane;
  22504. var TorusKnot = (function (_super) {
  22505. __extends(TorusKnot, _super);
  22506. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh) {
  22507. this.radius = radius;
  22508. this.tube = tube;
  22509. this.radialSegments = radialSegments;
  22510. this.tubularSegments = tubularSegments;
  22511. this.p = p;
  22512. this.q = q;
  22513. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  22514. }
  22515. TorusKnot.prototype._regenerateVertexData = function () {
  22516. return BABYLON.VertexData.CreateTorusKnot(this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q);
  22517. };
  22518. TorusKnot.prototype.copy = function (id) {
  22519. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null);
  22520. };
  22521. return TorusKnot;
  22522. })(_Primitive);
  22523. Primitives.TorusKnot = TorusKnot;
  22524. })(Geometry.Primitives || (Geometry.Primitives = {}));
  22525. var Primitives = Geometry.Primitives;
  22526. })(BABYLON.Geometry || (BABYLON.Geometry = {}));
  22527. var Geometry = BABYLON.Geometry;
  22528. })(BABYLON || (BABYLON = {}));
  22529. //# sourceMappingURL=babylon.geometry.js.map
  22530. var BABYLON;
  22531. (function (BABYLON) {
  22532. var Gamepads = (function () {
  22533. function Gamepads(ongamedpadconnected) {
  22534. var _this = this;
  22535. this.babylonGamepads = [];
  22536. this.oneGamepadConnected = false;
  22537. this.isMonitoring = false;
  22538. this.gamepadEventSupported = 'GamepadEvent' in window;
  22539. this.gamepadSupportAvailable = (navigator.getGamepads || !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  22540. 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=";
  22541. this._callbackGamepadConnected = ongamedpadconnected;
  22542. if (this.gamepadSupportAvailable) {
  22543. // Checking if the gamepad connected event is supported (like in Firefox)
  22544. if (this.gamepadEventSupported) {
  22545. window.addEventListener('gamepadconnected', function (evt) {
  22546. _this._onGamepadConnected(evt);
  22547. }, false);
  22548. window.addEventListener('gamepaddisconnected', function (evt) {
  22549. _this._onGamepadDisconnected(evt);
  22550. }, false);
  22551. } else {
  22552. this._startMonitoringGamepads();
  22553. }
  22554. if (!this.oneGamepadConnected) {
  22555. this._insertGamepadDOMInstructions();
  22556. }
  22557. } else {
  22558. this._insertGamepadDOMNotSupported();
  22559. }
  22560. }
  22561. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  22562. Gamepads.gamepadDOMInfo = document.createElement("div");
  22563. var buttonAImage = document.createElement("img");
  22564. buttonAImage.src = this.buttonADataURL;
  22565. var spanMessage = document.createElement("span");
  22566. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  22567. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  22568. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  22569. Gamepads.gamepadDOMInfo.style.position = "absolute";
  22570. Gamepads.gamepadDOMInfo.style.width = "100%";
  22571. Gamepads.gamepadDOMInfo.style.height = "48px";
  22572. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  22573. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  22574. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  22575. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  22576. buttonAImage.style.position = "relative";
  22577. buttonAImage.style.bottom = "8px";
  22578. spanMessage.style.position = "relative";
  22579. spanMessage.style.fontSize = "32px";
  22580. spanMessage.style.bottom = "32px";
  22581. spanMessage.style.color = "green";
  22582. document.body.appendChild(Gamepads.gamepadDOMInfo);
  22583. };
  22584. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  22585. Gamepads.gamepadDOMInfo = document.createElement("div");
  22586. var spanMessage = document.createElement("span");
  22587. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  22588. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  22589. Gamepads.gamepadDOMInfo.style.position = "absolute";
  22590. Gamepads.gamepadDOMInfo.style.width = "100%";
  22591. Gamepads.gamepadDOMInfo.style.height = "40px";
  22592. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  22593. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  22594. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  22595. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  22596. spanMessage.style.position = "relative";
  22597. spanMessage.style.fontSize = "32px";
  22598. spanMessage.style.color = "red";
  22599. document.body.appendChild(Gamepads.gamepadDOMInfo);
  22600. };
  22601. Gamepads.prototype.dispose = function () {
  22602. document.body.removeChild(Gamepads.gamepadDOMInfo);
  22603. };
  22604. Gamepads.prototype._onGamepadConnected = function (evt) {
  22605. var newGamepad = this._addNewGamepad(evt.gamepad);
  22606. if (this._callbackGamepadConnected)
  22607. this._callbackGamepadConnected(newGamepad);
  22608. this._startMonitoringGamepads();
  22609. };
  22610. Gamepads.prototype._addNewGamepad = function (gamepad) {
  22611. if (!this.oneGamepadConnected) {
  22612. this.oneGamepadConnected = true;
  22613. if (Gamepads.gamepadDOMInfo) {
  22614. document.body.removeChild(Gamepads.gamepadDOMInfo);
  22615. Gamepads.gamepadDOMInfo = null;
  22616. }
  22617. }
  22618. var newGamepad;
  22619. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  22620. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  22621. } else {
  22622. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  22623. }
  22624. this.babylonGamepads.push(newGamepad);
  22625. return newGamepad;
  22626. };
  22627. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  22628. for (var i in this.babylonGamepads) {
  22629. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  22630. this.babylonGamepads.splice(i, 1);
  22631. break;
  22632. }
  22633. }
  22634. // If no gamepads are left, stop the polling loop.
  22635. if (this.babylonGamepads.length == 0) {
  22636. this._stopMonitoringGamepads();
  22637. }
  22638. };
  22639. Gamepads.prototype._startMonitoringGamepads = function () {
  22640. if (!this.isMonitoring) {
  22641. this.isMonitoring = true;
  22642. this._checkGamepadsStatus();
  22643. }
  22644. };
  22645. Gamepads.prototype._stopMonitoringGamepads = function () {
  22646. this.isMonitoring = false;
  22647. };
  22648. Gamepads.prototype._checkGamepadsStatus = function () {
  22649. var _this = this;
  22650. // updating gamepad objects
  22651. this._updateGamepadObjects();
  22652. for (var i in this.babylonGamepads) {
  22653. this.babylonGamepads[i].update();
  22654. }
  22655. if (this.isMonitoring) {
  22656. if (window.requestAnimationFrame) {
  22657. window.requestAnimationFrame(function () {
  22658. _this._checkGamepadsStatus();
  22659. });
  22660. } else if (window.mozRequestAnimationFrame) {
  22661. window.mozRequestAnimationFrame(function () {
  22662. _this._checkGamepadsStatus();
  22663. });
  22664. } else if (window.webkitRequestAnimationFrame) {
  22665. window.webkitRequestAnimationFrame(function () {
  22666. _this._checkGamepadsStatus();
  22667. });
  22668. }
  22669. }
  22670. };
  22671. // This function is called only on Chrome, which does not yet support
  22672. // connection/disconnection events, but requires you to monitor
  22673. // an array for changes.
  22674. Gamepads.prototype._updateGamepadObjects = function () {
  22675. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  22676. for (var i = 0; i < gamepads.length; i++) {
  22677. if (gamepads[i]) {
  22678. if (!(gamepads[i].index in this.babylonGamepads)) {
  22679. var newGamepad = this._addNewGamepad(gamepads[i]);
  22680. if (this._callbackGamepadConnected) {
  22681. this._callbackGamepadConnected(newGamepad);
  22682. }
  22683. } else {
  22684. this.babylonGamepads[i].browserGamepad = gamepads[i];
  22685. }
  22686. }
  22687. }
  22688. };
  22689. return Gamepads;
  22690. })();
  22691. BABYLON.Gamepads = Gamepads;
  22692. var StickValues = (function () {
  22693. function StickValues(x, y) {
  22694. this.x = x;
  22695. this.y = y;
  22696. }
  22697. return StickValues;
  22698. })();
  22699. BABYLON.StickValues = StickValues;
  22700. var Gamepad = (function () {
  22701. function Gamepad(id, index, browserGamepad) {
  22702. this.id = id;
  22703. this.index = index;
  22704. this.browserGamepad = browserGamepad;
  22705. if (this.browserGamepad.axes.length >= 2) {
  22706. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  22707. }
  22708. if (this.browserGamepad.axes.length >= 4) {
  22709. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  22710. }
  22711. }
  22712. Gamepad.prototype.onleftstickchanged = function (callback) {
  22713. this._onleftstickchanged = callback;
  22714. };
  22715. Gamepad.prototype.onrightstickchanged = function (callback) {
  22716. this._onrightstickchanged = callback;
  22717. };
  22718. Object.defineProperty(Gamepad.prototype, "leftStick", {
  22719. get: function () {
  22720. return this._leftStick;
  22721. },
  22722. set: function (newValues) {
  22723. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  22724. this._onleftstickchanged(newValues);
  22725. }
  22726. this._leftStick = newValues;
  22727. },
  22728. enumerable: true,
  22729. configurable: true
  22730. });
  22731. Object.defineProperty(Gamepad.prototype, "rightStick", {
  22732. get: function () {
  22733. return this._rightStick;
  22734. },
  22735. set: function (newValues) {
  22736. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  22737. this._onrightstickchanged(newValues);
  22738. }
  22739. this._rightStick = newValues;
  22740. },
  22741. enumerable: true,
  22742. configurable: true
  22743. });
  22744. Gamepad.prototype.update = function () {
  22745. if (this._leftStick) {
  22746. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  22747. }
  22748. if (this._rightStick) {
  22749. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  22750. }
  22751. };
  22752. return Gamepad;
  22753. })();
  22754. BABYLON.Gamepad = Gamepad;
  22755. var GenericPad = (function (_super) {
  22756. __extends(GenericPad, _super);
  22757. function GenericPad(id, index, gamepad) {
  22758. _super.call(this, id, index, gamepad);
  22759. this.id = id;
  22760. this.index = index;
  22761. this.gamepad = gamepad;
  22762. this._buttons = new Array(gamepad.buttons.length);
  22763. }
  22764. GenericPad.prototype.onbuttondown = function (callback) {
  22765. this._onbuttondown = callback;
  22766. };
  22767. GenericPad.prototype.onbuttonup = function (callback) {
  22768. this._onbuttonup = callback;
  22769. };
  22770. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  22771. if (newValue !== currentValue) {
  22772. if (this._onbuttondown && newValue === 1) {
  22773. this._onbuttondown(buttonIndex);
  22774. }
  22775. if (this._onbuttonup && newValue === 0) {
  22776. this._onbuttonup(buttonIndex);
  22777. }
  22778. }
  22779. return newValue;
  22780. };
  22781. GenericPad.prototype.update = function () {
  22782. _super.prototype.update.call(this);
  22783. for (var index = 0; index < this._buttons.length; index++) {
  22784. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  22785. }
  22786. };
  22787. return GenericPad;
  22788. })(Gamepad);
  22789. BABYLON.GenericPad = GenericPad;
  22790. (function (Xbox360Button) {
  22791. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  22792. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  22793. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  22794. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  22795. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  22796. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  22797. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  22798. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  22799. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  22800. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  22801. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  22802. var Xbox360Button = BABYLON.Xbox360Button;
  22803. (function (Xbox360Dpad) {
  22804. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  22805. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  22806. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  22807. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  22808. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  22809. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  22810. var Xbox360Pad = (function (_super) {
  22811. __extends(Xbox360Pad, _super);
  22812. function Xbox360Pad() {
  22813. _super.apply(this, arguments);
  22814. this._leftTrigger = 0;
  22815. this._rightTrigger = 0;
  22816. this._buttonA = 0;
  22817. this._buttonB = 0;
  22818. this._buttonX = 0;
  22819. this._buttonY = 0;
  22820. this._buttonBack = 0;
  22821. this._buttonStart = 0;
  22822. this._buttonLB = 0;
  22823. this._buttonRB = 0;
  22824. this._buttonLeftStick = 0;
  22825. this._buttonRightStick = 0;
  22826. this._dPadUp = 0;
  22827. this._dPadDown = 0;
  22828. this._dPadLeft = 0;
  22829. this._dPadRight = 0;
  22830. }
  22831. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  22832. this._onlefttriggerchanged = callback;
  22833. };
  22834. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  22835. this._onrighttriggerchanged = callback;
  22836. };
  22837. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  22838. get: function () {
  22839. return this._leftTrigger;
  22840. },
  22841. set: function (newValue) {
  22842. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  22843. this._onlefttriggerchanged(newValue);
  22844. }
  22845. this._leftTrigger = newValue;
  22846. },
  22847. enumerable: true,
  22848. configurable: true
  22849. });
  22850. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  22851. get: function () {
  22852. return this._rightTrigger;
  22853. },
  22854. set: function (newValue) {
  22855. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  22856. this._onrighttriggerchanged(newValue);
  22857. }
  22858. this._rightTrigger = newValue;
  22859. },
  22860. enumerable: true,
  22861. configurable: true
  22862. });
  22863. Xbox360Pad.prototype.onbuttondown = function (callback) {
  22864. this._onbuttondown = callback;
  22865. };
  22866. Xbox360Pad.prototype.onbuttonup = function (callback) {
  22867. this._onbuttonup = callback;
  22868. };
  22869. Xbox360Pad.prototype.ondpaddown = function (callback) {
  22870. this._ondpaddown = callback;
  22871. };
  22872. Xbox360Pad.prototype.ondpadup = function (callback) {
  22873. this._ondpadup = callback;
  22874. };
  22875. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  22876. if (newValue !== currentValue) {
  22877. if (this._onbuttondown && newValue === 1) {
  22878. this._onbuttondown(buttonType);
  22879. }
  22880. if (this._onbuttonup && newValue === 0) {
  22881. this._onbuttonup(buttonType);
  22882. }
  22883. }
  22884. return newValue;
  22885. };
  22886. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  22887. if (newValue !== currentValue) {
  22888. if (this._ondpaddown && newValue === 1) {
  22889. this._ondpaddown(buttonType);
  22890. }
  22891. if (this._ondpadup && newValue === 0) {
  22892. this._ondpadup(buttonType);
  22893. }
  22894. }
  22895. return newValue;
  22896. };
  22897. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  22898. get: function () {
  22899. return this._buttonA;
  22900. },
  22901. set: function (value) {
  22902. this._buttonA = this._setButtonValue(value, this._buttonA, 0 /* A */);
  22903. },
  22904. enumerable: true,
  22905. configurable: true
  22906. });
  22907. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  22908. get: function () {
  22909. return this._buttonB;
  22910. },
  22911. set: function (value) {
  22912. this._buttonB = this._setButtonValue(value, this._buttonB, 1 /* B */);
  22913. },
  22914. enumerable: true,
  22915. configurable: true
  22916. });
  22917. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  22918. get: function () {
  22919. return this._buttonX;
  22920. },
  22921. set: function (value) {
  22922. this._buttonX = this._setButtonValue(value, this._buttonX, 2 /* X */);
  22923. },
  22924. enumerable: true,
  22925. configurable: true
  22926. });
  22927. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  22928. get: function () {
  22929. return this._buttonY;
  22930. },
  22931. set: function (value) {
  22932. this._buttonY = this._setButtonValue(value, this._buttonY, 3 /* Y */);
  22933. },
  22934. enumerable: true,
  22935. configurable: true
  22936. });
  22937. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  22938. get: function () {
  22939. return this._buttonStart;
  22940. },
  22941. set: function (value) {
  22942. this._buttonStart = this._setButtonValue(value, this._buttonStart, 4 /* Start */);
  22943. },
  22944. enumerable: true,
  22945. configurable: true
  22946. });
  22947. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  22948. get: function () {
  22949. return this._buttonBack;
  22950. },
  22951. set: function (value) {
  22952. this._buttonBack = this._setButtonValue(value, this._buttonBack, 5 /* Back */);
  22953. },
  22954. enumerable: true,
  22955. configurable: true
  22956. });
  22957. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  22958. get: function () {
  22959. return this._buttonLB;
  22960. },
  22961. set: function (value) {
  22962. this._buttonLB = this._setButtonValue(value, this._buttonLB, 6 /* LB */);
  22963. },
  22964. enumerable: true,
  22965. configurable: true
  22966. });
  22967. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  22968. get: function () {
  22969. return this._buttonRB;
  22970. },
  22971. set: function (value) {
  22972. this._buttonRB = this._setButtonValue(value, this._buttonRB, 7 /* RB */);
  22973. },
  22974. enumerable: true,
  22975. configurable: true
  22976. });
  22977. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  22978. get: function () {
  22979. return this._buttonLeftStick;
  22980. },
  22981. set: function (value) {
  22982. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, 8 /* LeftStick */);
  22983. },
  22984. enumerable: true,
  22985. configurable: true
  22986. });
  22987. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  22988. get: function () {
  22989. return this._buttonRightStick;
  22990. },
  22991. set: function (value) {
  22992. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, 9 /* RightStick */);
  22993. },
  22994. enumerable: true,
  22995. configurable: true
  22996. });
  22997. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  22998. get: function () {
  22999. return this._dPadUp;
  23000. },
  23001. set: function (value) {
  23002. this._dPadUp = this._setDPadValue(value, this._dPadUp, 0 /* Up */);
  23003. },
  23004. enumerable: true,
  23005. configurable: true
  23006. });
  23007. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  23008. get: function () {
  23009. return this._dPadDown;
  23010. },
  23011. set: function (value) {
  23012. this._dPadDown = this._setDPadValue(value, this._dPadDown, 1 /* Down */);
  23013. },
  23014. enumerable: true,
  23015. configurable: true
  23016. });
  23017. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  23018. get: function () {
  23019. return this._dPadLeft;
  23020. },
  23021. set: function (value) {
  23022. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, 2 /* Left */);
  23023. },
  23024. enumerable: true,
  23025. configurable: true
  23026. });
  23027. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  23028. get: function () {
  23029. return this._dPadRight;
  23030. },
  23031. set: function (value) {
  23032. this._dPadRight = this._setDPadValue(value, this._dPadRight, 3 /* Right */);
  23033. },
  23034. enumerable: true,
  23035. configurable: true
  23036. });
  23037. Xbox360Pad.prototype.update = function () {
  23038. _super.prototype.update.call(this);
  23039. this.buttonA = this.browserGamepad.buttons[0].value;
  23040. this.buttonB = this.browserGamepad.buttons[1].value;
  23041. this.buttonX = this.browserGamepad.buttons[2].value;
  23042. this.buttonY = this.browserGamepad.buttons[3].value;
  23043. this.buttonLB = this.browserGamepad.buttons[4].value;
  23044. this.buttonRB = this.browserGamepad.buttons[5].value;
  23045. this.leftTrigger = this.browserGamepad.buttons[6].value;
  23046. this.rightTrigger = this.browserGamepad.buttons[7].value;
  23047. this.buttonBack = this.browserGamepad.buttons[8].value;
  23048. this.buttonStart = this.browserGamepad.buttons[9].value;
  23049. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  23050. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  23051. this.dPadUp = this.browserGamepad.buttons[12].value;
  23052. this.dPadDown = this.browserGamepad.buttons[13].value;
  23053. this.dPadLeft = this.browserGamepad.buttons[14].value;
  23054. this.dPadRight = this.browserGamepad.buttons[15].value;
  23055. };
  23056. return Xbox360Pad;
  23057. })(Gamepad);
  23058. BABYLON.Xbox360Pad = Xbox360Pad;
  23059. })(BABYLON || (BABYLON = {}));
  23060. //# sourceMappingURL=babylon.gamepads.js.map
  23061. var BABYLON;
  23062. (function (BABYLON) {
  23063. // We're mainly based on the logic defined into the FreeCamera code
  23064. var GamepadCamera = (function (_super) {
  23065. __extends(GamepadCamera, _super);
  23066. function GamepadCamera(name, position, scene) {
  23067. var _this = this;
  23068. _super.call(this, name, position, scene);
  23069. this.angularSensibility = 200;
  23070. this.moveSensibility = 75;
  23071. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  23072. _this._onNewGameConnected(gamepad);
  23073. });
  23074. }
  23075. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  23076. // Only the first gamepad can control the camera
  23077. if (gamepad.index === 0) {
  23078. this._gamepad = gamepad;
  23079. }
  23080. };
  23081. GamepadCamera.prototype._checkInputs = function () {
  23082. if (!this._gamepad) {
  23083. return;
  23084. }
  23085. var LSValues = this._gamepad.leftStick;
  23086. var normalizedLX = LSValues.x / this.moveSensibility;
  23087. var normalizedLY = LSValues.y / this.moveSensibility;
  23088. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  23089. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  23090. var RSValues = this._gamepad.rightStick;
  23091. var normalizedRX = RSValues.x / this.angularSensibility;
  23092. var normalizedRY = RSValues.y / this.angularSensibility;
  23093. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  23094. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  23095. ;
  23096. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  23097. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x, 0, -LSValues.y), cameraTransform);
  23098. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  23099. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  23100. };
  23101. GamepadCamera.prototype.dispose = function () {
  23102. this._gamepads.dispose();
  23103. _super.prototype.dispose.call(this);
  23104. };
  23105. return GamepadCamera;
  23106. })(BABYLON.FreeCamera);
  23107. BABYLON.GamepadCamera = GamepadCamera;
  23108. })(BABYLON || (BABYLON = {}));
  23109. //# sourceMappingURL=babylon.gamepadCamera.js.map
  23110. var BABYLON;
  23111. (function (BABYLON) {
  23112. var LinesMesh = (function (_super) {
  23113. __extends(LinesMesh, _super);
  23114. function LinesMesh(name, scene, updatable) {
  23115. if (typeof updatable === "undefined") { updatable = false; }
  23116. _super.call(this, name, scene);
  23117. this.color = new BABYLON.Color3(1, 1, 1);
  23118. this.alpha = 1;
  23119. this._indices = new Array();
  23120. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  23121. attributes: ["position"],
  23122. uniforms: ["worldViewProjection", "color"],
  23123. needAlphaBlending: true
  23124. });
  23125. }
  23126. Object.defineProperty(LinesMesh.prototype, "material", {
  23127. get: function () {
  23128. return this._colorShader;
  23129. },
  23130. enumerable: true,
  23131. configurable: true
  23132. });
  23133. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  23134. get: function () {
  23135. return false;
  23136. },
  23137. enumerable: true,
  23138. configurable: true
  23139. });
  23140. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  23141. get: function () {
  23142. return false;
  23143. },
  23144. enumerable: true,
  23145. configurable: true
  23146. });
  23147. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  23148. var engine = this.getScene().getEngine();
  23149. var indexToBind = this._geometry.getIndexBuffer();
  23150. // VBOs
  23151. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  23152. // Color
  23153. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  23154. };
  23155. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  23156. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  23157. return;
  23158. }
  23159. var engine = this.getScene().getEngine();
  23160. // Draw order
  23161. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  23162. };
  23163. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  23164. return null;
  23165. };
  23166. LinesMesh.prototype.dispose = function (doNotRecurse) {
  23167. this._colorShader.dispose();
  23168. _super.prototype.dispose.call(this, doNotRecurse);
  23169. };
  23170. return LinesMesh;
  23171. })(BABYLON.Mesh);
  23172. BABYLON.LinesMesh = LinesMesh;
  23173. })(BABYLON || (BABYLON = {}));
  23174. //# sourceMappingURL=babylon.linesMesh.js.map
  23175. var BABYLON;
  23176. (function (BABYLON) {
  23177. var OutlineRenderer = (function () {
  23178. function OutlineRenderer(scene) {
  23179. this._scene = scene;
  23180. }
  23181. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  23182. if (typeof useOverlay === "undefined") { useOverlay = false; }
  23183. var scene = this._scene;
  23184. var engine = this._scene.getEngine();
  23185. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  23186. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  23187. return;
  23188. }
  23189. var mesh = subMesh.getRenderingMesh();
  23190. var material = subMesh.getMaterial();
  23191. engine.enableEffect(this._effect);
  23192. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  23193. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  23194. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  23195. // Bones
  23196. var useBones = mesh.skeleton && scene.skeletonsEnabled && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  23197. if (useBones) {
  23198. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  23199. }
  23200. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  23201. // Alpha test
  23202. if (material && material.needAlphaTesting()) {
  23203. var alphaTexture = material.getAlphaTestTexture();
  23204. this._effect.setTexture("diffuseSampler", alphaTexture);
  23205. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  23206. }
  23207. if (hardwareInstancedRendering) {
  23208. mesh._renderWithInstances(subMesh, BABYLON.Material.TriangleFillMode, batch, this._effect, engine);
  23209. } else {
  23210. if (batch.renderSelf[subMesh._id]) {
  23211. this._effect.setMatrix("world", mesh.getWorldMatrix());
  23212. // Draw
  23213. mesh._draw(subMesh, BABYLON.Material.TriangleFillMode);
  23214. }
  23215. if (batch.visibleInstances[subMesh._id]) {
  23216. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  23217. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  23218. this._effect.setMatrix("world", instance.getWorldMatrix());
  23219. // Draw
  23220. mesh._draw(subMesh, BABYLON.Material.TriangleFillMode);
  23221. }
  23222. }
  23223. }
  23224. };
  23225. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  23226. var defines = [];
  23227. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  23228. var mesh = subMesh.getMesh();
  23229. var material = subMesh.getMaterial();
  23230. // Alpha test
  23231. if (material && material.needAlphaTesting()) {
  23232. defines.push("#define ALPHATEST");
  23233. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  23234. attribs.push(BABYLON.VertexBuffer.UVKind);
  23235. defines.push("#define UV1");
  23236. }
  23237. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  23238. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  23239. defines.push("#define UV2");
  23240. }
  23241. }
  23242. // Bones
  23243. if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  23244. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  23245. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  23246. defines.push("#define BONES");
  23247. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  23248. }
  23249. // Instances
  23250. if (useInstances) {
  23251. defines.push("#define INSTANCES");
  23252. attribs.push("world0");
  23253. attribs.push("world1");
  23254. attribs.push("world2");
  23255. attribs.push("world3");
  23256. }
  23257. // Get correct effect
  23258. var join = defines.join("\n");
  23259. if (this._cachedDefines != join) {
  23260. this._cachedDefines = join;
  23261. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  23262. }
  23263. return this._effect.isReady();
  23264. };
  23265. return OutlineRenderer;
  23266. })();
  23267. BABYLON.OutlineRenderer = OutlineRenderer;
  23268. })(BABYLON || (BABYLON = {}));
  23269. //# sourceMappingURL=babylon.outlineRenderer.js.map
  23270. var BABYLON;
  23271. (function (BABYLON) {
  23272. var MeshAssetTask = (function () {
  23273. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  23274. this.name = name;
  23275. this.meshesNames = meshesNames;
  23276. this.rootUrl = rootUrl;
  23277. this.sceneFilename = sceneFilename;
  23278. this.isCompleted = false;
  23279. }
  23280. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  23281. var _this = this;
  23282. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  23283. _this.loadedMeshes = meshes;
  23284. _this.loadedParticleSystems = particleSystems;
  23285. _this.loadedSkeletons = skeletons;
  23286. _this.isCompleted = true;
  23287. if (_this.onSuccess) {
  23288. _this.onSuccess(_this);
  23289. }
  23290. onSuccess();
  23291. }, null, function () {
  23292. if (_this.onError) {
  23293. _this.onError(_this);
  23294. }
  23295. onError();
  23296. });
  23297. };
  23298. return MeshAssetTask;
  23299. })();
  23300. BABYLON.MeshAssetTask = MeshAssetTask;
  23301. var TextFileAssetTask = (function () {
  23302. function TextFileAssetTask(name, url) {
  23303. this.name = name;
  23304. this.url = url;
  23305. this.isCompleted = false;
  23306. }
  23307. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  23308. var _this = this;
  23309. BABYLON.Tools.LoadFile(this.url, function (data) {
  23310. _this.text = data;
  23311. _this.isCompleted = true;
  23312. if (_this.onSuccess) {
  23313. _this.onSuccess(_this);
  23314. }
  23315. onSuccess();
  23316. }, null, scene.database, false, function () {
  23317. if (_this.onError) {
  23318. _this.onError(_this);
  23319. }
  23320. onError();
  23321. });
  23322. };
  23323. return TextFileAssetTask;
  23324. })();
  23325. BABYLON.TextFileAssetTask = TextFileAssetTask;
  23326. var BinaryFileAssetTask = (function () {
  23327. function BinaryFileAssetTask(name, url) {
  23328. this.name = name;
  23329. this.url = url;
  23330. this.isCompleted = false;
  23331. }
  23332. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  23333. var _this = this;
  23334. BABYLON.Tools.LoadFile(this.url, function (data) {
  23335. _this.data = data;
  23336. _this.isCompleted = true;
  23337. if (_this.onSuccess) {
  23338. _this.onSuccess(_this);
  23339. }
  23340. onSuccess();
  23341. }, null, scene.database, true, function () {
  23342. if (_this.onError) {
  23343. _this.onError(_this);
  23344. }
  23345. onError();
  23346. });
  23347. };
  23348. return BinaryFileAssetTask;
  23349. })();
  23350. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  23351. var ImageAssetTask = (function () {
  23352. function ImageAssetTask(name, url) {
  23353. this.name = name;
  23354. this.url = url;
  23355. this.isCompleted = false;
  23356. }
  23357. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  23358. var _this = this;
  23359. var img = new Image();
  23360. img.onload = function () {
  23361. _this.image = img;
  23362. _this.isCompleted = true;
  23363. if (_this.onSuccess) {
  23364. _this.onSuccess(_this);
  23365. }
  23366. onSuccess();
  23367. };
  23368. img.onerror = function () {
  23369. if (_this.onError) {
  23370. _this.onError(_this);
  23371. }
  23372. onError();
  23373. };
  23374. img.src = this.url;
  23375. };
  23376. return ImageAssetTask;
  23377. })();
  23378. BABYLON.ImageAssetTask = ImageAssetTask;
  23379. var TextureAssetTask = (function () {
  23380. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  23381. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  23382. this.name = name;
  23383. this.url = url;
  23384. this.noMipmap = noMipmap;
  23385. this.invertY = invertY;
  23386. this.samplingMode = samplingMode;
  23387. this.isCompleted = false;
  23388. }
  23389. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  23390. var _this = this;
  23391. var onload = function () {
  23392. _this.isCompleted = true;
  23393. if (_this.onSuccess) {
  23394. _this.onSuccess(_this);
  23395. }
  23396. onSuccess();
  23397. };
  23398. var onerror = function () {
  23399. if (_this.onError) {
  23400. _this.onError(_this);
  23401. }
  23402. onError();
  23403. };
  23404. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onError);
  23405. };
  23406. return TextureAssetTask;
  23407. })();
  23408. BABYLON.TextureAssetTask = TextureAssetTask;
  23409. var AssetsManager = (function () {
  23410. function AssetsManager(scene) {
  23411. this._tasks = new Array();
  23412. this._waitingTasksCount = 0;
  23413. this.useDefaultLoadingScreen = true;
  23414. this._scene = scene;
  23415. }
  23416. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  23417. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  23418. this._tasks.push(task);
  23419. return task;
  23420. };
  23421. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  23422. var task = new TextFileAssetTask(taskName, url);
  23423. this._tasks.push(task);
  23424. return task;
  23425. };
  23426. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  23427. var task = new BinaryFileAssetTask(taskName, url);
  23428. this._tasks.push(task);
  23429. return task;
  23430. };
  23431. AssetsManager.prototype.addImageTask = function (taskName, url) {
  23432. var task = new ImageAssetTask(taskName, url);
  23433. this._tasks.push(task);
  23434. return task;
  23435. };
  23436. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  23437. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  23438. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  23439. this._tasks.push(task);
  23440. return task;
  23441. };
  23442. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  23443. this._waitingTasksCount--;
  23444. if (this._waitingTasksCount === 0) {
  23445. if (this.onFinish) {
  23446. this.onFinish(this._tasks);
  23447. }
  23448. this._scene.getEngine().hideLoadingUI();
  23449. }
  23450. };
  23451. AssetsManager.prototype._runTask = function (task) {
  23452. var _this = this;
  23453. task.run(this._scene, function () {
  23454. if (_this.onTaskSuccess) {
  23455. _this.onTaskSuccess(task);
  23456. }
  23457. _this._decreaseWaitingTasksCount();
  23458. }, function () {
  23459. if (_this.onTaskError) {
  23460. _this.onTaskError(task);
  23461. }
  23462. _this._decreaseWaitingTasksCount();
  23463. });
  23464. };
  23465. AssetsManager.prototype.reset = function () {
  23466. this._tasks = new Array();
  23467. return this;
  23468. };
  23469. AssetsManager.prototype.load = function () {
  23470. this._waitingTasksCount = this._tasks.length;
  23471. if (this._waitingTasksCount === 0) {
  23472. if (this.onFinish) {
  23473. this.onFinish(this._tasks);
  23474. }
  23475. return this;
  23476. }
  23477. if (this.useDefaultLoadingScreen) {
  23478. this._scene.getEngine().displayLoadingUI();
  23479. }
  23480. for (var index = 0; index < this._tasks.length; index++) {
  23481. var task = this._tasks[index];
  23482. this._runTask(task);
  23483. }
  23484. return this;
  23485. };
  23486. return AssetsManager;
  23487. })();
  23488. BABYLON.AssetsManager = AssetsManager;
  23489. })(BABYLON || (BABYLON = {}));
  23490. //# sourceMappingURL=babylon.assetsManager.js.map
  23491. var BABYLON;
  23492. (function (BABYLON) {
  23493. var VRDeviceOrientationCamera = (function (_super) {
  23494. __extends(VRDeviceOrientationCamera, _super);
  23495. function VRDeviceOrientationCamera(name, position, scene) {
  23496. _super.call(this, name, position, scene);
  23497. this._alpha = 0;
  23498. this._beta = 0;
  23499. this._gamma = 0;
  23500. }
  23501. VRDeviceOrientationCamera.prototype._onOrientationEvent = function (evt) {
  23502. this._alpha = +evt.alpha | 0;
  23503. this._beta = +evt.beta | 0;
  23504. this._gamma = +evt.gamma | 0;
  23505. if (this._gamma < 0) {
  23506. this._gamma = 90 + this._gamma;
  23507. } else {
  23508. // Incline it in the correct angle.
  23509. this._gamma = 270 - this._gamma;
  23510. }
  23511. this.rotation.x = this._gamma / 180.0 * Math.PI;
  23512. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  23513. this.rotation.z = this._beta / 180.0 * Math.PI;
  23514. };
  23515. return VRDeviceOrientationCamera;
  23516. })(BABYLON.OculusCamera);
  23517. BABYLON.VRDeviceOrientationCamera = VRDeviceOrientationCamera;
  23518. })(BABYLON || (BABYLON = {}));
  23519. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  23520. var BABYLON;
  23521. (function (BABYLON) {
  23522. var WebVRCamera = (function (_super) {
  23523. __extends(WebVRCamera, _super);
  23524. function WebVRCamera(name, position, scene) {
  23525. _super.call(this, name, position, scene);
  23526. this._hmdDevice = null;
  23527. this._sensorDevice = null;
  23528. this._cacheState = null;
  23529. this._cacheQuaternion = new BABYLON.Quaternion();
  23530. this._cacheRotation = BABYLON.Vector3.Zero();
  23531. this._vrEnabled = false;
  23532. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  23533. }
  23534. WebVRCamera.prototype._getWebVRDevices = function (devices) {
  23535. var size = devices.length;
  23536. var i = 0;
  23537. // Reset devices.
  23538. this._sensorDevice = null;
  23539. this._hmdDevice = null;
  23540. while (i < size && this._hmdDevice === null) {
  23541. if (devices[i] instanceof HMDVRDevice) {
  23542. this._hmdDevice = devices[i];
  23543. }
  23544. i++;
  23545. }
  23546. i = 0;
  23547. while (i < size && this._sensorDevice === null) {
  23548. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  23549. this._sensorDevice = devices[i];
  23550. }
  23551. i++;
  23552. }
  23553. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  23554. };
  23555. WebVRCamera.prototype._update = function () {
  23556. if (this._vrEnabled) {
  23557. this._cacheState = this._sensorDevice.getState();
  23558. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  23559. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  23560. this.rotation.x = -this._cacheRotation.z;
  23561. this.rotation.y = -this._cacheRotation.y;
  23562. this.rotation.z = this._cacheRotation.x;
  23563. }
  23564. _super.prototype._update.call(this);
  23565. };
  23566. WebVRCamera.prototype.attachControl = function (element, noPreventDefault) {
  23567. _super.prototype.attachControl.call(this, element, noPreventDefault);
  23568. if (navigator.getVRDevices) {
  23569. navigator.getVRDevices().then(this._getWebVRDevices);
  23570. } else if (navigator.mozGetVRDevices) {
  23571. navigator.mozGetVRDevices(this._getWebVRDevices);
  23572. }
  23573. };
  23574. WebVRCamera.prototype.detachControl = function (element) {
  23575. _super.prototype.detachControl.call(this, element);
  23576. this._vrEnabled = false;
  23577. };
  23578. return WebVRCamera;
  23579. })(BABYLON.OculusCamera);
  23580. BABYLON.WebVRCamera = WebVRCamera;
  23581. })(BABYLON || (BABYLON = {}));
  23582. //# sourceMappingURL=babylon.webVRCamera.js.map
  23583. var BABYLON;
  23584. (function (BABYLON) {
  23585. // Standard optimizations
  23586. var SceneOptimization = (function () {
  23587. function SceneOptimization(priority) {
  23588. if (typeof priority === "undefined") { priority = 0; }
  23589. this.priority = priority;
  23590. this.apply = function (scene) {
  23591. return true;
  23592. };
  23593. }
  23594. return SceneOptimization;
  23595. })();
  23596. BABYLON.SceneOptimization = SceneOptimization;
  23597. var TextureOptimization = (function (_super) {
  23598. __extends(TextureOptimization, _super);
  23599. function TextureOptimization(priority, maximumSize) {
  23600. if (typeof priority === "undefined") { priority = 0; }
  23601. if (typeof maximumSize === "undefined") { maximumSize = 1024; }
  23602. var _this = this;
  23603. _super.call(this, priority);
  23604. this.priority = priority;
  23605. this.maximumSize = maximumSize;
  23606. this.apply = function (scene) {
  23607. var allDone = true;
  23608. for (var index = 0; index < scene.textures.length; index++) {
  23609. var texture = scene.textures[index];
  23610. if (!texture.canRescale) {
  23611. continue;
  23612. }
  23613. var currentSize = texture.getSize();
  23614. var maxDimension = Math.max(currentSize.width, currentSize.height);
  23615. if (maxDimension > _this.maximumSize) {
  23616. texture.scale(0.5);
  23617. allDone = false;
  23618. }
  23619. }
  23620. return allDone;
  23621. };
  23622. }
  23623. return TextureOptimization;
  23624. })(SceneOptimization);
  23625. BABYLON.TextureOptimization = TextureOptimization;
  23626. var HardwareScalingOptimization = (function (_super) {
  23627. __extends(HardwareScalingOptimization, _super);
  23628. function HardwareScalingOptimization(priority, maximumScale) {
  23629. if (typeof priority === "undefined") { priority = 0; }
  23630. if (typeof maximumScale === "undefined") { maximumScale = 2; }
  23631. var _this = this;
  23632. _super.call(this, priority);
  23633. this.priority = priority;
  23634. this.maximumScale = maximumScale;
  23635. this._currentScale = 1;
  23636. this.apply = function (scene) {
  23637. _this._currentScale++;
  23638. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  23639. return _this._currentScale >= _this.maximumScale;
  23640. };
  23641. }
  23642. return HardwareScalingOptimization;
  23643. })(SceneOptimization);
  23644. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  23645. var ShadowsOptimization = (function (_super) {
  23646. __extends(ShadowsOptimization, _super);
  23647. function ShadowsOptimization() {
  23648. _super.apply(this, arguments);
  23649. this.apply = function (scene) {
  23650. scene.shadowsEnabled = false;
  23651. return true;
  23652. };
  23653. }
  23654. return ShadowsOptimization;
  23655. })(SceneOptimization);
  23656. BABYLON.ShadowsOptimization = ShadowsOptimization;
  23657. var PostProcessesOptimization = (function (_super) {
  23658. __extends(PostProcessesOptimization, _super);
  23659. function PostProcessesOptimization() {
  23660. _super.apply(this, arguments);
  23661. this.apply = function (scene) {
  23662. scene.postProcessesEnabled = false;
  23663. return true;
  23664. };
  23665. }
  23666. return PostProcessesOptimization;
  23667. })(SceneOptimization);
  23668. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  23669. var LensFlaresOptimization = (function (_super) {
  23670. __extends(LensFlaresOptimization, _super);
  23671. function LensFlaresOptimization() {
  23672. _super.apply(this, arguments);
  23673. this.apply = function (scene) {
  23674. scene.lensFlaresEnabled = false;
  23675. return true;
  23676. };
  23677. }
  23678. return LensFlaresOptimization;
  23679. })(SceneOptimization);
  23680. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  23681. var ParticlesOptimization = (function (_super) {
  23682. __extends(ParticlesOptimization, _super);
  23683. function ParticlesOptimization() {
  23684. _super.apply(this, arguments);
  23685. this.apply = function (scene) {
  23686. scene.particlesEnabled = false;
  23687. return true;
  23688. };
  23689. }
  23690. return ParticlesOptimization;
  23691. })(SceneOptimization);
  23692. BABYLON.ParticlesOptimization = ParticlesOptimization;
  23693. var RenderTargetsOptimization = (function (_super) {
  23694. __extends(RenderTargetsOptimization, _super);
  23695. function RenderTargetsOptimization() {
  23696. _super.apply(this, arguments);
  23697. this.apply = function (scene) {
  23698. scene.renderTargetsEnabled = false;
  23699. return true;
  23700. };
  23701. }
  23702. return RenderTargetsOptimization;
  23703. })(SceneOptimization);
  23704. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  23705. var MergeMeshesOptimization = (function (_super) {
  23706. __extends(MergeMeshesOptimization, _super);
  23707. function MergeMeshesOptimization() {
  23708. _super.apply(this, arguments);
  23709. var _this = this;
  23710. this._canBeMerged = function (abstractMesh) {
  23711. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  23712. return false;
  23713. }
  23714. var mesh = abstractMesh;
  23715. if (!mesh.isVisible || !mesh.isEnabled()) {
  23716. return false;
  23717. }
  23718. if (mesh.instances.length > 0) {
  23719. return false;
  23720. }
  23721. if (mesh.skeleton || mesh.hasLODLevels) {
  23722. return false;
  23723. }
  23724. return true;
  23725. };
  23726. this.apply = function (scene) {
  23727. var globalPool = scene.meshes.slice(0);
  23728. var globalLength = globalPool.length;
  23729. for (var index = 0; index < globalLength; index++) {
  23730. var currentPool = new Array();
  23731. var current = globalPool[index];
  23732. // Checks
  23733. if (!_this._canBeMerged(current)) {
  23734. continue;
  23735. }
  23736. currentPool.push(current);
  23737. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  23738. var otherMesh = globalPool[subIndex];
  23739. if (!_this._canBeMerged(otherMesh)) {
  23740. continue;
  23741. }
  23742. if (otherMesh.material !== current.material) {
  23743. continue;
  23744. }
  23745. if (otherMesh.checkCollisions !== current.checkCollisions) {
  23746. continue;
  23747. }
  23748. currentPool.push(otherMesh);
  23749. globalLength--;
  23750. globalPool.splice(subIndex, 1);
  23751. subIndex--;
  23752. }
  23753. if (currentPool.length < 2) {
  23754. continue;
  23755. }
  23756. // Merge meshes
  23757. BABYLON.Mesh.MergeMeshes(currentPool);
  23758. }
  23759. return true;
  23760. };
  23761. }
  23762. return MergeMeshesOptimization;
  23763. })(SceneOptimization);
  23764. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  23765. // Options
  23766. var SceneOptimizerOptions = (function () {
  23767. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  23768. if (typeof targetFrameRate === "undefined") { targetFrameRate = 60; }
  23769. if (typeof trackerDuration === "undefined") { trackerDuration = 2000; }
  23770. this.targetFrameRate = targetFrameRate;
  23771. this.trackerDuration = trackerDuration;
  23772. this.optimizations = new Array();
  23773. }
  23774. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  23775. var result = new SceneOptimizerOptions(targetFrameRate);
  23776. var priority = 0;
  23777. result.optimizations.push(new MergeMeshesOptimization(priority));
  23778. result.optimizations.push(new ShadowsOptimization(priority));
  23779. result.optimizations.push(new LensFlaresOptimization(priority));
  23780. // Next priority
  23781. priority++;
  23782. result.optimizations.push(new PostProcessesOptimization(priority));
  23783. result.optimizations.push(new ParticlesOptimization(priority));
  23784. // Next priority
  23785. priority++;
  23786. result.optimizations.push(new TextureOptimization(priority, 1024));
  23787. return result;
  23788. };
  23789. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  23790. var result = new SceneOptimizerOptions(targetFrameRate);
  23791. var priority = 0;
  23792. result.optimizations.push(new MergeMeshesOptimization(priority));
  23793. result.optimizations.push(new ShadowsOptimization(priority));
  23794. result.optimizations.push(new LensFlaresOptimization(priority));
  23795. // Next priority
  23796. priority++;
  23797. result.optimizations.push(new PostProcessesOptimization(priority));
  23798. result.optimizations.push(new ParticlesOptimization(priority));
  23799. // Next priority
  23800. priority++;
  23801. result.optimizations.push(new TextureOptimization(priority, 512));
  23802. // Next priority
  23803. priority++;
  23804. result.optimizations.push(new RenderTargetsOptimization(priority));
  23805. // Next priority
  23806. priority++;
  23807. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  23808. return result;
  23809. };
  23810. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  23811. var result = new SceneOptimizerOptions(targetFrameRate);
  23812. var priority = 0;
  23813. result.optimizations.push(new MergeMeshesOptimization(priority));
  23814. result.optimizations.push(new ShadowsOptimization(priority));
  23815. result.optimizations.push(new LensFlaresOptimization(priority));
  23816. // Next priority
  23817. priority++;
  23818. result.optimizations.push(new PostProcessesOptimization(priority));
  23819. result.optimizations.push(new ParticlesOptimization(priority));
  23820. // Next priority
  23821. priority++;
  23822. result.optimizations.push(new TextureOptimization(priority, 256));
  23823. // Next priority
  23824. priority++;
  23825. result.optimizations.push(new RenderTargetsOptimization(priority));
  23826. // Next priority
  23827. priority++;
  23828. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  23829. return result;
  23830. };
  23831. return SceneOptimizerOptions;
  23832. })();
  23833. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  23834. // Scene optimizer tool
  23835. var SceneOptimizer = (function () {
  23836. function SceneOptimizer() {
  23837. }
  23838. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  23839. // TODO: add an epsilon
  23840. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  23841. if (onSuccess) {
  23842. onSuccess();
  23843. }
  23844. return;
  23845. }
  23846. // Apply current level of optimizations
  23847. var allDone = true;
  23848. var noOptimizationApplied = true;
  23849. for (var index = 0; index < options.optimizations.length; index++) {
  23850. var optimization = options.optimizations[index];
  23851. if (optimization.priority === currentPriorityLevel) {
  23852. noOptimizationApplied = false;
  23853. allDone = allDone && optimization.apply(scene);
  23854. }
  23855. }
  23856. // If no optimization was applied, this is a failure :(
  23857. if (noOptimizationApplied) {
  23858. if (onFailure) {
  23859. onFailure();
  23860. }
  23861. return;
  23862. }
  23863. // If all optimizations were done, move to next level
  23864. if (allDone) {
  23865. currentPriorityLevel++;
  23866. }
  23867. // Let's the system running for a specific amount of time before checking FPS
  23868. scene.executeWhenReady(function () {
  23869. setTimeout(function () {
  23870. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  23871. }, options.trackerDuration);
  23872. });
  23873. };
  23874. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  23875. if (!options) {
  23876. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  23877. }
  23878. // Let's the system running for a specific amount of time before checking FPS
  23879. scene.executeWhenReady(function () {
  23880. setTimeout(function () {
  23881. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  23882. }, options.trackerDuration);
  23883. });
  23884. };
  23885. return SceneOptimizer;
  23886. })();
  23887. BABYLON.SceneOptimizer = SceneOptimizer;
  23888. })(BABYLON || (BABYLON = {}));
  23889. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  23890. var BABYLON;
  23891. (function (BABYLON) {
  23892. (function (Internals) {
  23893. var MeshLODLevel = (function () {
  23894. function MeshLODLevel(distance, mesh) {
  23895. this.distance = distance;
  23896. this.mesh = mesh;
  23897. }
  23898. return MeshLODLevel;
  23899. })();
  23900. Internals.MeshLODLevel = MeshLODLevel;
  23901. })(BABYLON.Internals || (BABYLON.Internals = {}));
  23902. var Internals = BABYLON.Internals;
  23903. })(BABYLON || (BABYLON = {}));
  23904. //# sourceMappingURL=babylon.meshLODLevel.js.map
  23905. var BABYLON;
  23906. (function (BABYLON) {
  23907. var AudioEngine = (function () {
  23908. function AudioEngine() {
  23909. this.audioContext = null;
  23910. this.canUseWebAudio = false;
  23911. try {
  23912. if (typeof AudioContext !== 'undefined') {
  23913. this.audioContext = new AudioContext();
  23914. this.canUseWebAudio = true;
  23915. } else if (typeof webkitAudioContext !== 'undefined') {
  23916. this.audioContext = new webkitAudioContext();
  23917. this.canUseWebAudio = true;
  23918. }
  23919. } catch (e) {
  23920. this.canUseWebAudio = false;
  23921. }
  23922. // create a global volume gain node
  23923. if (this.canUseWebAudio) {
  23924. this.masterGain = this.audioContext.createGain();
  23925. this.masterGain.gain.value = 1;
  23926. this.masterGain.connect(this.audioContext.destination);
  23927. }
  23928. }
  23929. AudioEngine.prototype.getGlobalVolume = function () {
  23930. if (this.canUseWebAudio) {
  23931. return this.masterGain.gain.value;
  23932. } else {
  23933. return -1;
  23934. }
  23935. };
  23936. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  23937. if (this.canUseWebAudio) {
  23938. this.masterGain.gain.value = newVolume;
  23939. }
  23940. };
  23941. return AudioEngine;
  23942. })();
  23943. BABYLON.AudioEngine = AudioEngine;
  23944. })(BABYLON || (BABYLON = {}));
  23945. //# sourceMappingURL=babylon.audioengine.js.map
  23946. var BABYLON;
  23947. (function (BABYLON) {
  23948. var Sound = (function () {
  23949. /**
  23950. * Create a sound and attach it to a scene
  23951. * @param name Name of your sound
  23952. * @param url Url to the sound to load async
  23953. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  23954. * @param options Objects to provide with the current available options: autoplay, loop, distanceMax
  23955. */
  23956. function Sound(name, url, scene, readyToPlayCallback, options) {
  23957. var _this = this;
  23958. this.maxDistance = 20;
  23959. this.autoplay = false;
  23960. this.loop = false;
  23961. this.useBabylonJSAttenuation = true;
  23962. this._position = BABYLON.Vector3.Zero();
  23963. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  23964. this._volume = 1;
  23965. this._isLoaded = false;
  23966. this._isReadyToPlay = false;
  23967. this._isPlaying = false;
  23968. this._isDirectional = false;
  23969. // Used if you'd like to create a directional sound.
  23970. // If not set, the sound will be omnidirectional
  23971. this._coneInnerAngle = null;
  23972. this._coneOuterAngle = null;
  23973. this._coneOuterGain = null;
  23974. this._name = name;
  23975. this._scene = scene;
  23976. this._audioEngine = this._scene.getEngine().getAudioEngine();
  23977. this._readyToPlayCallback = readyToPlayCallback;
  23978. this._attenuationFunction = function (currentVolume, currentDistance, maxDistance) {
  23979. return currentVolume * (1 - currentDistance / maxDistance);
  23980. };
  23981. if (options) {
  23982. if (options.maxDistance) {
  23983. this.maxDistance = options.maxDistance;
  23984. }
  23985. if (options.autoplay) {
  23986. this.autoplay = options.autoplay;
  23987. }
  23988. if (options.loop) {
  23989. this.loop = options.loop;
  23990. }
  23991. if (options.volume) {
  23992. this._volume = options.volume;
  23993. }
  23994. if (options.useBabylonJSAttenuation) {
  23995. this.useBabylonJSAttenuation = options.useBabylonJSAttenuation;
  23996. }
  23997. }
  23998. if (this._audioEngine.canUseWebAudio) {
  23999. this._soundGain = this._audioEngine.audioContext.createGain();
  24000. this._soundGain.gain.value = this._volume;
  24001. this._soundPanner = this._audioEngine.audioContext.createPanner();
  24002. this._soundPanner.connect(this._soundGain);
  24003. this._scene.mainSoundTrack.AddSound(this);
  24004. BABYLON.Tools.LoadFile(url, function (data) {
  24005. _this._soundLoaded(data);
  24006. }, null, null, true);
  24007. }
  24008. }
  24009. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  24010. if (this._audioEngine.canUseWebAudio) {
  24011. this._soundGain.disconnect();
  24012. this._soundGain.connect(soundTrackAudioNode);
  24013. }
  24014. };
  24015. /**
  24016. * Transform this sound into a directional source
  24017. * @param coneInnerAngle Size of the inner cone in degree
  24018. * @param coneOuterAngle Size of the outer cone in degree
  24019. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  24020. */
  24021. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  24022. if (coneOuterAngle < coneInnerAngle) {
  24023. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  24024. return;
  24025. }
  24026. this._coneInnerAngle = coneInnerAngle;
  24027. this._coneOuterAngle = coneOuterAngle;
  24028. this._coneOuterGain = coneOuterGain;
  24029. this._isDirectional = true;
  24030. if (this._isPlaying && this.loop) {
  24031. this.stop();
  24032. this.play();
  24033. }
  24034. };
  24035. Sound.prototype.setPosition = function (newPosition) {
  24036. this._position = newPosition;
  24037. if (this._isPlaying) {
  24038. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  24039. }
  24040. };
  24041. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  24042. this._localDirection = newLocalDirection;
  24043. if (this._connectedMesh && this._isPlaying) {
  24044. this._updateDirection();
  24045. }
  24046. };
  24047. Sound.prototype._updateDirection = function () {
  24048. var mat = this._connectedMesh.getWorldMatrix();
  24049. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  24050. direction.normalize();
  24051. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  24052. };
  24053. Sound.prototype.updateDistanceFromListener = function () {
  24054. if (this._connectedMesh) {
  24055. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  24056. if (this.useBabylonJSAttenuation) {
  24057. if (distance < this.maxDistance) {
  24058. //this._soundGain.gain.value = this._volume * (1 - distance / this.maxDistance);
  24059. this._soundGain.gain.value = this._attenuationFunction(this._volume, distance, this.maxDistance);
  24060. } else {
  24061. this._soundGain.gain.value = 0;
  24062. }
  24063. }
  24064. }
  24065. };
  24066. Sound.prototype.setAttenuationFunction = function (callback) {
  24067. this._attenuationFunction = callback;
  24068. };
  24069. /**
  24070. * Play the sound
  24071. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  24072. */
  24073. Sound.prototype.play = function (time) {
  24074. if (this._isReadyToPlay) {
  24075. try {
  24076. var startTime = time ? this._audioEngine.audioContext.currentTime + time : 0;
  24077. this._soundSource = this._audioEngine.audioContext.createBufferSource();
  24078. this._soundSource.buffer = this._audioBuffer;
  24079. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  24080. if (this._isDirectional) {
  24081. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  24082. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  24083. this._soundPanner.coneOuterGain = this._coneOuterGain;
  24084. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  24085. }
  24086. this._soundSource.connect(this._soundPanner);
  24087. this._soundSource.loop = this.loop;
  24088. this._soundSource.start(startTime);
  24089. this._isPlaying = true;
  24090. } catch (ex) {
  24091. BABYLON.Tools.Error("Error while trying to play audio: " + this._name + ", " + ex.message);
  24092. }
  24093. }
  24094. };
  24095. /**
  24096. * Stop the sound
  24097. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  24098. */
  24099. Sound.prototype.stop = function (time) {
  24100. var stopTime = time ? this._audioEngine.audioContext.currentTime + time : 0;
  24101. this._soundSource.stop(stopTime);
  24102. this._isPlaying = false;
  24103. };
  24104. Sound.prototype.pause = function () {
  24105. //this._soundSource.p
  24106. };
  24107. Sound.prototype.setVolume = function (newVolume) {
  24108. this._volume = newVolume;
  24109. };
  24110. Sound.prototype.getVolume = function () {
  24111. return this._volume;
  24112. };
  24113. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  24114. var _this = this;
  24115. this._connectedMesh = meshToConnectTo;
  24116. meshToConnectTo.registerAfterWorldMatrixUpdate(function (connectedMesh) {
  24117. return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh);
  24118. });
  24119. };
  24120. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  24121. this.setPosition(connectedMesh.position);
  24122. if (this._isDirectional && this._isPlaying) {
  24123. this._updateDirection();
  24124. }
  24125. };
  24126. Sound.prototype._soundLoaded = function (audioData) {
  24127. var _this = this;
  24128. this._isLoaded = true;
  24129. this._audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  24130. _this._audioBuffer = buffer;
  24131. _this._isReadyToPlay = true;
  24132. if (_this.autoplay) {
  24133. _this.play();
  24134. }
  24135. if (_this._readyToPlayCallback) {
  24136. _this._readyToPlayCallback();
  24137. }
  24138. }, function (error) {
  24139. BABYLON.Tools.Error("Error while decoding audio data: " + error.err);
  24140. });
  24141. };
  24142. return Sound;
  24143. })();
  24144. BABYLON.Sound = Sound;
  24145. })(BABYLON || (BABYLON = {}));
  24146. //# sourceMappingURL=babylon.sound.js.map
  24147. var BABYLON;
  24148. (function (BABYLON) {
  24149. var SoundTrack = (function () {
  24150. function SoundTrack(scene, options) {
  24151. this.id = -1;
  24152. this._isMainTrack = false;
  24153. this._scene = scene;
  24154. this._audioEngine = scene.getEngine().getAudioEngine();
  24155. this.soundCollection = new Array();
  24156. if (this._audioEngine.canUseWebAudio) {
  24157. this._trackGain = this._audioEngine.audioContext.createGain();
  24158. //this._trackConvolver = this._audioEngine.audioContext.createConvolver();
  24159. //this._trackConvolver.connect(this._trackGain);
  24160. this._trackGain.connect(this._audioEngine.masterGain);
  24161. if (options) {
  24162. if (options.volume) {
  24163. this._trackGain.gain.value = options.volume;
  24164. }
  24165. if (options.mainTrack) {
  24166. this._isMainTrack = options.mainTrack;
  24167. }
  24168. }
  24169. }
  24170. if (!this._isMainTrack) {
  24171. this._scene.soundTracks.push(this);
  24172. this.id = this._scene.soundTracks.length - 1;
  24173. }
  24174. }
  24175. SoundTrack.prototype.AddSound = function (sound) {
  24176. sound.connectToSoundTrackAudioNode(this._trackGain);
  24177. if (sound.soundTrackId) {
  24178. if (sound.soundTrackId === -1) {
  24179. this._scene.mainSoundTrack.RemoveSound(sound);
  24180. } else {
  24181. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  24182. }
  24183. }
  24184. this.soundCollection.push(sound);
  24185. sound.soundTrackId = this.id;
  24186. };
  24187. SoundTrack.prototype.RemoveSound = function (sound) {
  24188. var index = this.soundCollection.indexOf(sound);
  24189. if (index !== -1) {
  24190. this.soundCollection.splice(index, 1);
  24191. }
  24192. };
  24193. SoundTrack.prototype.setVolume = function (newVolume) {
  24194. if (this._audioEngine.canUseWebAudio) {
  24195. this._trackGain.gain.value = newVolume;
  24196. }
  24197. };
  24198. return SoundTrack;
  24199. })();
  24200. BABYLON.SoundTrack = SoundTrack;
  24201. })(BABYLON || (BABYLON = {}));
  24202. //# sourceMappingURL=babylon.soundtrack.js.map
  24203. var BABYLON;
  24204. (function (BABYLON) {
  24205. var DebugLayer = (function () {
  24206. function DebugLayer(scene) {
  24207. var _this = this;
  24208. this._enabled = false;
  24209. this._labelsEnabled = false;
  24210. this._displayStatistics = true;
  24211. this._displayTree = false;
  24212. this._displayLogs = false;
  24213. this._identityMatrix = BABYLON.Matrix.Identity();
  24214. this.axisRatio = 0.02;
  24215. this.accentColor = "orange";
  24216. this._scene = scene;
  24217. this._syncPositions = function () {
  24218. var engine = _this._scene.getEngine();
  24219. var canvasRect = engine.getRenderingCanvasClientRect();
  24220. if (_this._showUI) {
  24221. _this._statsDiv.style.left = (canvasRect.width - 310) + "px";
  24222. _this._statsDiv.style.top = (canvasRect.height - 370) + "px";
  24223. _this._statsDiv.style.width = "300px";
  24224. _this._statsDiv.style.height = "360px";
  24225. _this._statsSubsetDiv.style.maxHeight = (canvasRect.height - 60) + "px";
  24226. _this._optionsDiv.style.left = "0px";
  24227. _this._optionsDiv.style.top = "10px";
  24228. _this._optionsDiv.style.width = "200px";
  24229. _this._optionsDiv.style.height = "auto";
  24230. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  24231. _this._logDiv.style.left = "0px";
  24232. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  24233. _this._logDiv.style.width = "600px";
  24234. _this._logDiv.style.height = "160px";
  24235. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  24236. _this._treeDiv.style.top = "10px";
  24237. _this._treeDiv.style.width = "300px";
  24238. _this._treeDiv.style.height = "auto";
  24239. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 430) + "px";
  24240. }
  24241. _this._globalDiv.style.left = canvasRect.left + "px";
  24242. _this._globalDiv.style.top = canvasRect.top + "px";
  24243. _this._drawingCanvas.style.left = "0px";
  24244. _this._drawingCanvas.style.top = "0px";
  24245. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  24246. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  24247. var devicePixelRatio = window.devicePixelRatio || 1;
  24248. var context = _this._drawingContext;
  24249. var backingStoreRatio = context.webkitBackingStorePixelRatio || context.mozBackingStorePixelRatio || context.msBackingStorePixelRatio || context.oBackingStorePixelRatio || context.backingStorePixelRatio || 1;
  24250. _this._ratio = devicePixelRatio / backingStoreRatio;
  24251. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  24252. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  24253. };
  24254. this._onCanvasClick = function (evt) {
  24255. _this._clickPosition = {
  24256. x: evt.clientX * _this._ratio,
  24257. y: evt.clientY * _this._ratio
  24258. };
  24259. };
  24260. this._syncData = function () {
  24261. if (_this._showUI) {
  24262. if (_this._displayStatistics) {
  24263. _this._displayStats();
  24264. _this._statsDiv.style.display = "";
  24265. } else {
  24266. _this._statsDiv.style.display = "none";
  24267. }
  24268. if (_this._displayLogs) {
  24269. _this._logDiv.style.display = "";
  24270. } else {
  24271. _this._logDiv.style.display = "none";
  24272. }
  24273. if (_this._displayTree) {
  24274. _this._treeDiv.style.display = "";
  24275. if (_this._needToRefreshMeshesTree) {
  24276. _this._needToRefreshMeshesTree = false;
  24277. _this._refreshMeshesTreeContent();
  24278. }
  24279. } else {
  24280. _this._treeDiv.style.display = "none";
  24281. }
  24282. }
  24283. if (_this._labelsEnabled || !_this._showUI) {
  24284. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  24285. var engine = _this._scene.getEngine();
  24286. var viewport = _this._scene.activeCamera.viewport;
  24287. var globalViewport = viewport.toGlobal(engine);
  24288. // Meshes
  24289. var meshes = _this._scene.getActiveMeshes();
  24290. for (var index = 0; index < meshes.length; index++) {
  24291. var mesh = meshes.data[index];
  24292. var position = mesh.getBoundingInfo().boundingSphere.center;
  24293. var projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._scene.getTransformMatrix(), globalViewport);
  24294. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  24295. _this._renderAxis(projectedPosition, mesh, globalViewport);
  24296. }
  24297. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  24298. _this._renderLabel(mesh.name, projectedPosition, 12, function () {
  24299. mesh.renderOverlay = !mesh.renderOverlay;
  24300. }, function () {
  24301. return mesh.renderOverlay ? 'red' : 'black';
  24302. });
  24303. }
  24304. }
  24305. // Cameras
  24306. var cameras = _this._scene.cameras;
  24307. for (index = 0; index < cameras.length; index++) {
  24308. var camera = cameras[index];
  24309. if (camera === _this._scene.activeCamera) {
  24310. continue;
  24311. }
  24312. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._scene.getTransformMatrix(), globalViewport);
  24313. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  24314. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  24315. _this._scene.activeCamera.detachControl(engine.getRenderingCanvas());
  24316. _this._scene.activeCamera = camera;
  24317. _this._scene.activeCamera.attachControl(engine.getRenderingCanvas());
  24318. }, function () {
  24319. return "purple";
  24320. });
  24321. }
  24322. }
  24323. // Lights
  24324. var lights = _this._scene.lights;
  24325. for (index = 0; index < lights.length; index++) {
  24326. var light = lights[index];
  24327. if (light.position) {
  24328. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._scene.getTransformMatrix(), globalViewport);
  24329. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  24330. _this._renderLabel(light.name, projectedPosition, -20, function () {
  24331. light.setEnabled(!light.isEnabled());
  24332. }, function () {
  24333. return light.isEnabled() ? "orange" : "gray";
  24334. });
  24335. }
  24336. }
  24337. }
  24338. }
  24339. _this._clickPosition = undefined;
  24340. };
  24341. }
  24342. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  24343. while (this._treeSubsetDiv.hasChildNodes()) {
  24344. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  24345. }
  24346. // Add meshes
  24347. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  24348. sortedArray.sort(function (a, b) {
  24349. if (a.name === b.name) {
  24350. return 0;
  24351. }
  24352. return (a.name > b.name) ? 1 : -1;
  24353. });
  24354. for (var index = 0; index < sortedArray.length; index++) {
  24355. var mesh = sortedArray[index];
  24356. if (!mesh.isEnabled()) {
  24357. continue;
  24358. }
  24359. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  24360. m.isVisible = element.checked;
  24361. }, mesh);
  24362. }
  24363. };
  24364. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  24365. this._drawingContext.beginPath();
  24366. this._drawingContext.moveTo(zero.x, zero.y);
  24367. this._drawingContext.lineTo(unit.x, unit.y);
  24368. this._drawingContext.strokeStyle = color;
  24369. this._drawingContext.lineWidth = 4;
  24370. this._drawingContext.stroke();
  24371. this._drawingContext.font = "normal 14px Segoe UI";
  24372. this._drawingContext.fillStyle = color;
  24373. this._drawingContext.fillText(label, unitText.x, unitText.y);
  24374. };
  24375. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  24376. var position = mesh.getBoundingInfo().boundingSphere.center;
  24377. var worldMatrix = mesh.getWorldMatrix();
  24378. 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());
  24379. var unit = (unprojectedVector.subtract(position)).length();
  24380. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  24381. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  24382. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  24383. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  24384. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  24385. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  24386. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  24387. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  24388. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  24389. };
  24390. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  24391. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  24392. this._drawingContext.font = "normal 12px Segoe UI";
  24393. var textMetrics = this._drawingContext.measureText(text);
  24394. var centerX = projectedPosition.x - textMetrics.width / 2;
  24395. var centerY = projectedPosition.y;
  24396. if (this._isClickInsideRect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  24397. onClick();
  24398. }
  24399. this._drawingContext.beginPath();
  24400. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  24401. this._drawingContext.fillStyle = getFillStyle();
  24402. this._drawingContext.globalAlpha = 0.5;
  24403. this._drawingContext.fill();
  24404. this._drawingContext.globalAlpha = 1.0;
  24405. this._drawingContext.strokeStyle = '#FFFFFF';
  24406. this._drawingContext.lineWidth = 1;
  24407. this._drawingContext.stroke();
  24408. this._drawingContext.fillStyle = "#FFFFFF";
  24409. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  24410. this._drawingContext.beginPath();
  24411. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  24412. this._drawingContext.fill();
  24413. }
  24414. };
  24415. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  24416. if (!this._clickPosition) {
  24417. return false;
  24418. }
  24419. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  24420. return false;
  24421. }
  24422. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  24423. return false;
  24424. }
  24425. return true;
  24426. };
  24427. DebugLayer.prototype.isVisible = function () {
  24428. return this._enabled;
  24429. };
  24430. DebugLayer.prototype.hide = function () {
  24431. if (!this._enabled) {
  24432. return;
  24433. }
  24434. this._enabled = false;
  24435. var engine = this._scene.getEngine();
  24436. this._scene.unregisterAfterRender(this._syncData);
  24437. document.body.removeChild(this._globalDiv);
  24438. window.removeEventListener("resize", this._syncPositions);
  24439. this._scene.forceShowBoundingBoxes = false;
  24440. this._scene.forceWireframe = false;
  24441. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  24442. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  24443. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  24444. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  24445. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  24446. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  24447. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  24448. this._scene.shadowsEnabled = true;
  24449. this._scene.particlesEnabled = true;
  24450. this._scene.postProcessesEnabled = true;
  24451. this._scene.collisionsEnabled = true;
  24452. this._scene.lightsEnabled = true;
  24453. this._scene.texturesEnabled = true;
  24454. this._scene.lensFlaresEnabled = true;
  24455. this._scene.proceduralTexturesEnabled = true;
  24456. this._scene.renderTargetsEnabled = true;
  24457. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  24458. };
  24459. DebugLayer.prototype.show = function (showUI) {
  24460. if (typeof showUI === "undefined") { showUI = true; }
  24461. if (this._enabled) {
  24462. return;
  24463. }
  24464. this._enabled = true;
  24465. this._showUI = showUI;
  24466. var engine = this._scene.getEngine();
  24467. this._globalDiv = document.createElement("div");
  24468. document.body.appendChild(this._globalDiv);
  24469. this._generateDOMelements();
  24470. window.addEventListener("resize", this._syncPositions);
  24471. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  24472. this._syncPositions();
  24473. this._scene.registerAfterRender(this._syncData);
  24474. };
  24475. DebugLayer.prototype._clearLabels = function () {
  24476. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  24477. for (var index = 0; index < this._scene.meshes.length; index++) {
  24478. var mesh = this._scene.meshes[index];
  24479. mesh.renderOverlay = false;
  24480. }
  24481. };
  24482. DebugLayer.prototype._generateheader = function (root, text) {
  24483. var header = document.createElement("div");
  24484. header.innerHTML = text + "&nbsp;";
  24485. header.style.textAlign = "right";
  24486. header.style.width = "100%";
  24487. header.style.color = "white";
  24488. header.style.backgroundColor = "Black";
  24489. header.style.padding = "5px 5px 4px 0px";
  24490. header.style.marginLeft = "-5px";
  24491. header.style.fontWeight = "bold";
  24492. root.appendChild(header);
  24493. };
  24494. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  24495. var label = document.createElement("label");
  24496. label.innerHTML = title;
  24497. label.style.color = color;
  24498. root.appendChild(label);
  24499. root.appendChild(document.createElement("br"));
  24500. };
  24501. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  24502. if (typeof tag === "undefined") { tag = null; }
  24503. var label = document.createElement("label");
  24504. var boundingBoxesCheckbox = document.createElement("input");
  24505. boundingBoxesCheckbox.type = "checkbox";
  24506. boundingBoxesCheckbox.checked = initialState;
  24507. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  24508. task(evt.target, tag);
  24509. });
  24510. label.appendChild(boundingBoxesCheckbox);
  24511. var container = document.createElement("span");
  24512. var leftPart = document.createElement("span");
  24513. var rightPart = document.createElement("span");
  24514. rightPart.style.cssFloat = "right";
  24515. leftPart.innerHTML = leftTitle;
  24516. rightPart.innerHTML = rightTitle;
  24517. rightPart.style.fontSize = "12px";
  24518. rightPart.style.maxWidth = "200px";
  24519. container.appendChild(leftPart);
  24520. container.appendChild(rightPart);
  24521. label.appendChild(container);
  24522. root.appendChild(label);
  24523. root.appendChild(document.createElement("br"));
  24524. };
  24525. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  24526. if (typeof tag === "undefined") { tag = null; }
  24527. var label = document.createElement("label");
  24528. var boundingBoxesCheckbox = document.createElement("input");
  24529. boundingBoxesCheckbox.type = "checkbox";
  24530. boundingBoxesCheckbox.checked = initialState;
  24531. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  24532. task(evt.target, tag);
  24533. });
  24534. label.appendChild(boundingBoxesCheckbox);
  24535. label.appendChild(document.createTextNode(title));
  24536. root.appendChild(label);
  24537. root.appendChild(document.createElement("br"));
  24538. };
  24539. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  24540. if (typeof tag === "undefined") { tag = null; }
  24541. var label = document.createElement("label");
  24542. var boundingBoxesRadio = document.createElement("input");
  24543. boundingBoxesRadio.type = "radio";
  24544. boundingBoxesRadio.name = name;
  24545. boundingBoxesRadio.checked = initialState;
  24546. boundingBoxesRadio.addEventListener("change", function (evt) {
  24547. task(evt.target, tag);
  24548. });
  24549. label.appendChild(boundingBoxesRadio);
  24550. label.appendChild(document.createTextNode(title));
  24551. root.appendChild(label);
  24552. root.appendChild(document.createElement("br"));
  24553. };
  24554. DebugLayer.prototype._generateDOMelements = function () {
  24555. var _this = this;
  24556. this._globalDiv.id = "DebugLayer";
  24557. this._globalDiv.style.position = "absolute";
  24558. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  24559. this._globalDiv.style.fontSize = "14px";
  24560. this._globalDiv.style.color = "white";
  24561. // Drawing canvas
  24562. this._drawingCanvas = document.createElement("canvas");
  24563. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  24564. this._drawingCanvas.style.position = "absolute";
  24565. this._drawingCanvas.style.pointerEvents = "none";
  24566. this._drawingContext = this._drawingCanvas.getContext("2d");
  24567. this._globalDiv.appendChild(this._drawingCanvas);
  24568. if (this._showUI) {
  24569. var background = "rgba(128, 128, 128, 0.4)";
  24570. var border = "rgb(180, 180, 180) solid 1px";
  24571. // Stats
  24572. this._statsDiv = document.createElement("div");
  24573. this._statsDiv.id = "DebugLayerStats";
  24574. this._statsDiv.style.border = border;
  24575. this._statsDiv.style.position = "absolute";
  24576. this._statsDiv.style.background = background;
  24577. this._statsDiv.style.padding = "0px 0px 0px 5px";
  24578. this._statsDiv.style.pointerEvents = "none";
  24579. this._statsDiv.style.overflowY = "auto";
  24580. this._generateheader(this._statsDiv, "STATISTICS");
  24581. this._statsSubsetDiv = document.createElement("div");
  24582. this._statsSubsetDiv.style.paddingTop = "5px";
  24583. this._statsSubsetDiv.style.paddingBottom = "5px";
  24584. this._statsDiv.appendChild(this._statsSubsetDiv);
  24585. // Tree
  24586. this._treeDiv = document.createElement("div");
  24587. this._treeDiv.id = "DebugLayerTree";
  24588. this._treeDiv.style.border = border;
  24589. this._treeDiv.style.position = "absolute";
  24590. this._treeDiv.style.background = background;
  24591. this._treeDiv.style.padding = "0px 0px 0px 5px";
  24592. this._treeDiv.style.display = "none";
  24593. this._generateheader(this._treeDiv, "MESHES TREE");
  24594. this._treeSubsetDiv = document.createElement("div");
  24595. this._treeSubsetDiv.style.paddingTop = "5px";
  24596. this._treeSubsetDiv.style.paddingRight = "5px";
  24597. this._treeSubsetDiv.style.overflowY = "auto";
  24598. this._treeSubsetDiv.style.maxHeight = "300px";
  24599. this._treeDiv.appendChild(this._treeSubsetDiv);
  24600. this._needToRefreshMeshesTree = true;
  24601. // Logs
  24602. this._logDiv = document.createElement("div");
  24603. this._logDiv.style.border = border;
  24604. this._logDiv.id = "DebugLayerLogs";
  24605. this._logDiv.style.position = "absolute";
  24606. this._logDiv.style.background = background;
  24607. this._logDiv.style.padding = "0px 0px 0px 5px";
  24608. this._logDiv.style.display = "none";
  24609. this._generateheader(this._logDiv, "LOGS");
  24610. this._logSubsetDiv = document.createElement("div");
  24611. this._logSubsetDiv.style.height = "127px";
  24612. this._logSubsetDiv.style.paddingTop = "5px";
  24613. this._logSubsetDiv.style.overflowY = "auto";
  24614. this._logSubsetDiv.style.fontSize = "12px";
  24615. this._logSubsetDiv.style.fontFamily = "consolas";
  24616. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  24617. this._logDiv.appendChild(this._logSubsetDiv);
  24618. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  24619. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  24620. };
  24621. // Options
  24622. this._optionsDiv = document.createElement("div");
  24623. this._optionsDiv.id = "DebugLayerOptions";
  24624. this._optionsDiv.style.border = border;
  24625. this._optionsDiv.style.position = "absolute";
  24626. this._optionsDiv.style.background = background;
  24627. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  24628. this._optionsDiv.style.overflowY = "auto";
  24629. this._generateheader(this._optionsDiv, "OPTIONS");
  24630. this._optionsSubsetDiv = document.createElement("div");
  24631. this._optionsSubsetDiv.style.paddingTop = "5px";
  24632. this._optionsSubsetDiv.style.paddingBottom = "5px";
  24633. this._optionsSubsetDiv.style.overflowY = "auto";
  24634. this._optionsSubsetDiv.style.maxHeight = "200px";
  24635. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  24636. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  24637. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) {
  24638. _this._displayStatistics = element.checked;
  24639. });
  24640. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) {
  24641. _this._displayLogs = element.checked;
  24642. });
  24643. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  24644. _this._displayTree = element.checked;
  24645. _this._needToRefreshMeshesTree = true;
  24646. });
  24647. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) {
  24648. _this._scene.forceShowBoundingBoxes = element.checked;
  24649. });
  24650. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  24651. _this._labelsEnabled = element.checked;
  24652. if (!_this._labelsEnabled) {
  24653. _this._clearLabels();
  24654. }
  24655. });
  24656. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  24657. if (element.checked) {
  24658. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  24659. } else {
  24660. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  24661. }
  24662. });
  24663. ;
  24664. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  24665. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  24666. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  24667. if (element.checked) {
  24668. _this._scene.forceWireframe = false;
  24669. _this._scene.forcePointsCloud = false;
  24670. }
  24671. });
  24672. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  24673. if (element.checked) {
  24674. _this._scene.forceWireframe = true;
  24675. _this._scene.forcePointsCloud = false;
  24676. }
  24677. });
  24678. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  24679. if (element.checked) {
  24680. _this._scene.forceWireframe = false;
  24681. _this._scene.forcePointsCloud = true;
  24682. }
  24683. });
  24684. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  24685. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  24686. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) {
  24687. BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked;
  24688. });
  24689. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) {
  24690. BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked;
  24691. });
  24692. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) {
  24693. BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked;
  24694. });
  24695. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) {
  24696. BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked;
  24697. });
  24698. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) {
  24699. BABYLON.StandardMaterial.BumpTextureEnabled = element.checked;
  24700. });
  24701. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) {
  24702. BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked;
  24703. });
  24704. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) {
  24705. BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked;
  24706. });
  24707. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) {
  24708. BABYLON.StandardMaterial.FresnelEnabled = element.checked;
  24709. });
  24710. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  24711. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  24712. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) {
  24713. _this._scene.animationsEnabled = element.checked;
  24714. });
  24715. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) {
  24716. _this._scene.collisionsEnabled = element.checked;
  24717. });
  24718. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) {
  24719. _this._scene.fogEnabled = element.checked;
  24720. });
  24721. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) {
  24722. _this._scene.lensFlaresEnabled = element.checked;
  24723. });
  24724. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) {
  24725. _this._scene.lightsEnabled = element.checked;
  24726. });
  24727. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) {
  24728. _this._scene.particlesEnabled = element.checked;
  24729. });
  24730. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) {
  24731. _this._scene.postProcessesEnabled = element.checked;
  24732. });
  24733. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) {
  24734. _this._scene.proceduralTexturesEnabled = element.checked;
  24735. });
  24736. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) {
  24737. _this._scene.renderTargetsEnabled = element.checked;
  24738. });
  24739. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) {
  24740. _this._scene.shadowsEnabled = element.checked;
  24741. });
  24742. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) {
  24743. _this._scene.skeletonsEnabled = element.checked;
  24744. });
  24745. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) {
  24746. _this._scene.texturesEnabled = element.checked;
  24747. });
  24748. this._globalDiv.appendChild(this._statsDiv);
  24749. this._globalDiv.appendChild(this._logDiv);
  24750. this._globalDiv.appendChild(this._optionsDiv);
  24751. this._globalDiv.appendChild(this._treeDiv);
  24752. }
  24753. };
  24754. DebugLayer.prototype._displayStats = function () {
  24755. var scene = this._scene;
  24756. var engine = scene.getEngine();
  24757. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>" + "Total meshes: " + scene.meshes.length + "<br>" + "Total vertices: " + scene.getTotalVertices() + "<br>" + "Active meshes: " + scene.getActiveMeshes().length + "<br>" + "Active vertices: " + scene.getActiveVertices() + "<br>" + "Active bones: " + scene.getActiveBones() + "<br>" + "Active particles: " + scene.getActiveParticles() + "<br><br>" + "Frame duration: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>" + "<b>Draw calls: " + engine.drawCalls + "</b><br><br>" + "<i>Evaluate Active Meshes duration:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>" + "<i>Render Targets duration:</i> " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>" + "<i>Particles duration:</i> " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>" + "<i>Sprites duration:</i> " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br>" + "<i>Render duration:</i> <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b>";
  24758. };
  24759. return DebugLayer;
  24760. })();
  24761. BABYLON.DebugLayer = DebugLayer;
  24762. })(BABYLON || (BABYLON = {}));
  24763. //# sourceMappingURL=babylon.debugLayer.js.map
  24764. var BABYLON;
  24765. (function (BABYLON) {
  24766. var RawTexture = (function (_super) {
  24767. __extends(RawTexture, _super);
  24768. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  24769. if (typeof generateMipMaps === "undefined") { generateMipMaps = true; }
  24770. if (typeof invertY === "undefined") { invertY = false; }
  24771. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  24772. _super.call(this, null, scene, !generateMipMaps, invertY);
  24773. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  24774. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  24775. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  24776. }
  24777. // Statics
  24778. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  24779. if (typeof generateMipMaps === "undefined") { generateMipMaps = true; }
  24780. if (typeof invertY === "undefined") { invertY = false; }
  24781. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  24782. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  24783. };
  24784. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  24785. if (typeof generateMipMaps === "undefined") { generateMipMaps = true; }
  24786. if (typeof invertY === "undefined") { invertY = false; }
  24787. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  24788. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  24789. };
  24790. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  24791. if (typeof generateMipMaps === "undefined") { generateMipMaps = true; }
  24792. if (typeof invertY === "undefined") { invertY = false; }
  24793. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  24794. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  24795. };
  24796. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  24797. if (typeof generateMipMaps === "undefined") { generateMipMaps = true; }
  24798. if (typeof invertY === "undefined") { invertY = false; }
  24799. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  24800. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  24801. };
  24802. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  24803. if (typeof generateMipMaps === "undefined") { generateMipMaps = true; }
  24804. if (typeof invertY === "undefined") { invertY = false; }
  24805. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  24806. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  24807. };
  24808. return RawTexture;
  24809. })(BABYLON.Texture);
  24810. BABYLON.RawTexture = RawTexture;
  24811. })(BABYLON || (BABYLON = {}));
  24812. //# sourceMappingURL=babylon.rawTexture.js.map
  24813. var BABYLON;
  24814. (function (BABYLON) {
  24815. var IndexedVector2 = (function (_super) {
  24816. __extends(IndexedVector2, _super);
  24817. function IndexedVector2(original, index) {
  24818. _super.call(this, original.x, original.y);
  24819. this.index = index;
  24820. }
  24821. return IndexedVector2;
  24822. })(BABYLON.Vector2);
  24823. var PolygonPoints = (function () {
  24824. function PolygonPoints() {
  24825. this.elements = new Array();
  24826. }
  24827. PolygonPoints.prototype.add = function (originalPoints) {
  24828. var _this = this;
  24829. var result = new Array();
  24830. originalPoints.forEach(function (point) {
  24831. var newPoint = new IndexedVector2(point, _this.elements.length);
  24832. result.push(newPoint);
  24833. _this.elements.push(newPoint);
  24834. });
  24835. return result;
  24836. };
  24837. PolygonPoints.prototype.computeBounds = function () {
  24838. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  24839. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  24840. this.elements.forEach(function (point) {
  24841. // x
  24842. if (point.x < lmin.x) {
  24843. lmin.x = point.x;
  24844. } else if (point.x > lmax.x) {
  24845. lmax.x = point.x;
  24846. }
  24847. // y
  24848. if (point.y < lmin.y) {
  24849. lmin.y = point.y;
  24850. } else if (point.y > lmax.y) {
  24851. lmax.y = point.y;
  24852. }
  24853. });
  24854. return {
  24855. min: lmin,
  24856. max: lmax,
  24857. width: lmax.x - lmin.x,
  24858. height: lmax.y - lmin.y
  24859. };
  24860. };
  24861. return PolygonPoints;
  24862. })();
  24863. var Polygon = (function () {
  24864. function Polygon() {
  24865. }
  24866. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  24867. return [
  24868. new BABYLON.Vector2(xmin, ymin),
  24869. new BABYLON.Vector2(xmax, ymin),
  24870. new BABYLON.Vector2(xmax, ymax),
  24871. new BABYLON.Vector2(xmin, ymax)
  24872. ];
  24873. };
  24874. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  24875. if (typeof cx === "undefined") { cx = 0; }
  24876. if (typeof cy === "undefined") { cy = 0; }
  24877. if (typeof numberOfSides === "undefined") { numberOfSides = 32; }
  24878. var result = new Array();
  24879. var angle = 0;
  24880. var increment = (Math.PI * 2) / numberOfSides;
  24881. for (var i = 0; i < numberOfSides; i++) {
  24882. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  24883. angle -= increment;
  24884. }
  24885. return result;
  24886. };
  24887. Polygon.Parse = function (input) {
  24888. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) {
  24889. return (!isNaN(val));
  24890. });
  24891. var i, result = [];
  24892. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  24893. result.push(new poly2tri.Point(floats[i], floats[i + 1]));
  24894. }
  24895. return result;
  24896. };
  24897. return Polygon;
  24898. })();
  24899. BABYLON.Polygon = Polygon;
  24900. var PolygonMeshBuilder = (function () {
  24901. function PolygonMeshBuilder(name, contours, scene) {
  24902. this.name = name;
  24903. this.scene = scene;
  24904. this._points = new PolygonPoints();
  24905. if (!("poly2tri" in window)) {
  24906. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  24907. }
  24908. this._swctx = new poly2tri.SweepContext(this._points.add(contours));
  24909. }
  24910. PolygonMeshBuilder.prototype.addHole = function (hole) {
  24911. this._swctx.addHole(this._points.add(hole));
  24912. return this;
  24913. };
  24914. PolygonMeshBuilder.prototype.build = function (updatable) {
  24915. if (typeof updatable === "undefined") { updatable = false; }
  24916. var result = new BABYLON.Mesh(this.name, this.scene);
  24917. var normals = [];
  24918. var positions = [];
  24919. var uvs = [];
  24920. var bounds = this._points.computeBounds();
  24921. this._points.elements.forEach(function (p) {
  24922. normals.push(0, 1.0, 0);
  24923. positions.push(p.x, 0, p.y);
  24924. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  24925. });
  24926. var indices = [];
  24927. this._swctx.triangulate();
  24928. this._swctx.getTriangles().forEach(function (triangle) {
  24929. triangle.getPoints().forEach(function (point) {
  24930. indices.push(point.index);
  24931. });
  24932. });
  24933. result.setVerticesData(positions, BABYLON.VertexBuffer.PositionKind, updatable);
  24934. result.setVerticesData(normals, BABYLON.VertexBuffer.NormalKind, updatable);
  24935. result.setVerticesData(uvs, BABYLON.VertexBuffer.UVKind, updatable);
  24936. result.setIndices(indices);
  24937. return result;
  24938. };
  24939. return PolygonMeshBuilder;
  24940. })();
  24941. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  24942. })(BABYLON || (BABYLON = {}));
  24943. //# sourceMappingURL=babylon.polygonmesh.js.map