babylon.2.0-alpha.debug.js 1.2 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473
  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. 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 = 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 = 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 = 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.0) {
  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 Plane(array[0], array[1], array[2], array[3]);
  1773. };
  1774. Plane.FromPoints = function (point1, point2, point3) {
  1775. var result = new 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 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 = Vector3.Zero();
  1961. this._edge2 = Vector3.Zero();
  1962. this._pvec = Vector3.Zero();
  1963. this._tvec = Vector3.Zero();
  1964. this._qvec = Vector3.Zero();
  1965. }
  1966. vertex1.subtractToRef(vertex0, this._edge1);
  1967. vertex2.subtractToRef(vertex0, this._edge2);
  1968. 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 = Vector3.Unproject(new Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  1994. var end = Vector3.Unproject(new 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 = 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 = Vector3.TransformCoordinates(ray.origin, matrix);
  2015. var newDirection = 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 Vector3(1, 0, 0);
  2030. Axis.Y = new Vector3(0, 1, 0);
  2031. Axis.Z = new 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. (function (Orientation) {
  2060. Orientation[Orientation["CW"] = 0] = "CW";
  2061. Orientation[Orientation["CCW"] = 1] = "CCW";
  2062. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2063. var Orientation = BABYLON.Orientation;
  2064. var Angle = (function () {
  2065. function Angle(radians) {
  2066. var _this = this;
  2067. this.degrees = function () {
  2068. return _this._radians * 180 / Math.PI;
  2069. };
  2070. this.radians = function () {
  2071. return _this._radians;
  2072. };
  2073. this._radians = radians;
  2074. if (this._radians < 0)
  2075. this._radians += (2 * Math.PI);
  2076. }
  2077. Angle.BetweenTwoPoints = function (a, b) {
  2078. var delta = b.subtract(a);
  2079. var theta = Math.atan2(delta.y, delta.x);
  2080. return new Angle(theta);
  2081. };
  2082. Angle.FromRadians = function (radians) {
  2083. return new Angle(radians);
  2084. };
  2085. Angle.FromDegrees = function (degrees) {
  2086. return new Angle(degrees * Math.PI / 180);
  2087. };
  2088. return Angle;
  2089. })();
  2090. BABYLON.Angle = Angle;
  2091. var Arc2 = (function () {
  2092. function Arc2(startPoint, midPoint, endPoint) {
  2093. this.startPoint = startPoint;
  2094. this.midPoint = midPoint;
  2095. this.endPoint = endPoint;
  2096. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2097. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2098. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2099. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2100. this.centerPoint = new Vector2((startToMid * (midPoint.y - endPoint.y) - midToEnd * (startPoint.y - midPoint.y)) / det, ((startPoint.x - midPoint.x) * midToEnd - (midPoint.x - endPoint.x) * startToMid) / det);
  2101. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2102. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2103. var a1 = this.startAngle.degrees();
  2104. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2105. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2106. // angles correction
  2107. if (a2 - a1 > +180.0)
  2108. a2 -= 360.0;
  2109. if (a2 - a1 < -180.0)
  2110. a2 += 360.0;
  2111. if (a3 - a2 > +180.0)
  2112. a3 -= 360.0;
  2113. if (a3 - a2 < -180.0)
  2114. a3 += 360.0;
  2115. this.orientation = (a2 - a1) < 0 ? 0 /* CW */ : 1 /* CCW */;
  2116. this.angle = Angle.FromDegrees(this.orientation === 0 /* CW */ ? a1 - a3 : a3 - a1);
  2117. }
  2118. return Arc2;
  2119. })();
  2120. BABYLON.Arc2 = Arc2;
  2121. var Path2 = (function () {
  2122. function Path2(x, y) {
  2123. this._points = [];
  2124. this._points.push(new Vector2(x, y));
  2125. }
  2126. Path2.prototype.addLineTo = function (x, y) {
  2127. this._points.push(new Vector2(x, y));
  2128. return this;
  2129. };
  2130. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2131. if (typeof numberOfSegments === "undefined") { numberOfSegments = 36; }
  2132. var startPoint = this._points[this._points.length - 1];
  2133. var midPoint = new Vector2(midX, midY);
  2134. var endPoint = new Vector2(endX, endY);
  2135. var arc = new Arc2(startPoint, midPoint, endPoint);
  2136. var increment = arc.angle.radians() / numberOfSegments;
  2137. if (arc.orientation === 0 /* CW */)
  2138. increment *= -1;
  2139. var currentAngle = arc.startAngle.radians() + increment;
  2140. for (var i = 0; i < numberOfSegments; i++) {
  2141. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2142. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2143. this.addLineTo(x, y);
  2144. currentAngle += increment;
  2145. }
  2146. return this;
  2147. };
  2148. Path2.prototype.close = function () {
  2149. return this._points;
  2150. };
  2151. Path2.StartingAt = function (x, y) {
  2152. return new Path2(x, y);
  2153. };
  2154. return Path2;
  2155. })();
  2156. BABYLON.Path2 = Path2;
  2157. })(BABYLON || (BABYLON = {}));
  2158. //# sourceMappingURL=babylon.math.js.map
  2159. var BABYLON;
  2160. (function (BABYLON) {
  2161. // Screenshots
  2162. var screenshotCanvas;
  2163. var cloneValue = function (source, destinationObject) {
  2164. if (!source)
  2165. return null;
  2166. if (source instanceof BABYLON.Mesh) {
  2167. return null;
  2168. }
  2169. if (source instanceof BABYLON.SubMesh) {
  2170. return source.clone(destinationObject);
  2171. } else if (source.clone) {
  2172. return source.clone();
  2173. }
  2174. return null;
  2175. };
  2176. var Tools = (function () {
  2177. function Tools() {
  2178. }
  2179. Tools.GetFilename = function (path) {
  2180. var index = path.lastIndexOf("/");
  2181. if (index < 0)
  2182. return path;
  2183. return path.substring(index + 1);
  2184. };
  2185. Tools.GetDOMTextContent = function (element) {
  2186. var result = "";
  2187. var child = element.firstChild;
  2188. while (child) {
  2189. if (child.nodeType == 3) {
  2190. result += child.textContent;
  2191. }
  2192. child = child.nextSibling;
  2193. }
  2194. return result;
  2195. };
  2196. Tools.ToDegrees = function (angle) {
  2197. return angle * 180 / Math.PI;
  2198. };
  2199. Tools.ToRadians = function (angle) {
  2200. return angle * Math.PI / 180;
  2201. };
  2202. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  2203. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  2204. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  2205. for (var index = indexStart; index < indexStart + indexCount; index++) {
  2206. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  2207. minimum = BABYLON.Vector3.Minimize(current, minimum);
  2208. maximum = BABYLON.Vector3.Maximize(current, maximum);
  2209. }
  2210. return {
  2211. minimum: minimum,
  2212. maximum: maximum
  2213. };
  2214. };
  2215. Tools.ExtractMinAndMax = function (positions, start, count) {
  2216. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  2217. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  2218. for (var index = start; index < start + count; index++) {
  2219. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  2220. minimum = BABYLON.Vector3.Minimize(current, minimum);
  2221. maximum = BABYLON.Vector3.Maximize(current, maximum);
  2222. }
  2223. return {
  2224. minimum: minimum,
  2225. maximum: maximum
  2226. };
  2227. };
  2228. Tools.MakeArray = function (obj, allowsNullUndefined) {
  2229. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  2230. return undefined;
  2231. return Array.isArray(obj) ? obj : [obj];
  2232. };
  2233. // Misc.
  2234. Tools.GetPointerPrefix = function () {
  2235. var eventPrefix = "pointer";
  2236. // Check if hand.js is referenced or if the browser natively supports pointer events
  2237. if (!navigator.pointerEnabled) {
  2238. eventPrefix = "mouse";
  2239. }
  2240. return eventPrefix;
  2241. };
  2242. Tools.QueueNewFrame = function (func) {
  2243. if (window.requestAnimationFrame)
  2244. window.requestAnimationFrame(func);
  2245. else if (window.msRequestAnimationFrame)
  2246. window.msRequestAnimationFrame(func);
  2247. else if (window.webkitRequestAnimationFrame)
  2248. window.webkitRequestAnimationFrame(func);
  2249. else if (window.mozRequestAnimationFrame)
  2250. window.mozRequestAnimationFrame(func);
  2251. else if (window.oRequestAnimationFrame)
  2252. window.oRequestAnimationFrame(func);
  2253. else {
  2254. window.setTimeout(func, 16);
  2255. }
  2256. };
  2257. Tools.RequestFullscreen = function (element) {
  2258. if (element.requestFullscreen)
  2259. element.requestFullscreen();
  2260. else if (element.msRequestFullscreen)
  2261. element.msRequestFullscreen();
  2262. else if (element.webkitRequestFullscreen)
  2263. element.webkitRequestFullscreen();
  2264. else if (element.mozRequestFullScreen)
  2265. element.mozRequestFullScreen();
  2266. };
  2267. Tools.ExitFullscreen = function () {
  2268. if (document.exitFullscreen) {
  2269. document.exitFullscreen();
  2270. } else if (document.mozCancelFullScreen) {
  2271. document.mozCancelFullScreen();
  2272. } else if (document.webkitCancelFullScreen) {
  2273. document.webkitCancelFullScreen();
  2274. } else if (document.msCancelFullScreen) {
  2275. document.msCancelFullScreen();
  2276. }
  2277. };
  2278. // External files
  2279. Tools.CleanUrl = function (url) {
  2280. url = url.replace(/#/mg, "%23");
  2281. return url;
  2282. };
  2283. Tools.LoadImage = function (url, onload, onerror, database) {
  2284. url = Tools.CleanUrl(url);
  2285. var img = new Image();
  2286. if (url.substr(0, 5) != "data:")
  2287. img.crossOrigin = 'anonymous';
  2288. img.onload = function () {
  2289. onload(img);
  2290. };
  2291. img.onerror = function (err) {
  2292. onerror(img, err);
  2293. };
  2294. var noIndexedDB = function () {
  2295. img.src = url;
  2296. };
  2297. var loadFromIndexedDB = function () {
  2298. database.loadImageFromDB(url, img);
  2299. };
  2300. //ANY database to do!
  2301. if (database && database.enableTexturesOffline && BABYLON.Database.isUASupportingBlobStorage) {
  2302. database.openAsync(loadFromIndexedDB, noIndexedDB);
  2303. } else {
  2304. if (url.indexOf("file:") === -1) {
  2305. noIndexedDB();
  2306. } else {
  2307. try {
  2308. var textureName = url.substring(5);
  2309. var blobURL;
  2310. try {
  2311. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  2312. } catch (ex) {
  2313. // Chrome doesn't support oneTimeOnly parameter
  2314. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  2315. }
  2316. img.src = blobURL;
  2317. } catch (e) {
  2318. Tools.Log("Error while trying to load texture: " + textureName);
  2319. img.src = null;
  2320. }
  2321. }
  2322. }
  2323. return img;
  2324. };
  2325. //ANY
  2326. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  2327. url = Tools.CleanUrl(url);
  2328. var noIndexedDB = function () {
  2329. var request = new XMLHttpRequest();
  2330. var loadUrl = Tools.BaseUrl + url;
  2331. request.open('GET', loadUrl, true);
  2332. if (useArrayBuffer) {
  2333. request.responseType = "arraybuffer";
  2334. }
  2335. request.onprogress = progressCallBack;
  2336. request.onreadystatechange = function () {
  2337. if (request.readyState == 4) {
  2338. if (request.status == 200 || BABYLON.Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  2339. callback(!useArrayBuffer ? request.responseText : request.response);
  2340. } else {
  2341. if (onError) {
  2342. onError();
  2343. } else {
  2344. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  2345. }
  2346. }
  2347. }
  2348. };
  2349. request.send(null);
  2350. };
  2351. var loadFromIndexedDB = function () {
  2352. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  2353. };
  2354. if (url.indexOf("file:") !== -1) {
  2355. var fileName = url.substring(5);
  2356. BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  2357. } else {
  2358. // Caching all files
  2359. if (database && database.enableSceneOffline) {
  2360. database.openAsync(loadFromIndexedDB, noIndexedDB);
  2361. } else {
  2362. noIndexedDB();
  2363. }
  2364. }
  2365. };
  2366. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  2367. var reader = new FileReader();
  2368. reader.onload = function (e) {
  2369. callback(e.target.result);
  2370. };
  2371. reader.onprogress = progressCallback;
  2372. reader.readAsDataURL(fileToLoad);
  2373. };
  2374. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  2375. var reader = new FileReader();
  2376. reader.onload = function (e) {
  2377. callback(e.target.result);
  2378. };
  2379. reader.onprogress = progressCallBack;
  2380. if (!useArrayBuffer) {
  2381. // Asynchronous read
  2382. reader.readAsText(fileToLoad);
  2383. } else {
  2384. reader.readAsArrayBuffer(fileToLoad);
  2385. }
  2386. };
  2387. // Misc.
  2388. Tools.Clamp = function (value, min, max) {
  2389. if (typeof min === "undefined") { min = 0; }
  2390. if (typeof max === "undefined") { max = 1; }
  2391. return Math.min(max, Math.max(min, value));
  2392. };
  2393. Tools.Format = function (value, decimals) {
  2394. if (typeof decimals === "undefined") { decimals = 2; }
  2395. return value.toFixed(decimals);
  2396. };
  2397. Tools.CheckExtends = function (v, min, max) {
  2398. if (v.x < min.x)
  2399. min.x = v.x;
  2400. if (v.y < min.y)
  2401. min.y = v.y;
  2402. if (v.z < min.z)
  2403. min.z = v.z;
  2404. if (v.x > max.x)
  2405. max.x = v.x;
  2406. if (v.y > max.y)
  2407. max.y = v.y;
  2408. if (v.z > max.z)
  2409. max.z = v.z;
  2410. };
  2411. Tools.WithinEpsilon = function (a, b) {
  2412. var num = a - b;
  2413. return -1.401298E-45 <= num && num <= 1.401298E-45;
  2414. };
  2415. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  2416. for (var prop in source) {
  2417. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  2418. continue;
  2419. }
  2420. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  2421. continue;
  2422. }
  2423. var sourceValue = source[prop];
  2424. var typeOfSourceValue = typeof sourceValue;
  2425. if (typeOfSourceValue == "function") {
  2426. continue;
  2427. }
  2428. if (typeOfSourceValue == "object") {
  2429. if (sourceValue instanceof Array) {
  2430. destination[prop] = [];
  2431. if (sourceValue.length > 0) {
  2432. if (typeof sourceValue[0] == "object") {
  2433. for (var index = 0; index < sourceValue.length; index++) {
  2434. var clonedValue = cloneValue(sourceValue[index], destination);
  2435. if (destination[prop].indexOf(clonedValue) === -1) {
  2436. destination[prop].push(clonedValue);
  2437. }
  2438. }
  2439. } else {
  2440. destination[prop] = sourceValue.slice(0);
  2441. }
  2442. }
  2443. } else {
  2444. destination[prop] = cloneValue(sourceValue, destination);
  2445. }
  2446. } else {
  2447. destination[prop] = sourceValue;
  2448. }
  2449. }
  2450. };
  2451. Tools.IsEmpty = function (obj) {
  2452. for (var i in obj) {
  2453. return false;
  2454. }
  2455. return true;
  2456. };
  2457. Tools.RegisterTopRootEvents = function (events) {
  2458. for (var index = 0; index < events.length; index++) {
  2459. var event = events[index];
  2460. window.addEventListener(event.name, event.handler, false);
  2461. try {
  2462. if (window.parent) {
  2463. window.parent.addEventListener(event.name, event.handler, false);
  2464. }
  2465. } catch (e) {
  2466. // Silently fails...
  2467. }
  2468. }
  2469. };
  2470. Tools.UnregisterTopRootEvents = function (events) {
  2471. for (var index = 0; index < events.length; index++) {
  2472. var event = events[index];
  2473. window.removeEventListener(event.name, event.handler);
  2474. try {
  2475. if (window.parent) {
  2476. window.parent.removeEventListener(event.name, event.handler);
  2477. }
  2478. } catch (e) {
  2479. // Silently fails...
  2480. }
  2481. }
  2482. };
  2483. Tools.CreateScreenshot = function (engine, camera, size) {
  2484. var width;
  2485. var height;
  2486. var scene = camera.getScene();
  2487. var previousCamera = null;
  2488. if (scene.activeCamera !== camera) {
  2489. previousCamera = scene.activeCamera;
  2490. scene.activeCamera = camera;
  2491. }
  2492. //If a precision value is specified
  2493. if (size.precision) {
  2494. width = Math.round(engine.getRenderWidth() * size.precision);
  2495. height = Math.round(width / engine.getAspectRatio(camera));
  2496. size = { width: width, height: height };
  2497. } else if (size.width && size.height) {
  2498. width = size.width;
  2499. height = size.height;
  2500. } else if (size.width && !size.height) {
  2501. width = size.width;
  2502. height = Math.round(width / engine.getAspectRatio(camera));
  2503. size = { width: width, height: height };
  2504. } else if (size.height && !size.width) {
  2505. height = size.height;
  2506. width = Math.round(height * engine.getAspectRatio(camera));
  2507. size = { width: width, height: height };
  2508. } else if (!isNaN(size)) {
  2509. height = size;
  2510. width = size;
  2511. } else {
  2512. Tools.Error("Invalid 'size' parameter !");
  2513. return;
  2514. }
  2515. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  2516. var texture = new BABYLON.RenderTargetTexture("screenShot", size, engine.scenes[0], false, false);
  2517. texture.renderList = engine.scenes[0].meshes;
  2518. texture.onAfterRender = function () {
  2519. // Read the contents of the framebuffer
  2520. var numberOfChannelsByLine = width * 4;
  2521. var halfHeight = height / 2;
  2522. //Reading datas from WebGL
  2523. var data = engine.readPixels(0, 0, width, height);
  2524. for (var i = 0; i < halfHeight; i++) {
  2525. for (var j = 0; j < numberOfChannelsByLine; j++) {
  2526. var currentCell = j + i * numberOfChannelsByLine;
  2527. var targetLine = height - i - 1;
  2528. var targetCell = j + targetLine * numberOfChannelsByLine;
  2529. var temp = data[currentCell];
  2530. data[currentCell] = data[targetCell];
  2531. data[targetCell] = temp;
  2532. }
  2533. }
  2534. // Create a 2D canvas to store the result
  2535. if (!screenshotCanvas) {
  2536. screenshotCanvas = document.createElement('canvas');
  2537. }
  2538. screenshotCanvas.width = width;
  2539. screenshotCanvas.height = height;
  2540. var context = screenshotCanvas.getContext('2d');
  2541. // Copy the pixels to a 2D canvas
  2542. var imageData = context.createImageData(width, height);
  2543. imageData.data.set(data);
  2544. context.putImageData(imageData, 0, 0);
  2545. var base64Image = screenshotCanvas.toDataURL();
  2546. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  2547. if (("download" in document.createElement("a"))) {
  2548. var a = window.document.createElement("a");
  2549. a.href = base64Image;
  2550. var date = new Date();
  2551. var stringDate = date.getFullYear() + "/" + date.getMonth() + "/" + date.getDate() + "-" + date.getHours() + ":" + date.getMinutes();
  2552. a.setAttribute("download", "screenshot-" + stringDate + ".png");
  2553. window.document.body.appendChild(a);
  2554. a.addEventListener("click", function () {
  2555. a.parentElement.removeChild(a);
  2556. });
  2557. a.click();
  2558. //Or opening a new tab with the image if it is not possible to automatically start download.
  2559. } else {
  2560. var newWindow = window.open("");
  2561. var img = newWindow.document.createElement("img");
  2562. img.src = base64Image;
  2563. newWindow.document.body.appendChild(img);
  2564. }
  2565. };
  2566. texture.render(true);
  2567. texture.dispose();
  2568. if (previousCamera) {
  2569. scene.activeCamera = previousCamera;
  2570. }
  2571. };
  2572. // XHR response validator for local file scenario
  2573. Tools.ValidateXHRData = function (xhr, dataType) {
  2574. if (typeof dataType === "undefined") { dataType = 7; }
  2575. try {
  2576. if (dataType & 1) {
  2577. if (xhr.responseText && xhr.responseText.length > 0) {
  2578. return true;
  2579. } else if (dataType === 1) {
  2580. return false;
  2581. }
  2582. }
  2583. if (dataType & 2) {
  2584. // Check header width and height since there is no "TGA" magic number
  2585. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  2586. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  2587. return true;
  2588. } else if (dataType === 2) {
  2589. return false;
  2590. }
  2591. }
  2592. if (dataType & 4) {
  2593. // Check for the "DDS" magic number
  2594. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  2595. if (ddsHeader[0] == 68 && ddsHeader[1] == 68 && ddsHeader[2] == 83) {
  2596. return true;
  2597. } else {
  2598. return false;
  2599. }
  2600. }
  2601. } catch (e) {
  2602. // Global protection
  2603. }
  2604. return false;
  2605. };
  2606. Object.defineProperty(Tools, "NoneLogLevel", {
  2607. get: function () {
  2608. return Tools._NoneLogLevel;
  2609. },
  2610. enumerable: true,
  2611. configurable: true
  2612. });
  2613. Object.defineProperty(Tools, "MessageLogLevel", {
  2614. get: function () {
  2615. return Tools._MessageLogLevel;
  2616. },
  2617. enumerable: true,
  2618. configurable: true
  2619. });
  2620. Object.defineProperty(Tools, "WarningLogLevel", {
  2621. get: function () {
  2622. return Tools._WarningLogLevel;
  2623. },
  2624. enumerable: true,
  2625. configurable: true
  2626. });
  2627. Object.defineProperty(Tools, "ErrorLogLevel", {
  2628. get: function () {
  2629. return Tools._ErrorLogLevel;
  2630. },
  2631. enumerable: true,
  2632. configurable: true
  2633. });
  2634. Object.defineProperty(Tools, "AllLogLevel", {
  2635. get: function () {
  2636. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  2637. },
  2638. enumerable: true,
  2639. configurable: true
  2640. });
  2641. Tools._AddLogEntry = function (entry) {
  2642. Tools._LogCache = entry + Tools._LogCache;
  2643. if (Tools.OnNewCacheEntry) {
  2644. Tools.OnNewCacheEntry(entry);
  2645. }
  2646. };
  2647. Tools._FormatMessage = function (message) {
  2648. var padStr = function (i) {
  2649. return (i < 10) ? "0" + i : "" + i;
  2650. };
  2651. var date = new Date();
  2652. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  2653. };
  2654. Tools._LogDisabled = function (message) {
  2655. // nothing to do
  2656. };
  2657. Tools._LogEnabled = function (message) {
  2658. var formattedMessage = Tools._FormatMessage(message);
  2659. console.log("BJS - " + formattedMessage);
  2660. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  2661. Tools._AddLogEntry(entry);
  2662. };
  2663. Tools._WarnDisabled = function (message) {
  2664. // nothing to do
  2665. };
  2666. Tools._WarnEnabled = function (message) {
  2667. var formattedMessage = Tools._FormatMessage(message);
  2668. console.warn("BJS - " + formattedMessage);
  2669. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  2670. Tools._AddLogEntry(entry);
  2671. };
  2672. Tools._ErrorDisabled = function (message) {
  2673. // nothing to do
  2674. };
  2675. Tools._ErrorEnabled = function (message) {
  2676. var formattedMessage = Tools._FormatMessage(message);
  2677. console.error("BJS - " + formattedMessage);
  2678. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  2679. Tools._AddLogEntry(entry);
  2680. };
  2681. Object.defineProperty(Tools, "LogCache", {
  2682. get: function () {
  2683. return Tools._LogCache;
  2684. },
  2685. enumerable: true,
  2686. configurable: true
  2687. });
  2688. Object.defineProperty(Tools, "LogLevels", {
  2689. set: function (level) {
  2690. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  2691. Tools.Log = Tools._LogEnabled;
  2692. } else {
  2693. Tools.Log = Tools._LogDisabled;
  2694. }
  2695. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  2696. Tools.Warn = Tools._WarnEnabled;
  2697. } else {
  2698. Tools.Warn = Tools._WarnDisabled;
  2699. }
  2700. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  2701. Tools.Error = Tools._ErrorEnabled;
  2702. } else {
  2703. Tools.Error = Tools._ErrorDisabled;
  2704. }
  2705. },
  2706. enumerable: true,
  2707. configurable: true
  2708. });
  2709. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  2710. get: function () {
  2711. return Tools._PerformanceNoneLogLevel;
  2712. },
  2713. enumerable: true,
  2714. configurable: true
  2715. });
  2716. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  2717. get: function () {
  2718. return Tools._PerformanceUserMarkLogLevel;
  2719. },
  2720. enumerable: true,
  2721. configurable: true
  2722. });
  2723. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  2724. get: function () {
  2725. return Tools._PerformanceConsoleLogLevel;
  2726. },
  2727. enumerable: true,
  2728. configurable: true
  2729. });
  2730. Object.defineProperty(Tools, "PerformanceLogLevel", {
  2731. set: function (level) {
  2732. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  2733. Tools.StartPerformanceCounter = Tools._StartUserMark;
  2734. Tools.EndPerformanceCounter = Tools._EndUserMark;
  2735. return;
  2736. }
  2737. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  2738. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  2739. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  2740. return;
  2741. }
  2742. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  2743. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  2744. },
  2745. enumerable: true,
  2746. configurable: true
  2747. });
  2748. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  2749. };
  2750. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  2751. };
  2752. Tools._StartUserMark = function (counterName, condition) {
  2753. if (typeof condition === "undefined") { condition = true; }
  2754. if (!condition || !Tools._performance.mark) {
  2755. return;
  2756. }
  2757. Tools._performance.mark(counterName + "-Begin");
  2758. };
  2759. Tools._EndUserMark = function (counterName, condition) {
  2760. if (typeof condition === "undefined") { condition = true; }
  2761. if (!condition || !Tools._performance.mark) {
  2762. return;
  2763. }
  2764. Tools._performance.mark(counterName + "-End");
  2765. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  2766. };
  2767. Tools._StartPerformanceConsole = function (counterName, condition) {
  2768. if (typeof condition === "undefined") { condition = true; }
  2769. if (!condition) {
  2770. return;
  2771. }
  2772. Tools._StartUserMark(counterName, condition);
  2773. if (console.time) {
  2774. console.time(counterName);
  2775. }
  2776. };
  2777. Tools._EndPerformanceConsole = function (counterName, condition) {
  2778. if (typeof condition === "undefined") { condition = true; }
  2779. if (!condition) {
  2780. return;
  2781. }
  2782. Tools._EndUserMark(counterName, condition);
  2783. if (console.time) {
  2784. console.timeEnd(counterName);
  2785. }
  2786. };
  2787. Object.defineProperty(Tools, "Now", {
  2788. get: function () {
  2789. if (window.performance && window.performance.now) {
  2790. return window.performance.now();
  2791. }
  2792. return new Date().getTime();
  2793. },
  2794. enumerable: true,
  2795. configurable: true
  2796. });
  2797. // Deprecated
  2798. Tools.GetFps = function () {
  2799. Tools.Warn("Tools.GetFps() is deprecated. Please use engine.getFps() instead");
  2800. return 0;
  2801. };
  2802. Tools.BaseUrl = "";
  2803. Tools.GetExponantOfTwo = function (value, max) {
  2804. var count = 1;
  2805. do {
  2806. count *= 2;
  2807. } while(count < value);
  2808. if (count > max)
  2809. count = max;
  2810. return count;
  2811. };
  2812. Tools._NoneLogLevel = 0;
  2813. Tools._MessageLogLevel = 1;
  2814. Tools._WarningLogLevel = 2;
  2815. Tools._ErrorLogLevel = 4;
  2816. Tools._LogCache = "";
  2817. Tools.Log = Tools._LogEnabled;
  2818. Tools.Warn = Tools._WarnEnabled;
  2819. Tools.Error = Tools._ErrorEnabled;
  2820. Tools._PerformanceNoneLogLevel = 0;
  2821. Tools._PerformanceUserMarkLogLevel = 1;
  2822. Tools._PerformanceConsoleLogLevel = 2;
  2823. Tools._performance = window.performance;
  2824. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  2825. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  2826. return Tools;
  2827. })();
  2828. BABYLON.Tools = Tools;
  2829. })(BABYLON || (BABYLON = {}));
  2830. //# sourceMappingURL=babylon.tools.js.map
  2831. var BABYLON;
  2832. (function (BABYLON) {
  2833. var _DepthCullingState = (function () {
  2834. function _DepthCullingState() {
  2835. this._isDepthTestDirty = false;
  2836. this._isDepthMaskDirty = false;
  2837. this._isDepthFuncDirty = false;
  2838. this._isCullFaceDirty = false;
  2839. this._isCullDirty = false;
  2840. }
  2841. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  2842. get: function () {
  2843. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty;
  2844. },
  2845. enumerable: true,
  2846. configurable: true
  2847. });
  2848. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  2849. get: function () {
  2850. return this._cullFace;
  2851. },
  2852. set: function (value) {
  2853. if (this._cullFace === value) {
  2854. return;
  2855. }
  2856. this._cullFace = value;
  2857. this._isCullFaceDirty = true;
  2858. },
  2859. enumerable: true,
  2860. configurable: true
  2861. });
  2862. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  2863. get: function () {
  2864. return this._cull;
  2865. },
  2866. set: function (value) {
  2867. if (this._cull === value) {
  2868. return;
  2869. }
  2870. this._cull = value;
  2871. this._isCullDirty = true;
  2872. },
  2873. enumerable: true,
  2874. configurable: true
  2875. });
  2876. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  2877. get: function () {
  2878. return this._depthFunc;
  2879. },
  2880. set: function (value) {
  2881. if (this._depthFunc === value) {
  2882. return;
  2883. }
  2884. this._depthFunc = value;
  2885. this._isDepthFuncDirty = true;
  2886. },
  2887. enumerable: true,
  2888. configurable: true
  2889. });
  2890. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  2891. get: function () {
  2892. return this._depthMask;
  2893. },
  2894. set: function (value) {
  2895. if (this._depthMask === value) {
  2896. return;
  2897. }
  2898. this._depthMask = value;
  2899. this._isDepthMaskDirty = true;
  2900. },
  2901. enumerable: true,
  2902. configurable: true
  2903. });
  2904. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  2905. get: function () {
  2906. return this._depthTest;
  2907. },
  2908. set: function (value) {
  2909. if (this._depthTest === value) {
  2910. return;
  2911. }
  2912. this._depthTest = value;
  2913. this._isDepthTestDirty = true;
  2914. },
  2915. enumerable: true,
  2916. configurable: true
  2917. });
  2918. _DepthCullingState.prototype.reset = function () {
  2919. this._depthMask = true;
  2920. this._depthTest = true;
  2921. this._depthFunc = null;
  2922. this._cull = null;
  2923. this._cullFace = null;
  2924. this._isDepthTestDirty = true;
  2925. this._isDepthMaskDirty = true;
  2926. this._isDepthFuncDirty = false;
  2927. this._isCullFaceDirty = false;
  2928. this._isCullDirty = false;
  2929. };
  2930. _DepthCullingState.prototype.apply = function (gl) {
  2931. if (!this.isDirty) {
  2932. return;
  2933. }
  2934. // Cull
  2935. if (this._isCullDirty) {
  2936. if (this.cull === true) {
  2937. gl.enable(gl.CULL_FACE);
  2938. } else if (this.cull === false) {
  2939. gl.disable(gl.CULL_FACE);
  2940. }
  2941. this._isCullDirty = false;
  2942. }
  2943. // Cull face
  2944. if (this._isCullFaceDirty) {
  2945. gl.cullFace(this.cullFace);
  2946. this._isCullFaceDirty = false;
  2947. }
  2948. // Depth mask
  2949. if (this._isDepthMaskDirty) {
  2950. gl.depthMask(this.depthMask);
  2951. this._isDepthMaskDirty = false;
  2952. }
  2953. // Depth test
  2954. if (this._isDepthTestDirty) {
  2955. if (this.depthTest === true) {
  2956. gl.enable(gl.DEPTH_TEST);
  2957. } else if (this.depthTest === false) {
  2958. gl.disable(gl.DEPTH_TEST);
  2959. }
  2960. this._isDepthTestDirty = false;
  2961. }
  2962. // Depth func
  2963. if (this._isDepthFuncDirty) {
  2964. gl.depthFunc(this.depthFunc);
  2965. this._isDepthFuncDirty = false;
  2966. }
  2967. };
  2968. return _DepthCullingState;
  2969. })();
  2970. BABYLON._DepthCullingState = _DepthCullingState;
  2971. var _AlphaState = (function () {
  2972. function _AlphaState() {
  2973. this._isAlphaBlendDirty = false;
  2974. this._isBlendFunctionParametersDirty = false;
  2975. this._alphaBlend = false;
  2976. this._blendFunctionParameters = new Array(4);
  2977. }
  2978. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  2979. get: function () {
  2980. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  2981. },
  2982. enumerable: true,
  2983. configurable: true
  2984. });
  2985. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  2986. get: function () {
  2987. return this._alphaBlend;
  2988. },
  2989. set: function (value) {
  2990. if (this._alphaBlend === value) {
  2991. return;
  2992. }
  2993. this._alphaBlend = value;
  2994. this._isAlphaBlendDirty = true;
  2995. },
  2996. enumerable: true,
  2997. configurable: true
  2998. });
  2999. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  3000. if (this._blendFunctionParameters[0] === value0 && this._blendFunctionParameters[1] === value1 && this._blendFunctionParameters[2] === value2 && this._blendFunctionParameters[3] === value3) {
  3001. return;
  3002. }
  3003. this._blendFunctionParameters[0] = value0;
  3004. this._blendFunctionParameters[1] = value1;
  3005. this._blendFunctionParameters[2] = value2;
  3006. this._blendFunctionParameters[3] = value3;
  3007. this._isBlendFunctionParametersDirty = true;
  3008. };
  3009. _AlphaState.prototype.reset = function () {
  3010. this._alphaBlend = false;
  3011. this._blendFunctionParameters[0] = null;
  3012. this._blendFunctionParameters[1] = null;
  3013. this._blendFunctionParameters[2] = null;
  3014. this._blendFunctionParameters[3] = null;
  3015. this._isAlphaBlendDirty = true;
  3016. this._isBlendFunctionParametersDirty = false;
  3017. };
  3018. _AlphaState.prototype.apply = function (gl) {
  3019. if (!this.isDirty) {
  3020. return;
  3021. }
  3022. // Alpha blend
  3023. if (this._isAlphaBlendDirty) {
  3024. if (this._alphaBlend === true) {
  3025. gl.enable(gl.BLEND);
  3026. } else if (this._alphaBlend === false) {
  3027. gl.disable(gl.BLEND);
  3028. }
  3029. this._isAlphaBlendDirty = false;
  3030. }
  3031. // Alpha function
  3032. if (this._isBlendFunctionParametersDirty) {
  3033. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  3034. this._isBlendFunctionParametersDirty = false;
  3035. }
  3036. };
  3037. return _AlphaState;
  3038. })();
  3039. BABYLON._AlphaState = _AlphaState;
  3040. var compileShader = function (gl, source, type, defines) {
  3041. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  3042. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  3043. gl.compileShader(shader);
  3044. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  3045. throw new Error(gl.getShaderInfoLog(shader));
  3046. }
  3047. return shader;
  3048. };
  3049. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  3050. var magFilter = gl.NEAREST;
  3051. var minFilter = gl.NEAREST;
  3052. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  3053. magFilter = gl.LINEAR;
  3054. if (generateMipMaps) {
  3055. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  3056. } else {
  3057. minFilter = gl.LINEAR;
  3058. }
  3059. } else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  3060. magFilter = gl.LINEAR;
  3061. if (generateMipMaps) {
  3062. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  3063. } else {
  3064. minFilter = gl.LINEAR;
  3065. }
  3066. } else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  3067. magFilter = gl.NEAREST;
  3068. if (generateMipMaps) {
  3069. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  3070. } else {
  3071. minFilter = gl.NEAREST;
  3072. }
  3073. }
  3074. return {
  3075. min: minFilter,
  3076. mag: magFilter
  3077. };
  3078. };
  3079. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  3080. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  3081. var engine = scene.getEngine();
  3082. var potWidth = BABYLON.Tools.GetExponantOfTwo(width, engine.getCaps().maxTextureSize);
  3083. var potHeight = BABYLON.Tools.GetExponantOfTwo(height, engine.getCaps().maxTextureSize);
  3084. gl.bindTexture(gl.TEXTURE_2D, texture);
  3085. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  3086. processFunction(potWidth, potHeight);
  3087. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  3088. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  3089. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  3090. if (!noMipmap && !isCompressed) {
  3091. gl.generateMipmap(gl.TEXTURE_2D);
  3092. }
  3093. gl.bindTexture(gl.TEXTURE_2D, null);
  3094. engine._activeTexturesCache = [];
  3095. texture._baseWidth = width;
  3096. texture._baseHeight = height;
  3097. texture._width = potWidth;
  3098. texture._height = potHeight;
  3099. texture.isReady = true;
  3100. texture.samplingMode = samplingMode;
  3101. scene._removePendingData(texture);
  3102. };
  3103. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  3104. var img;
  3105. var onload = function () {
  3106. loadedImages[index] = img;
  3107. loadedImages._internalCount++;
  3108. scene._removePendingData(img);
  3109. if (loadedImages._internalCount == 6) {
  3110. onfinish(loadedImages);
  3111. }
  3112. };
  3113. var onerror = function () {
  3114. scene._removePendingData(img);
  3115. };
  3116. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  3117. scene._addPendingData(img);
  3118. };
  3119. var cascadeLoad = function (rootUrl, scene, onfinish, extensions) {
  3120. var loadedImages = [];
  3121. loadedImages._internalCount = 0;
  3122. for (var index = 0; index < 6; index++) {
  3123. partialLoad(rootUrl + extensions[index], index, loadedImages, scene, onfinish);
  3124. }
  3125. };
  3126. var EngineCapabilities = (function () {
  3127. function EngineCapabilities() {
  3128. }
  3129. return EngineCapabilities;
  3130. })();
  3131. BABYLON.EngineCapabilities = EngineCapabilities;
  3132. var Engine = (function () {
  3133. function Engine(canvas, antialias, options) {
  3134. var _this = this;
  3135. // Public members
  3136. this.isFullscreen = false;
  3137. this.isPointerLock = false;
  3138. this.cullBackFaces = true;
  3139. this.renderEvenInBackground = true;
  3140. this.scenes = new Array();
  3141. this._windowIsBackground = false;
  3142. this._loadingDivBackgroundColor = "black";
  3143. this._drawCalls = 0;
  3144. this._renderingQueueLaunched = false;
  3145. this._activeRenderLoops = [];
  3146. // FPS
  3147. this.fpsRange = 60;
  3148. this.previousFramesDuration = [];
  3149. this.fps = 60;
  3150. this.deltaTime = 0;
  3151. // States
  3152. this._depthCullingState = new _DepthCullingState();
  3153. this._alphaState = new _AlphaState();
  3154. this._alphaMode = Engine.ALPHA_DISABLE;
  3155. // Cache
  3156. this._loadedTexturesCache = new Array();
  3157. this._activeTexturesCache = new Array();
  3158. this._compiledEffects = {};
  3159. this._uintIndicesCurrentlySet = false;
  3160. this._renderingCanvas = canvas;
  3161. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  3162. options = options || {};
  3163. options.antialias = antialias;
  3164. try {
  3165. this._gl = canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options);
  3166. } catch (e) {
  3167. throw new Error("WebGL not supported");
  3168. }
  3169. if (!this._gl) {
  3170. throw new Error("WebGL not supported");
  3171. }
  3172. this._onBlur = function () {
  3173. _this._windowIsBackground = true;
  3174. };
  3175. this._onFocus = function () {
  3176. _this._windowIsBackground = false;
  3177. };
  3178. window.addEventListener("blur", this._onBlur);
  3179. window.addEventListener("focus", this._onFocus);
  3180. // Textures
  3181. this._workingCanvas = document.createElement("canvas");
  3182. this._workingContext = this._workingCanvas.getContext("2d");
  3183. // Viewport
  3184. this._hardwareScalingLevel = 1.0 / (window.devicePixelRatio || 1.0);
  3185. this.resize();
  3186. // Caps
  3187. this._caps = new EngineCapabilities();
  3188. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  3189. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  3190. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  3191. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  3192. // Extensions
  3193. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  3194. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  3195. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  3196. 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');
  3197. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  3198. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  3199. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  3200. // Depth buffer
  3201. this.setDepthBuffer(true);
  3202. this.setDepthFunctionToLessOrEqual();
  3203. this.setDepthWrite(true);
  3204. // Fullscreen
  3205. this._onFullscreenChange = function () {
  3206. if (document.fullscreen !== undefined) {
  3207. _this.isFullscreen = document.fullscreen;
  3208. } else if (document.mozFullScreen !== undefined) {
  3209. _this.isFullscreen = document.mozFullScreen;
  3210. } else if (document.webkitIsFullScreen !== undefined) {
  3211. _this.isFullscreen = document.webkitIsFullScreen;
  3212. } else if (document.msIsFullScreen !== undefined) {
  3213. _this.isFullscreen = document.msIsFullScreen;
  3214. }
  3215. // Pointer lock
  3216. if (_this.isFullscreen && _this._pointerLockRequested) {
  3217. canvas.requestPointerLock = canvas.requestPointerLock || canvas.msRequestPointerLock || canvas.mozRequestPointerLock || canvas.webkitRequestPointerLock;
  3218. if (canvas.requestPointerLock) {
  3219. canvas.requestPointerLock();
  3220. }
  3221. }
  3222. };
  3223. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  3224. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  3225. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  3226. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  3227. // Pointer lock
  3228. this._onPointerLockChange = function () {
  3229. _this.isPointerLock = (document.mozPointerLockElement === canvas || document.webkitPointerLockElement === canvas || document.msPointerLockElement === canvas || document.pointerLockElement === canvas);
  3230. };
  3231. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  3232. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  3233. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  3234. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  3235. this._audioEngine = new BABYLON.AudioEngine();
  3236. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  3237. }
  3238. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  3239. get: function () {
  3240. return Engine._ALPHA_DISABLE;
  3241. },
  3242. enumerable: true,
  3243. configurable: true
  3244. });
  3245. Object.defineProperty(Engine, "ALPHA_ADD", {
  3246. get: function () {
  3247. return Engine._ALPHA_ADD;
  3248. },
  3249. enumerable: true,
  3250. configurable: true
  3251. });
  3252. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  3253. get: function () {
  3254. return Engine._ALPHA_COMBINE;
  3255. },
  3256. enumerable: true,
  3257. configurable: true
  3258. });
  3259. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  3260. get: function () {
  3261. return Engine._DELAYLOADSTATE_NONE;
  3262. },
  3263. enumerable: true,
  3264. configurable: true
  3265. });
  3266. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  3267. get: function () {
  3268. return Engine._DELAYLOADSTATE_LOADED;
  3269. },
  3270. enumerable: true,
  3271. configurable: true
  3272. });
  3273. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  3274. get: function () {
  3275. return Engine._DELAYLOADSTATE_LOADING;
  3276. },
  3277. enumerable: true,
  3278. configurable: true
  3279. });
  3280. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  3281. get: function () {
  3282. return Engine._DELAYLOADSTATE_NOTLOADED;
  3283. },
  3284. enumerable: true,
  3285. configurable: true
  3286. });
  3287. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  3288. get: function () {
  3289. return Engine._TEXTUREFORMAT_ALPHA;
  3290. },
  3291. enumerable: true,
  3292. configurable: true
  3293. });
  3294. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  3295. get: function () {
  3296. return Engine._TEXTUREFORMAT_LUMINANCE;
  3297. },
  3298. enumerable: true,
  3299. configurable: true
  3300. });
  3301. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  3302. get: function () {
  3303. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  3304. },
  3305. enumerable: true,
  3306. configurable: true
  3307. });
  3308. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  3309. get: function () {
  3310. return Engine._TEXTUREFORMAT_RGB;
  3311. },
  3312. enumerable: true,
  3313. configurable: true
  3314. });
  3315. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  3316. get: function () {
  3317. return Engine._TEXTUREFORMAT_RGBA;
  3318. },
  3319. enumerable: true,
  3320. configurable: true
  3321. });
  3322. Object.defineProperty(Engine, "Version", {
  3323. get: function () {
  3324. return "2.0.0";
  3325. },
  3326. enumerable: true,
  3327. configurable: true
  3328. });
  3329. Engine.prototype.getAudioEngine = function () {
  3330. return this._audioEngine;
  3331. };
  3332. Engine.prototype.getAspectRatio = function (camera) {
  3333. var viewport = camera.viewport;
  3334. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  3335. };
  3336. Engine.prototype.getRenderWidth = function () {
  3337. if (this._currentRenderTarget) {
  3338. return this._currentRenderTarget._width;
  3339. }
  3340. return this._renderingCanvas.width;
  3341. };
  3342. Engine.prototype.getRenderHeight = function () {
  3343. if (this._currentRenderTarget) {
  3344. return this._currentRenderTarget._height;
  3345. }
  3346. return this._renderingCanvas.height;
  3347. };
  3348. Engine.prototype.getRenderingCanvas = function () {
  3349. return this._renderingCanvas;
  3350. };
  3351. Engine.prototype.getRenderingCanvasClientRect = function () {
  3352. return this._renderingCanvas.getBoundingClientRect();
  3353. };
  3354. Engine.prototype.setHardwareScalingLevel = function (level) {
  3355. this._hardwareScalingLevel = level;
  3356. this.resize();
  3357. };
  3358. Engine.prototype.getHardwareScalingLevel = function () {
  3359. return this._hardwareScalingLevel;
  3360. };
  3361. Engine.prototype.getLoadedTexturesCache = function () {
  3362. return this._loadedTexturesCache;
  3363. };
  3364. Engine.prototype.getCaps = function () {
  3365. return this._caps;
  3366. };
  3367. Object.defineProperty(Engine.prototype, "drawCalls", {
  3368. get: function () {
  3369. return this._drawCalls;
  3370. },
  3371. enumerable: true,
  3372. configurable: true
  3373. });
  3374. // Methods
  3375. Engine.prototype.resetDrawCalls = function () {
  3376. this._drawCalls = 0;
  3377. };
  3378. Engine.prototype.setDepthFunctionToGreater = function () {
  3379. this._depthCullingState.depthFunc = this._gl.GREATER;
  3380. };
  3381. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  3382. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  3383. };
  3384. Engine.prototype.setDepthFunctionToLess = function () {
  3385. this._depthCullingState.depthFunc = this._gl.LESS;
  3386. };
  3387. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  3388. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  3389. };
  3390. Engine.prototype.stopRenderLoop = function (renderFunction) {
  3391. if (!renderFunction) {
  3392. this._activeRenderLoops = [];
  3393. return;
  3394. }
  3395. var index = this._activeRenderLoops.indexOf(renderFunction);
  3396. if (index >= 0) {
  3397. this._activeRenderLoops.splice(index, 1);
  3398. }
  3399. };
  3400. Engine.prototype._renderLoop = function () {
  3401. var _this = this;
  3402. var shouldRender = true;
  3403. if (!this.renderEvenInBackground && this._windowIsBackground) {
  3404. shouldRender = false;
  3405. }
  3406. if (shouldRender) {
  3407. // Start new frame
  3408. this.beginFrame();
  3409. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  3410. var renderFunction = this._activeRenderLoops[index];
  3411. renderFunction();
  3412. }
  3413. // Present
  3414. this.endFrame();
  3415. }
  3416. if (this._activeRenderLoops.length > 0) {
  3417. // Register new frame
  3418. BABYLON.Tools.QueueNewFrame(function () {
  3419. _this._renderLoop();
  3420. });
  3421. } else {
  3422. this._renderingQueueLaunched = false;
  3423. }
  3424. };
  3425. Engine.prototype.runRenderLoop = function (renderFunction) {
  3426. var _this = this;
  3427. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  3428. return;
  3429. }
  3430. this._activeRenderLoops.push(renderFunction);
  3431. if (!this._renderingQueueLaunched) {
  3432. this._renderingQueueLaunched = true;
  3433. BABYLON.Tools.QueueNewFrame(function () {
  3434. _this._renderLoop();
  3435. });
  3436. }
  3437. };
  3438. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  3439. if (this.isFullscreen) {
  3440. BABYLON.Tools.ExitFullscreen();
  3441. } else {
  3442. this._pointerLockRequested = requestPointerLock;
  3443. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  3444. }
  3445. };
  3446. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  3447. this.applyStates();
  3448. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  3449. if (this._depthCullingState.depthMask) {
  3450. this._gl.clearDepth(1.0);
  3451. }
  3452. var mode = 0;
  3453. if (backBuffer)
  3454. mode |= this._gl.COLOR_BUFFER_BIT;
  3455. if (depthStencil && this._depthCullingState.depthMask)
  3456. mode |= this._gl.DEPTH_BUFFER_BIT;
  3457. this._gl.clear(mode);
  3458. };
  3459. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  3460. var width = requiredWidth || this._renderingCanvas.width;
  3461. var height = requiredHeight || this._renderingCanvas.height;
  3462. var x = viewport.x || 0;
  3463. var y = viewport.y || 0;
  3464. this._cachedViewport = viewport;
  3465. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  3466. };
  3467. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  3468. this._cachedViewport = null;
  3469. this._gl.viewport(x, y, width, height);
  3470. };
  3471. Engine.prototype.beginFrame = function () {
  3472. this._measureFps();
  3473. };
  3474. Engine.prototype.endFrame = function () {
  3475. this.flushFramebuffer();
  3476. };
  3477. Engine.prototype.resize = function () {
  3478. this.setSize(this._renderingCanvas.clientWidth / this._hardwareScalingLevel, this._renderingCanvas.clientHeight / this._hardwareScalingLevel);
  3479. };
  3480. Engine.prototype.setSize = function (width, height) {
  3481. this._renderingCanvas.width = width;
  3482. this._renderingCanvas.height = height;
  3483. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  3484. };
  3485. Engine.prototype.bindFramebuffer = function (texture) {
  3486. this._currentRenderTarget = texture;
  3487. var gl = this._gl;
  3488. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  3489. this._gl.viewport(0, 0, texture._width, texture._height);
  3490. this.wipeCaches();
  3491. };
  3492. Engine.prototype.unBindFramebuffer = function (texture) {
  3493. this._currentRenderTarget = null;
  3494. if (texture.generateMipMaps) {
  3495. var gl = this._gl;
  3496. gl.bindTexture(gl.TEXTURE_2D, texture);
  3497. gl.generateMipmap(gl.TEXTURE_2D);
  3498. gl.bindTexture(gl.TEXTURE_2D, null);
  3499. }
  3500. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  3501. };
  3502. Engine.prototype.flushFramebuffer = function () {
  3503. // this._gl.flush();
  3504. };
  3505. Engine.prototype.restoreDefaultFramebuffer = function () {
  3506. this._currentRenderTarget = null;
  3507. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  3508. this.setViewport(this._cachedViewport);
  3509. this.wipeCaches();
  3510. };
  3511. // VBOs
  3512. Engine.prototype._resetVertexBufferBinding = function () {
  3513. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  3514. this._cachedVertexBuffers = null;
  3515. };
  3516. Engine.prototype.createVertexBuffer = function (vertices) {
  3517. var vbo = this._gl.createBuffer();
  3518. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  3519. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  3520. this._resetVertexBufferBinding();
  3521. vbo.references = 1;
  3522. return vbo;
  3523. };
  3524. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  3525. var vbo = this._gl.createBuffer();
  3526. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  3527. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  3528. this._resetVertexBufferBinding();
  3529. vbo.references = 1;
  3530. return vbo;
  3531. };
  3532. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  3533. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  3534. if (offset === undefined) {
  3535. offset = 0;
  3536. }
  3537. if (vertices instanceof Float32Array) {
  3538. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  3539. } else {
  3540. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  3541. }
  3542. this._resetVertexBufferBinding();
  3543. };
  3544. Engine.prototype._resetIndexBufferBinding = function () {
  3545. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  3546. this._cachedIndexBuffer = null;
  3547. };
  3548. Engine.prototype.createIndexBuffer = function (indices) {
  3549. var vbo = this._gl.createBuffer();
  3550. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  3551. // Check for 32 bits indices
  3552. var arrayBuffer;
  3553. var need32Bits = false;
  3554. if (this._caps.uintIndices) {
  3555. for (var index = 0; index < indices.length; index++) {
  3556. if (indices[index] > 65535) {
  3557. need32Bits = true;
  3558. break;
  3559. }
  3560. }
  3561. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  3562. } else {
  3563. arrayBuffer = new Uint16Array(indices);
  3564. }
  3565. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  3566. this._resetIndexBufferBinding();
  3567. vbo.references = 1;
  3568. vbo.is32Bits = need32Bits;
  3569. return vbo;
  3570. };
  3571. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  3572. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  3573. this._cachedVertexBuffers = vertexBuffer;
  3574. this._cachedEffectForVertexBuffers = effect;
  3575. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  3576. var offset = 0;
  3577. for (var index = 0; index < vertexDeclaration.length; index++) {
  3578. var order = effect.getAttributeLocation(index);
  3579. if (order >= 0) {
  3580. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  3581. }
  3582. offset += vertexDeclaration[index] * 4;
  3583. }
  3584. }
  3585. if (this._cachedIndexBuffer !== indexBuffer) {
  3586. this._cachedIndexBuffer = indexBuffer;
  3587. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  3588. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  3589. }
  3590. };
  3591. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  3592. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  3593. this._cachedVertexBuffers = vertexBuffers;
  3594. this._cachedEffectForVertexBuffers = effect;
  3595. var attributes = effect.getAttributesNames();
  3596. for (var index = 0; index < attributes.length; index++) {
  3597. var order = effect.getAttributeLocation(index);
  3598. if (order >= 0) {
  3599. var vertexBuffer = vertexBuffers[attributes[index]];
  3600. if (!vertexBuffer) {
  3601. continue;
  3602. }
  3603. var stride = vertexBuffer.getStrideSize();
  3604. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  3605. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  3606. }
  3607. }
  3608. }
  3609. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  3610. this._cachedIndexBuffer = indexBuffer;
  3611. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  3612. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  3613. }
  3614. };
  3615. Engine.prototype._releaseBuffer = function (buffer) {
  3616. buffer.references--;
  3617. if (buffer.references === 0) {
  3618. this._gl.deleteBuffer(buffer);
  3619. return true;
  3620. }
  3621. return false;
  3622. };
  3623. Engine.prototype.createInstancesBuffer = function (capacity) {
  3624. var buffer = this._gl.createBuffer();
  3625. buffer.capacity = capacity;
  3626. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  3627. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  3628. return buffer;
  3629. };
  3630. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  3631. this._gl.deleteBuffer(buffer);
  3632. };
  3633. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  3634. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  3635. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  3636. for (var index = 0; index < 4; index++) {
  3637. var offsetLocation = offsetLocations[index];
  3638. this._gl.enableVertexAttribArray(offsetLocation);
  3639. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  3640. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  3641. }
  3642. };
  3643. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  3644. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  3645. for (var index = 0; index < 4; index++) {
  3646. var offsetLocation = offsetLocations[index];
  3647. this._gl.disableVertexAttribArray(offsetLocation);
  3648. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  3649. }
  3650. };
  3651. Engine.prototype.applyStates = function () {
  3652. this._depthCullingState.apply(this._gl);
  3653. this._alphaState.apply(this._gl);
  3654. };
  3655. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  3656. // Apply states
  3657. this.applyStates();
  3658. this._drawCalls++;
  3659. // Render
  3660. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  3661. if (instancesCount) {
  3662. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2, instancesCount);
  3663. return;
  3664. }
  3665. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2);
  3666. };
  3667. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  3668. // Apply states
  3669. this.applyStates();
  3670. this._drawCalls++;
  3671. if (instancesCount) {
  3672. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  3673. return;
  3674. }
  3675. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  3676. };
  3677. // Shaders
  3678. Engine.prototype._releaseEffect = function (effect) {
  3679. if (this._compiledEffects[effect._key]) {
  3680. delete this._compiledEffects[effect._key];
  3681. if (effect.getProgram()) {
  3682. this._gl.deleteProgram(effect.getProgram());
  3683. }
  3684. }
  3685. };
  3686. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  3687. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  3688. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  3689. var name = vertex + "+" + fragment + "@" + defines;
  3690. if (this._compiledEffects[name]) {
  3691. return this._compiledEffects[name];
  3692. }
  3693. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  3694. effect._key = name;
  3695. this._compiledEffects[name] = effect;
  3696. return effect;
  3697. };
  3698. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  3699. if (typeof uniformsNames === "undefined") { uniformsNames = []; }
  3700. if (typeof samplers === "undefined") { samplers = []; }
  3701. if (typeof defines === "undefined") { defines = ""; }
  3702. return this.createEffect({
  3703. vertex: "particles",
  3704. fragmentElement: fragmentName
  3705. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  3706. };
  3707. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  3708. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  3709. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  3710. var shaderProgram = this._gl.createProgram();
  3711. this._gl.attachShader(shaderProgram, vertexShader);
  3712. this._gl.attachShader(shaderProgram, fragmentShader);
  3713. this._gl.linkProgram(shaderProgram);
  3714. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  3715. if (!linked) {
  3716. var error = this._gl.getProgramInfoLog(shaderProgram);
  3717. if (error) {
  3718. throw new Error(error);
  3719. }
  3720. }
  3721. this._gl.deleteShader(vertexShader);
  3722. this._gl.deleteShader(fragmentShader);
  3723. return shaderProgram;
  3724. };
  3725. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  3726. var results = [];
  3727. for (var index = 0; index < uniformsNames.length; index++) {
  3728. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  3729. }
  3730. return results;
  3731. };
  3732. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  3733. var results = [];
  3734. for (var index = 0; index < attributesNames.length; index++) {
  3735. try {
  3736. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  3737. } catch (e) {
  3738. results.push(-1);
  3739. }
  3740. }
  3741. return results;
  3742. };
  3743. Engine.prototype.enableEffect = function (effect) {
  3744. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  3745. if (effect && effect.onBind) {
  3746. effect.onBind(effect);
  3747. }
  3748. return;
  3749. }
  3750. this._vertexAttribArrays = this._vertexAttribArrays || [];
  3751. // Use program
  3752. this._gl.useProgram(effect.getProgram());
  3753. for (var i in this._vertexAttribArrays) {
  3754. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  3755. continue;
  3756. }
  3757. this._vertexAttribArrays[i] = false;
  3758. this._gl.disableVertexAttribArray(i);
  3759. }
  3760. var attributesCount = effect.getAttributesCount();
  3761. for (var index = 0; index < attributesCount; index++) {
  3762. // Attributes
  3763. var order = effect.getAttributeLocation(index);
  3764. if (order >= 0) {
  3765. this._vertexAttribArrays[order] = true;
  3766. this._gl.enableVertexAttribArray(order);
  3767. }
  3768. }
  3769. this._currentEffect = effect;
  3770. if (effect.onBind) {
  3771. effect.onBind(effect);
  3772. }
  3773. };
  3774. Engine.prototype.setArray = function (uniform, array) {
  3775. if (!uniform)
  3776. return;
  3777. this._gl.uniform1fv(uniform, array);
  3778. };
  3779. Engine.prototype.setMatrices = function (uniform, matrices) {
  3780. if (!uniform)
  3781. return;
  3782. this._gl.uniformMatrix4fv(uniform, false, matrices);
  3783. };
  3784. Engine.prototype.setMatrix = function (uniform, matrix) {
  3785. if (!uniform)
  3786. return;
  3787. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  3788. };
  3789. Engine.prototype.setFloat = function (uniform, value) {
  3790. if (!uniform)
  3791. return;
  3792. this._gl.uniform1f(uniform, value);
  3793. };
  3794. Engine.prototype.setFloat2 = function (uniform, x, y) {
  3795. if (!uniform)
  3796. return;
  3797. this._gl.uniform2f(uniform, x, y);
  3798. };
  3799. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  3800. if (!uniform)
  3801. return;
  3802. this._gl.uniform3f(uniform, x, y, z);
  3803. };
  3804. Engine.prototype.setBool = function (uniform, bool) {
  3805. if (!uniform)
  3806. return;
  3807. this._gl.uniform1i(uniform, bool);
  3808. };
  3809. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  3810. if (!uniform)
  3811. return;
  3812. this._gl.uniform4f(uniform, x, y, z, w);
  3813. };
  3814. Engine.prototype.setColor3 = function (uniform, color3) {
  3815. if (!uniform)
  3816. return;
  3817. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  3818. };
  3819. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  3820. if (!uniform)
  3821. return;
  3822. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  3823. };
  3824. // States
  3825. Engine.prototype.setState = function (culling, force) {
  3826. // Culling
  3827. if (this._depthCullingState.cull !== culling || force) {
  3828. if (culling) {
  3829. this._depthCullingState.cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  3830. this._depthCullingState.cull = true;
  3831. } else {
  3832. this._depthCullingState.cull = false;
  3833. }
  3834. }
  3835. };
  3836. Engine.prototype.setDepthBuffer = function (enable) {
  3837. this._depthCullingState.depthTest = enable;
  3838. };
  3839. Engine.prototype.getDepthWrite = function () {
  3840. return this._depthCullingState.depthMask;
  3841. };
  3842. Engine.prototype.setDepthWrite = function (enable) {
  3843. this._depthCullingState.depthMask = enable;
  3844. };
  3845. Engine.prototype.setColorWrite = function (enable) {
  3846. this._gl.colorMask(enable, enable, enable, enable);
  3847. };
  3848. Engine.prototype.setAlphaMode = function (mode) {
  3849. switch (mode) {
  3850. case BABYLON.Engine.ALPHA_DISABLE:
  3851. this.setDepthWrite(true);
  3852. this._alphaState.alphaBlend = false;
  3853. break;
  3854. case BABYLON.Engine.ALPHA_COMBINE:
  3855. this.setDepthWrite(false);
  3856. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  3857. this._alphaState.alphaBlend = true;
  3858. break;
  3859. case BABYLON.Engine.ALPHA_ADD:
  3860. this.setDepthWrite(false);
  3861. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  3862. this._alphaState.alphaBlend = true;
  3863. break;
  3864. }
  3865. this._alphaMode = mode;
  3866. };
  3867. Engine.prototype.getAlphaMode = function () {
  3868. return this._alphaMode;
  3869. };
  3870. Engine.prototype.setAlphaTesting = function (enable) {
  3871. this._alphaTest = enable;
  3872. };
  3873. Engine.prototype.getAlphaTesting = function () {
  3874. return this._alphaTest;
  3875. };
  3876. // Textures
  3877. Engine.prototype.wipeCaches = function () {
  3878. this._activeTexturesCache = [];
  3879. this._currentEffect = null;
  3880. this._depthCullingState.reset();
  3881. this._alphaState.reset();
  3882. this._cachedVertexBuffers = null;
  3883. this._cachedIndexBuffer = null;
  3884. this._cachedEffectForVertexBuffers = null;
  3885. };
  3886. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  3887. var gl = this._gl;
  3888. gl.bindTexture(gl.TEXTURE_2D, texture);
  3889. var magFilter = gl.NEAREST;
  3890. var minFilter = gl.NEAREST;
  3891. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  3892. magFilter = gl.LINEAR;
  3893. minFilter = gl.LINEAR;
  3894. } else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  3895. magFilter = gl.LINEAR;
  3896. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  3897. }
  3898. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  3899. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  3900. gl.bindTexture(gl.TEXTURE_2D, null);
  3901. texture.samplingMode = samplingMode;
  3902. };
  3903. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  3904. var _this = this;
  3905. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  3906. if (typeof onLoad === "undefined") { onLoad = null; }
  3907. if (typeof onError === "undefined") { onError = null; }
  3908. if (typeof buffer === "undefined") { buffer = null; }
  3909. var texture = this._gl.createTexture();
  3910. var extension;
  3911. var fromData = false;
  3912. if (url.substr(0, 5) === "data:") {
  3913. fromData = true;
  3914. }
  3915. if (!fromData)
  3916. extension = url.substr(url.length - 4, 4).toLowerCase();
  3917. else {
  3918. var oldUrl = url;
  3919. fromData = oldUrl.split(':');
  3920. url = oldUrl;
  3921. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  3922. }
  3923. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  3924. var isTGA = (extension === ".tga");
  3925. scene._addPendingData(texture);
  3926. texture.url = url;
  3927. texture.noMipmap = noMipmap;
  3928. texture.references = 1;
  3929. this._loadedTexturesCache.push(texture);
  3930. var onerror = function () {
  3931. scene._removePendingData(texture);
  3932. if (onError) {
  3933. onError();
  3934. }
  3935. };
  3936. if (isTGA) {
  3937. var callback = function (arrayBuffer) {
  3938. var data = new Uint8Array(arrayBuffer);
  3939. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  3940. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  3941. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  3942. if (onLoad) {
  3943. onLoad();
  3944. }
  3945. }, samplingMode);
  3946. };
  3947. if (!(fromData instanceof Array))
  3948. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  3949. callback(arrayBuffer);
  3950. }, onerror, scene.database, true);
  3951. else
  3952. callback(buffer);
  3953. } else if (isDDS) {
  3954. callback = function (data) {
  3955. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  3956. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) == 1);
  3957. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  3958. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  3959. if (onLoad) {
  3960. onLoad();
  3961. }
  3962. }, samplingMode);
  3963. };
  3964. if (!(fromData instanceof Array))
  3965. BABYLON.Tools.LoadFile(url, function (data) {
  3966. callback(data);
  3967. }, onerror, scene.database, true);
  3968. else
  3969. callback(buffer);
  3970. } else {
  3971. var onload = function (img) {
  3972. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  3973. var isPot = (img.width == potWidth && img.height == potHeight);
  3974. if (!isPot) {
  3975. _this._workingCanvas.width = potWidth;
  3976. _this._workingCanvas.height = potHeight;
  3977. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  3978. }
  3979. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  3980. if (onLoad) {
  3981. onLoad();
  3982. }
  3983. }, samplingMode);
  3984. };
  3985. if (!(fromData instanceof Array))
  3986. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  3987. else
  3988. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  3989. }
  3990. return texture;
  3991. };
  3992. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode) {
  3993. var texture = this._gl.createTexture();
  3994. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  3995. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  3996. // Format
  3997. var internalFormat = this._gl.RGBA;
  3998. switch (format) {
  3999. case Engine.TEXTUREFORMAT_ALPHA:
  4000. internalFormat = this._gl.ALPHA;
  4001. break;
  4002. case Engine.TEXTUREFORMAT_LUMINANCE:
  4003. internalFormat = this._gl.LUMINANCE;
  4004. break;
  4005. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  4006. internalFormat = this._gl.LUMINANCE_ALPHA;
  4007. break;
  4008. case Engine.TEXTUREFORMAT_RGB:
  4009. internalFormat = this._gl.RGB;
  4010. break;
  4011. case Engine.TEXTUREFORMAT_RGBA:
  4012. internalFormat = this._gl.RGBA;
  4013. break;
  4014. }
  4015. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, width, height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  4016. if (generateMipMaps) {
  4017. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4018. }
  4019. // Filters
  4020. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  4021. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  4022. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  4023. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4024. this._activeTexturesCache = [];
  4025. texture._baseWidth = width;
  4026. texture._baseHeight = height;
  4027. texture._width = width;
  4028. texture._height = height;
  4029. texture.isReady = true;
  4030. texture.references = 1;
  4031. texture.samplingMode = samplingMode;
  4032. this._loadedTexturesCache.push(texture);
  4033. return texture;
  4034. };
  4035. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  4036. var texture = this._gl.createTexture();
  4037. width = BABYLON.Tools.GetExponantOfTwo(width, this._caps.maxTextureSize);
  4038. height = BABYLON.Tools.GetExponantOfTwo(height, this._caps.maxTextureSize);
  4039. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4040. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  4041. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  4042. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  4043. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4044. this._activeTexturesCache = [];
  4045. texture._baseWidth = width;
  4046. texture._baseHeight = height;
  4047. texture._width = width;
  4048. texture._height = height;
  4049. texture.isReady = false;
  4050. texture.generateMipMaps = generateMipMaps;
  4051. texture.references = 1;
  4052. texture.samplingMode = samplingMode;
  4053. this._loadedTexturesCache.push(texture);
  4054. return texture;
  4055. };
  4056. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  4057. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4058. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  4059. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  4060. if (texture.generateMipMaps) {
  4061. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4062. }
  4063. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4064. this._activeTexturesCache = [];
  4065. texture.isReady = true;
  4066. };
  4067. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  4068. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4069. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  4070. // Scale the video if it is a NPOT using the current working canvas
  4071. if (video.videoWidth !== texture._width || video.videoHeight !== texture._height) {
  4072. if (!texture._workingCanvas) {
  4073. texture._workingCanvas = document.createElement("canvas");
  4074. texture._workingContext = texture._workingCanvas.getContext("2d");
  4075. texture._workingCanvas.width = texture._width;
  4076. texture._workingCanvas.height = texture._height;
  4077. }
  4078. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  4079. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  4080. } else {
  4081. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  4082. }
  4083. if (texture.generateMipMaps) {
  4084. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4085. }
  4086. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4087. this._activeTexturesCache = [];
  4088. texture.isReady = true;
  4089. };
  4090. Engine.prototype.createRenderTargetTexture = function (size, options) {
  4091. // old version had a "generateMipMaps" arg instead of options.
  4092. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  4093. // in the same way, generateDepthBuffer is defaulted to true
  4094. var generateMipMaps = false;
  4095. var generateDepthBuffer = true;
  4096. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  4097. if (options !== undefined) {
  4098. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipmaps;
  4099. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  4100. if (options.samplingMode !== undefined) {
  4101. samplingMode = options.samplingMode;
  4102. }
  4103. }
  4104. var gl = this._gl;
  4105. var texture = gl.createTexture();
  4106. gl.bindTexture(gl.TEXTURE_2D, texture);
  4107. var width = size.width || size;
  4108. var height = size.height || size;
  4109. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  4110. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  4111. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  4112. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4113. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4114. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  4115. var depthBuffer;
  4116. // Create the depth buffer
  4117. if (generateDepthBuffer) {
  4118. depthBuffer = gl.createRenderbuffer();
  4119. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  4120. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  4121. }
  4122. // Create the framebuffer
  4123. var framebuffer = gl.createFramebuffer();
  4124. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  4125. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  4126. if (generateDepthBuffer) {
  4127. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  4128. }
  4129. // Unbind
  4130. gl.bindTexture(gl.TEXTURE_2D, null);
  4131. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  4132. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  4133. texture._framebuffer = framebuffer;
  4134. if (generateDepthBuffer) {
  4135. texture._depthBuffer = depthBuffer;
  4136. }
  4137. texture._width = width;
  4138. texture._height = height;
  4139. texture.isReady = true;
  4140. texture.generateMipMaps = generateMipMaps;
  4141. texture.references = 1;
  4142. texture.samplingMode = samplingMode;
  4143. this._activeTexturesCache = [];
  4144. this._loadedTexturesCache.push(texture);
  4145. return texture;
  4146. };
  4147. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  4148. var _this = this;
  4149. var gl = this._gl;
  4150. var texture = gl.createTexture();
  4151. texture.isCube = true;
  4152. texture.url = rootUrl;
  4153. texture.references = 1;
  4154. this._loadedTexturesCache.push(texture);
  4155. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  4156. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  4157. if (isDDS) {
  4158. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  4159. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  4160. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  4161. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  4162. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  4163. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  4164. if (!noMipmap && !info.isFourCC && info.mipmapCount == 1) {
  4165. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  4166. }
  4167. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  4168. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  4169. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4170. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4171. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  4172. _this._activeTexturesCache = [];
  4173. texture._width = info.width;
  4174. texture._height = info.height;
  4175. texture.isReady = true;
  4176. }, null, null, true);
  4177. } else {
  4178. cascadeLoad(rootUrl, scene, function (imgs) {
  4179. var width = BABYLON.Tools.GetExponantOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  4180. var height = width;
  4181. _this._workingCanvas.width = width;
  4182. _this._workingCanvas.height = height;
  4183. var faces = [
  4184. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  4185. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  4186. ];
  4187. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  4188. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  4189. for (var index = 0; index < faces.length; index++) {
  4190. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  4191. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  4192. }
  4193. if (!noMipmap) {
  4194. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  4195. }
  4196. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  4197. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  4198. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4199. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4200. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  4201. _this._activeTexturesCache = [];
  4202. texture._width = width;
  4203. texture._height = height;
  4204. texture.isReady = true;
  4205. }, extensions);
  4206. }
  4207. return texture;
  4208. };
  4209. Engine.prototype._releaseTexture = function (texture) {
  4210. var gl = this._gl;
  4211. if (texture._framebuffer) {
  4212. gl.deleteFramebuffer(texture._framebuffer);
  4213. }
  4214. if (texture._depthBuffer) {
  4215. gl.deleteRenderbuffer(texture._depthBuffer);
  4216. }
  4217. gl.deleteTexture(texture);
  4218. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  4219. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4220. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4221. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  4222. this._activeTexturesCache[channel] = null;
  4223. }
  4224. var index = this._loadedTexturesCache.indexOf(texture);
  4225. if (index !== -1) {
  4226. this._loadedTexturesCache.splice(index, 1);
  4227. }
  4228. };
  4229. Engine.prototype.bindSamplers = function (effect) {
  4230. this._gl.useProgram(effect.getProgram());
  4231. var samplers = effect.getSamplers();
  4232. for (var index = 0; index < samplers.length; index++) {
  4233. var uniform = effect.getUniform(samplers[index]);
  4234. this._gl.uniform1i(uniform, index);
  4235. }
  4236. this._currentEffect = null;
  4237. };
  4238. Engine.prototype._bindTexture = function (channel, texture) {
  4239. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4240. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4241. this._activeTexturesCache[channel] = null;
  4242. };
  4243. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  4244. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  4245. };
  4246. Engine.prototype.setTexture = function (channel, texture) {
  4247. if (channel < 0) {
  4248. return;
  4249. }
  4250. // Not ready?
  4251. if (!texture || !texture.isReady()) {
  4252. if (this._activeTexturesCache[channel] != null) {
  4253. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4254. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4255. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  4256. this._activeTexturesCache[channel] = null;
  4257. }
  4258. return;
  4259. }
  4260. // Video
  4261. if (texture instanceof BABYLON.VideoTexture) {
  4262. if (texture.update()) {
  4263. this._activeTexturesCache[channel] = null;
  4264. }
  4265. } else if (texture.delayLoadState == BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  4266. texture.delayLoad();
  4267. return;
  4268. }
  4269. if (this._activeTexturesCache[channel] == texture) {
  4270. return;
  4271. }
  4272. this._activeTexturesCache[channel] = texture;
  4273. var internalTexture = texture.getInternalTexture();
  4274. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4275. if (internalTexture.isCube) {
  4276. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  4277. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  4278. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  4279. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  4280. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  4281. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  4282. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  4283. }
  4284. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  4285. } else {
  4286. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  4287. if (internalTexture._cachedWrapU !== texture.wrapU) {
  4288. internalTexture._cachedWrapU = texture.wrapU;
  4289. switch (texture.wrapU) {
  4290. case BABYLON.Texture.WRAP_ADDRESSMODE:
  4291. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  4292. break;
  4293. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  4294. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  4295. break;
  4296. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  4297. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  4298. break;
  4299. }
  4300. }
  4301. if (internalTexture._cachedWrapV !== texture.wrapV) {
  4302. internalTexture._cachedWrapV = texture.wrapV;
  4303. switch (texture.wrapV) {
  4304. case BABYLON.Texture.WRAP_ADDRESSMODE:
  4305. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  4306. break;
  4307. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  4308. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  4309. break;
  4310. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  4311. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  4312. break;
  4313. }
  4314. }
  4315. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  4316. }
  4317. };
  4318. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  4319. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  4320. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== texture.anisotropicFilteringLevel) {
  4321. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropicFilteringLevel, this._caps.maxAnisotropy));
  4322. texture._cachedAnisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  4323. }
  4324. };
  4325. Engine.prototype.readPixels = function (x, y, width, height) {
  4326. var data = new Uint8Array(height * width * 4);
  4327. this._gl.readPixels(0, 0, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  4328. return data;
  4329. };
  4330. // Dispose
  4331. Engine.prototype.dispose = function () {
  4332. this.hideLoadingUI();
  4333. this.stopRenderLoop();
  4334. while (this.scenes.length) {
  4335. this.scenes[0].dispose();
  4336. }
  4337. for (var name in this._compiledEffects) {
  4338. this._gl.deleteProgram(this._compiledEffects[name]._program);
  4339. }
  4340. for (var i in this._vertexAttribArrays) {
  4341. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  4342. continue;
  4343. }
  4344. this._gl.disableVertexAttribArray(i);
  4345. }
  4346. // Events
  4347. window.removeEventListener("blur", this._onBlur);
  4348. window.removeEventListener("focus", this._onFocus);
  4349. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  4350. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  4351. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  4352. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  4353. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  4354. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  4355. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  4356. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  4357. };
  4358. // Loading screen
  4359. Engine.prototype.displayLoadingUI = function () {
  4360. var _this = this;
  4361. this._loadingDiv = document.createElement("div");
  4362. this._loadingDiv.style.opacity = "0";
  4363. this._loadingDiv.style.transition = "opacity 1.5s ease";
  4364. // Loading text
  4365. this._loadingTextDiv = document.createElement("div");
  4366. this._loadingTextDiv.style.position = "absolute";
  4367. this._loadingTextDiv.style.left = "0";
  4368. this._loadingTextDiv.style.top = "50%";
  4369. this._loadingTextDiv.style.marginTop = "80px";
  4370. this._loadingTextDiv.style.width = "100%";
  4371. this._loadingTextDiv.style.height = "20px";
  4372. this._loadingTextDiv.style.fontFamily = "Arial";
  4373. this._loadingTextDiv.style.fontSize = "14px";
  4374. this._loadingTextDiv.style.color = "white";
  4375. this._loadingTextDiv.style.textAlign = "center";
  4376. this._loadingTextDiv.innerHTML = "Loading";
  4377. this._loadingDiv.appendChild(this._loadingTextDiv);
  4378. // Loading img
  4379. var imgBack = new Image();
  4380. 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==";
  4381. imgBack.style.position = "absolute";
  4382. imgBack.style.left = "50%";
  4383. imgBack.style.top = "50%";
  4384. imgBack.style.marginLeft = "-50px";
  4385. imgBack.style.marginTop = "-50px";
  4386. imgBack.style.transition = "transform 1.0s ease";
  4387. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  4388. var deg = 360;
  4389. var onTransitionEnd = function () {
  4390. deg += 360;
  4391. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  4392. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  4393. };
  4394. imgBack.addEventListener("transitionend", onTransitionEnd);
  4395. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  4396. this._loadingDiv.appendChild(imgBack);
  4397. // front image
  4398. var imgFront = new Image();
  4399. 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=";
  4400. imgFront.style.position = "absolute";
  4401. imgFront.style.left = "50%";
  4402. imgFront.style.top = "50%";
  4403. imgFront.style.marginLeft = "-50px";
  4404. imgFront.style.marginTop = "-50px";
  4405. this._loadingDiv.appendChild(imgFront);
  4406. // Resize
  4407. this._resizeLoadingUI = function () {
  4408. var canvasRect = _this.getRenderingCanvasClientRect();
  4409. _this._loadingDiv.style.position = "absolute";
  4410. _this._loadingDiv.style.left = canvasRect.left + "px";
  4411. _this._loadingDiv.style.top = canvasRect.top + "px";
  4412. _this._loadingDiv.style.width = canvasRect.width + "px";
  4413. _this._loadingDiv.style.height = canvasRect.height + "px";
  4414. };
  4415. this._resizeLoadingUI();
  4416. window.addEventListener("resize", this._resizeLoadingUI);
  4417. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  4418. document.body.appendChild(this._loadingDiv);
  4419. setTimeout(function () {
  4420. _this._loadingDiv.style.opacity = "1";
  4421. imgBack.style.transform = "rotateZ(360deg)";
  4422. imgBack.style.webkitTransform = "rotateZ(360deg)";
  4423. }, 0);
  4424. };
  4425. Object.defineProperty(Engine.prototype, "loadingUIText", {
  4426. set: function (text) {
  4427. if (!this._loadingDiv) {
  4428. return;
  4429. }
  4430. this._loadingTextDiv.innerHTML = text;
  4431. },
  4432. enumerable: true,
  4433. configurable: true
  4434. });
  4435. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  4436. get: function () {
  4437. return this._loadingDivBackgroundColor;
  4438. },
  4439. set: function (color) {
  4440. this._loadingDivBackgroundColor = color;
  4441. if (!this._loadingDiv) {
  4442. return;
  4443. }
  4444. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  4445. },
  4446. enumerable: true,
  4447. configurable: true
  4448. });
  4449. Engine.prototype.hideLoadingUI = function () {
  4450. var _this = this;
  4451. if (!this._loadingDiv) {
  4452. return;
  4453. }
  4454. var onTransitionEnd = function () {
  4455. if (!_this._loadingDiv) {
  4456. return;
  4457. }
  4458. document.body.removeChild(_this._loadingDiv);
  4459. window.removeEventListener("resize", _this._resizeLoadingUI);
  4460. _this._loadingDiv = null;
  4461. };
  4462. this._loadingDiv.style.opacity = "0";
  4463. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  4464. };
  4465. // FPS
  4466. Engine.prototype.getFps = function () {
  4467. return this.fps;
  4468. };
  4469. Engine.prototype.getDeltaTime = function () {
  4470. return this.deltaTime;
  4471. };
  4472. Engine.prototype._measureFps = function () {
  4473. this.previousFramesDuration.push(BABYLON.Tools.Now);
  4474. var length = this.previousFramesDuration.length;
  4475. if (length >= 2) {
  4476. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  4477. }
  4478. if (length >= this.fpsRange) {
  4479. if (length > this.fpsRange) {
  4480. this.previousFramesDuration.splice(0, 1);
  4481. length = this.previousFramesDuration.length;
  4482. }
  4483. var sum = 0;
  4484. for (var id = 0; id < length - 1; id++) {
  4485. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  4486. }
  4487. this.fps = 1000.0 / (sum / (length - 1));
  4488. }
  4489. };
  4490. // Statics
  4491. Engine.isSupported = function () {
  4492. try {
  4493. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  4494. if (navigator.isCocoonJS) {
  4495. return true;
  4496. }
  4497. var tempcanvas = document.createElement("canvas");
  4498. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  4499. return gl != null && !!window.WebGLRenderingContext;
  4500. } catch (e) {
  4501. return false;
  4502. }
  4503. };
  4504. Engine._ALPHA_DISABLE = 0;
  4505. Engine._ALPHA_ADD = 1;
  4506. Engine._ALPHA_COMBINE = 2;
  4507. Engine._DELAYLOADSTATE_NONE = 0;
  4508. Engine._DELAYLOADSTATE_LOADED = 1;
  4509. Engine._DELAYLOADSTATE_LOADING = 2;
  4510. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  4511. Engine._TEXTUREFORMAT_ALPHA = 0;
  4512. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  4513. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  4514. Engine._TEXTUREFORMAT_RGB = 4;
  4515. Engine._TEXTUREFORMAT_RGBA = 4;
  4516. Engine.Epsilon = 0.001;
  4517. Engine.CollisionsEpsilon = 0.001;
  4518. Engine.ShadersRepository = "Babylon/Shaders/";
  4519. return Engine;
  4520. })();
  4521. BABYLON.Engine = Engine;
  4522. })(BABYLON || (BABYLON = {}));
  4523. //# sourceMappingURL=babylon.engine.js.map
  4524. var BABYLON;
  4525. (function (BABYLON) {
  4526. var Node = (function () {
  4527. function Node(name, scene) {
  4528. this.state = "";
  4529. this.animations = new Array();
  4530. this._childrenFlag = -1;
  4531. this._isEnabled = true;
  4532. this._isReady = true;
  4533. this._currentRenderId = -1;
  4534. this.name = name;
  4535. this.id = name;
  4536. this._scene = scene;
  4537. this._initCache();
  4538. }
  4539. Node.prototype.getScene = function () {
  4540. return this._scene;
  4541. };
  4542. Node.prototype.getEngine = function () {
  4543. return this._scene.getEngine();
  4544. };
  4545. // override it in derived class
  4546. Node.prototype.getWorldMatrix = function () {
  4547. return BABYLON.Matrix.Identity();
  4548. };
  4549. // override it in derived class if you add new variables to the cache
  4550. // and call the parent class method
  4551. Node.prototype._initCache = function () {
  4552. this._cache = {};
  4553. this._cache.parent = undefined;
  4554. };
  4555. Node.prototype.updateCache = function (force) {
  4556. if (!force && this.isSynchronized())
  4557. return;
  4558. this._cache.parent = this.parent;
  4559. this._updateCache();
  4560. };
  4561. // override it in derived class if you add new variables to the cache
  4562. // and call the parent class method if !ignoreParentClass
  4563. Node.prototype._updateCache = function (ignoreParentClass) {
  4564. };
  4565. // override it in derived class if you add new variables to the cache
  4566. Node.prototype._isSynchronized = function () {
  4567. return true;
  4568. };
  4569. Node.prototype.isSynchronizedWithParent = function () {
  4570. return this.parent ? this.parent._currentRenderId <= this._currentRenderId : true;
  4571. };
  4572. Node.prototype.isSynchronized = function (updateCache) {
  4573. var check = this.hasNewParent();
  4574. check = check || !this.isSynchronizedWithParent();
  4575. check = check || !this._isSynchronized();
  4576. if (updateCache)
  4577. this.updateCache(true);
  4578. return !check;
  4579. };
  4580. Node.prototype.hasNewParent = function (update) {
  4581. if (this._cache.parent === this.parent)
  4582. return false;
  4583. if (update)
  4584. this._cache.parent = this.parent;
  4585. return true;
  4586. };
  4587. Node.prototype.isReady = function () {
  4588. return this._isReady;
  4589. };
  4590. Node.prototype.isEnabled = function () {
  4591. if (!this._isEnabled) {
  4592. return false;
  4593. }
  4594. if (this.parent) {
  4595. return this.parent.isEnabled();
  4596. }
  4597. return true;
  4598. };
  4599. Node.prototype.setEnabled = function (value) {
  4600. this._isEnabled = value;
  4601. };
  4602. Node.prototype.isDescendantOf = function (ancestor) {
  4603. if (this.parent) {
  4604. if (this.parent === ancestor) {
  4605. return true;
  4606. }
  4607. return this.parent.isDescendantOf(ancestor);
  4608. }
  4609. return false;
  4610. };
  4611. Node.prototype._getDescendants = function (list, results) {
  4612. for (var index = 0; index < list.length; index++) {
  4613. var item = list[index];
  4614. if (item.isDescendantOf(this)) {
  4615. results.push(item);
  4616. }
  4617. }
  4618. };
  4619. Node.prototype.getDescendants = function () {
  4620. var results = [];
  4621. this._getDescendants(this._scene.meshes, results);
  4622. this._getDescendants(this._scene.lights, results);
  4623. this._getDescendants(this._scene.cameras, results);
  4624. return results;
  4625. };
  4626. Node.prototype._setReady = function (state) {
  4627. if (state == this._isReady) {
  4628. return;
  4629. }
  4630. if (!state) {
  4631. this._isReady = false;
  4632. return;
  4633. }
  4634. this._isReady = true;
  4635. if (this.onReady) {
  4636. this.onReady(this);
  4637. }
  4638. };
  4639. return Node;
  4640. })();
  4641. BABYLON.Node = Node;
  4642. })(BABYLON || (BABYLON = {}));
  4643. //# sourceMappingURL=babylon.node.js.map
  4644. var BABYLON;
  4645. (function (BABYLON) {
  4646. var BoundingSphere = (function () {
  4647. function BoundingSphere(minimum, maximum) {
  4648. this.minimum = minimum;
  4649. this.maximum = maximum;
  4650. this._tempRadiusVector = BABYLON.Vector3.Zero();
  4651. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  4652. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  4653. this.radius = distance * 0.5;
  4654. this.centerWorld = BABYLON.Vector3.Zero();
  4655. this._update(BABYLON.Matrix.Identity());
  4656. }
  4657. // Methods
  4658. BoundingSphere.prototype._update = function (world) {
  4659. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  4660. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  4661. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  4662. };
  4663. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  4664. for (var i = 0; i < 6; i++) {
  4665. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  4666. return false;
  4667. }
  4668. return true;
  4669. };
  4670. BoundingSphere.prototype.intersectsPoint = function (point) {
  4671. var x = this.centerWorld.x - point.x;
  4672. var y = this.centerWorld.y - point.y;
  4673. var z = this.centerWorld.z - point.z;
  4674. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  4675. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  4676. return false;
  4677. return true;
  4678. };
  4679. // Statics
  4680. BoundingSphere.Intersects = function (sphere0, sphere1) {
  4681. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  4682. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  4683. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  4684. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  4685. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  4686. return false;
  4687. return true;
  4688. };
  4689. return BoundingSphere;
  4690. })();
  4691. BABYLON.BoundingSphere = BoundingSphere;
  4692. })(BABYLON || (BABYLON = {}));
  4693. //# sourceMappingURL=babylon.boundingSphere.js.map
  4694. var BABYLON;
  4695. (function (BABYLON) {
  4696. var BoundingBox = (function () {
  4697. function BoundingBox(minimum, maximum) {
  4698. this.minimum = minimum;
  4699. this.maximum = maximum;
  4700. this.vectors = new Array();
  4701. this.vectorsWorld = new Array();
  4702. // Bounding vectors
  4703. this.vectors.push(this.minimum.clone());
  4704. this.vectors.push(this.maximum.clone());
  4705. this.vectors.push(this.minimum.clone());
  4706. this.vectors[2].x = this.maximum.x;
  4707. this.vectors.push(this.minimum.clone());
  4708. this.vectors[3].y = this.maximum.y;
  4709. this.vectors.push(this.minimum.clone());
  4710. this.vectors[4].z = this.maximum.z;
  4711. this.vectors.push(this.maximum.clone());
  4712. this.vectors[5].z = this.minimum.z;
  4713. this.vectors.push(this.maximum.clone());
  4714. this.vectors[6].x = this.minimum.x;
  4715. this.vectors.push(this.maximum.clone());
  4716. this.vectors[7].y = this.minimum.y;
  4717. // OBB
  4718. this.center = this.maximum.add(this.minimum).scale(0.5);
  4719. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  4720. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  4721. for (var index = 0; index < this.vectors.length; index++) {
  4722. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  4723. }
  4724. this.minimumWorld = BABYLON.Vector3.Zero();
  4725. this.maximumWorld = BABYLON.Vector3.Zero();
  4726. this._update(BABYLON.Matrix.Identity());
  4727. }
  4728. // Methods
  4729. BoundingBox.prototype.getWorldMatrix = function () {
  4730. return this._worldMatrix;
  4731. };
  4732. BoundingBox.prototype._update = function (world) {
  4733. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  4734. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  4735. for (var index = 0; index < this.vectors.length; index++) {
  4736. var v = this.vectorsWorld[index];
  4737. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  4738. if (v.x < this.minimumWorld.x)
  4739. this.minimumWorld.x = v.x;
  4740. if (v.y < this.minimumWorld.y)
  4741. this.minimumWorld.y = v.y;
  4742. if (v.z < this.minimumWorld.z)
  4743. this.minimumWorld.z = v.z;
  4744. if (v.x > this.maximumWorld.x)
  4745. this.maximumWorld.x = v.x;
  4746. if (v.y > this.maximumWorld.y)
  4747. this.maximumWorld.y = v.y;
  4748. if (v.z > this.maximumWorld.z)
  4749. this.maximumWorld.z = v.z;
  4750. }
  4751. // OBB
  4752. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  4753. this.center.scaleInPlace(0.5);
  4754. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  4755. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  4756. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  4757. this._worldMatrix = world;
  4758. };
  4759. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  4760. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  4761. };
  4762. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  4763. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  4764. };
  4765. BoundingBox.prototype.intersectsPoint = function (point) {
  4766. var delta = BABYLON.Engine.Epsilon;
  4767. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  4768. return false;
  4769. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  4770. return false;
  4771. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  4772. return false;
  4773. return true;
  4774. };
  4775. BoundingBox.prototype.intersectsSphere = function (sphere) {
  4776. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  4777. };
  4778. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  4779. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  4780. return false;
  4781. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  4782. return false;
  4783. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  4784. return false;
  4785. return true;
  4786. };
  4787. // Statics
  4788. BoundingBox.Intersects = function (box0, box1) {
  4789. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  4790. return false;
  4791. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  4792. return false;
  4793. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  4794. return false;
  4795. return true;
  4796. };
  4797. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  4798. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  4799. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  4800. return (num <= (sphereRadius * sphereRadius));
  4801. };
  4802. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  4803. for (var p = 0; p < 6; p++) {
  4804. for (var i = 0; i < 8; i++) {
  4805. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  4806. return false;
  4807. }
  4808. }
  4809. }
  4810. return true;
  4811. };
  4812. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  4813. for (var p = 0; p < 6; p++) {
  4814. var inCount = 8;
  4815. for (var i = 0; i < 8; i++) {
  4816. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  4817. --inCount;
  4818. } else {
  4819. break;
  4820. }
  4821. }
  4822. if (inCount == 0)
  4823. return false;
  4824. }
  4825. return true;
  4826. };
  4827. return BoundingBox;
  4828. })();
  4829. BABYLON.BoundingBox = BoundingBox;
  4830. })(BABYLON || (BABYLON = {}));
  4831. //# sourceMappingURL=babylon.boundingBox.js.map
  4832. var BABYLON;
  4833. (function (BABYLON) {
  4834. var computeBoxExtents = function (axis, box) {
  4835. var p = BABYLON.Vector3.Dot(box.center, axis);
  4836. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  4837. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  4838. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  4839. var r = r0 + r1 + r2;
  4840. return {
  4841. min: p - r,
  4842. max: p + r
  4843. };
  4844. };
  4845. var extentsOverlap = function (min0, max0, min1, max1) {
  4846. return !(min0 > max1 || min1 > max0);
  4847. };
  4848. var axisOverlap = function (axis, box0, box1) {
  4849. var result0 = computeBoxExtents(axis, box0);
  4850. var result1 = computeBoxExtents(axis, box1);
  4851. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  4852. };
  4853. var BoundingInfo = (function () {
  4854. function BoundingInfo(minimum, maximum) {
  4855. this.minimum = minimum;
  4856. this.maximum = maximum;
  4857. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  4858. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  4859. }
  4860. // Methods
  4861. BoundingInfo.prototype._update = function (world) {
  4862. this.boundingBox._update(world);
  4863. this.boundingSphere._update(world);
  4864. };
  4865. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  4866. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  4867. return false;
  4868. return this.boundingBox.isInFrustum(frustumPlanes);
  4869. };
  4870. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  4871. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  4872. };
  4873. BoundingInfo.prototype._checkCollision = function (collider) {
  4874. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  4875. };
  4876. BoundingInfo.prototype.intersectsPoint = function (point) {
  4877. if (!this.boundingSphere.centerWorld) {
  4878. return false;
  4879. }
  4880. if (!this.boundingSphere.intersectsPoint(point)) {
  4881. return false;
  4882. }
  4883. if (!this.boundingBox.intersectsPoint(point)) {
  4884. return false;
  4885. }
  4886. return true;
  4887. };
  4888. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  4889. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  4890. return false;
  4891. }
  4892. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  4893. return false;
  4894. }
  4895. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  4896. return false;
  4897. }
  4898. if (!precise) {
  4899. return true;
  4900. }
  4901. var box0 = this.boundingBox;
  4902. var box1 = boundingInfo.boundingBox;
  4903. if (!axisOverlap(box0.directions[0], box0, box1))
  4904. return false;
  4905. if (!axisOverlap(box0.directions[1], box0, box1))
  4906. return false;
  4907. if (!axisOverlap(box0.directions[2], box0, box1))
  4908. return false;
  4909. if (!axisOverlap(box1.directions[0], box0, box1))
  4910. return false;
  4911. if (!axisOverlap(box1.directions[1], box0, box1))
  4912. return false;
  4913. if (!axisOverlap(box1.directions[2], box0, box1))
  4914. return false;
  4915. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  4916. return false;
  4917. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  4918. return false;
  4919. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  4920. return false;
  4921. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  4922. return false;
  4923. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  4924. return false;
  4925. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  4926. return false;
  4927. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  4928. return false;
  4929. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  4930. return false;
  4931. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  4932. return false;
  4933. return true;
  4934. };
  4935. return BoundingInfo;
  4936. })();
  4937. BABYLON.BoundingInfo = BoundingInfo;
  4938. })(BABYLON || (BABYLON = {}));
  4939. //# sourceMappingURL=babylon.boundingInfo.js.map
  4940. var BABYLON;
  4941. (function (BABYLON) {
  4942. var Light = (function (_super) {
  4943. __extends(Light, _super);
  4944. function Light(name, scene) {
  4945. _super.call(this, name, scene);
  4946. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  4947. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  4948. this.intensity = 1.0;
  4949. this.range = Number.MAX_VALUE;
  4950. this.includedOnlyMeshes = new Array();
  4951. this.excludedMeshes = new Array();
  4952. this._excludedMeshesIds = new Array();
  4953. this._includedOnlyMeshesIds = new Array();
  4954. scene.lights.push(this);
  4955. }
  4956. Light.prototype.getShadowGenerator = function () {
  4957. return this._shadowGenerator;
  4958. };
  4959. Light.prototype.getAbsolutePosition = function () {
  4960. return BABYLON.Vector3.Zero();
  4961. };
  4962. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  4963. };
  4964. Light.prototype._getWorldMatrix = function () {
  4965. return BABYLON.Matrix.Identity();
  4966. };
  4967. Light.prototype.canAffectMesh = function (mesh) {
  4968. if (!mesh) {
  4969. return true;
  4970. }
  4971. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  4972. return false;
  4973. }
  4974. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  4975. return false;
  4976. }
  4977. return true;
  4978. };
  4979. Light.prototype.getWorldMatrix = function () {
  4980. this._currentRenderId = this.getScene().getRenderId();
  4981. var worldMatrix = this._getWorldMatrix();
  4982. if (this.parent && this.parent.getWorldMatrix) {
  4983. if (!this._parentedWorldMatrix) {
  4984. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  4985. }
  4986. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  4987. return this._parentedWorldMatrix;
  4988. }
  4989. return worldMatrix;
  4990. };
  4991. Light.prototype.dispose = function () {
  4992. if (this._shadowGenerator) {
  4993. this._shadowGenerator.dispose();
  4994. this._shadowGenerator = null;
  4995. }
  4996. // Remove from scene
  4997. var index = this.getScene().lights.indexOf(this);
  4998. this.getScene().lights.splice(index, 1);
  4999. };
  5000. return Light;
  5001. })(BABYLON.Node);
  5002. BABYLON.Light = Light;
  5003. })(BABYLON || (BABYLON = {}));
  5004. //# sourceMappingURL=babylon.light.js.map
  5005. var BABYLON;
  5006. (function (BABYLON) {
  5007. var PointLight = (function (_super) {
  5008. __extends(PointLight, _super);
  5009. function PointLight(name, position, scene) {
  5010. _super.call(this, name, scene);
  5011. this.position = position;
  5012. }
  5013. PointLight.prototype.getAbsolutePosition = function () {
  5014. return this._transformedPosition ? this._transformedPosition : this.position;
  5015. };
  5016. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  5017. if (this.parent && this.parent.getWorldMatrix) {
  5018. if (!this._transformedPosition) {
  5019. this._transformedPosition = BABYLON.Vector3.Zero();
  5020. }
  5021. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  5022. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, 0);
  5023. return;
  5024. }
  5025. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  5026. };
  5027. PointLight.prototype.getShadowGenerator = function () {
  5028. return null;
  5029. };
  5030. PointLight.prototype._getWorldMatrix = function () {
  5031. if (!this._worldMatrix) {
  5032. this._worldMatrix = BABYLON.Matrix.Identity();
  5033. }
  5034. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  5035. return this._worldMatrix;
  5036. };
  5037. return PointLight;
  5038. })(BABYLON.Light);
  5039. BABYLON.PointLight = PointLight;
  5040. })(BABYLON || (BABYLON = {}));
  5041. //# sourceMappingURL=babylon.pointLight.js.map
  5042. var BABYLON;
  5043. (function (BABYLON) {
  5044. var SpotLight = (function (_super) {
  5045. __extends(SpotLight, _super);
  5046. function SpotLight(name, position, direction, angle, exponent, scene) {
  5047. _super.call(this, name, scene);
  5048. this.position = position;
  5049. this.direction = direction;
  5050. this.angle = angle;
  5051. this.exponent = exponent;
  5052. }
  5053. SpotLight.prototype.getAbsolutePosition = function () {
  5054. return this._transformedPosition ? this._transformedPosition : this.position;
  5055. };
  5056. SpotLight.prototype.setDirectionToTarget = function (target) {
  5057. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  5058. return this.direction;
  5059. };
  5060. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  5061. var normalizeDirection;
  5062. if (this.parent && this.parent.getWorldMatrix) {
  5063. if (!this._transformedDirection) {
  5064. this._transformedDirection = BABYLON.Vector3.Zero();
  5065. }
  5066. if (!this._transformedPosition) {
  5067. this._transformedPosition = BABYLON.Vector3.Zero();
  5068. }
  5069. var parentWorldMatrix = this.parent.getWorldMatrix();
  5070. BABYLON.Vector3.TransformCoordinatesToRef(this.position, parentWorldMatrix, this._transformedPosition);
  5071. BABYLON.Vector3.TransformNormalToRef(this.direction, parentWorldMatrix, this._transformedDirection);
  5072. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, this.exponent);
  5073. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  5074. } else {
  5075. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  5076. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  5077. }
  5078. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  5079. };
  5080. SpotLight.prototype._getWorldMatrix = function () {
  5081. if (!this._worldMatrix) {
  5082. this._worldMatrix = BABYLON.Matrix.Identity();
  5083. }
  5084. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  5085. return this._worldMatrix;
  5086. };
  5087. return SpotLight;
  5088. })(BABYLON.Light);
  5089. BABYLON.SpotLight = SpotLight;
  5090. })(BABYLON || (BABYLON = {}));
  5091. //# sourceMappingURL=babylon.spotLight.js.map
  5092. var BABYLON;
  5093. (function (BABYLON) {
  5094. var DirectionalLight = (function (_super) {
  5095. __extends(DirectionalLight, _super);
  5096. function DirectionalLight(name, direction, scene) {
  5097. _super.call(this, name, scene);
  5098. this.direction = direction;
  5099. this.position = direction.scale(-1);
  5100. }
  5101. DirectionalLight.prototype.getAbsolutePosition = function () {
  5102. return this._transformedPosition ? this._transformedPosition : this.position;
  5103. };
  5104. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  5105. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  5106. return this.direction;
  5107. };
  5108. DirectionalLight.prototype._computeTransformedPosition = function () {
  5109. if (this.parent && this.parent.getWorldMatrix) {
  5110. if (!this._transformedPosition) {
  5111. this._transformedPosition = BABYLON.Vector3.Zero();
  5112. }
  5113. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  5114. return true;
  5115. }
  5116. return false;
  5117. };
  5118. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  5119. if (this.parent && this.parent.getWorldMatrix) {
  5120. if (!this._transformedDirection) {
  5121. this._transformedDirection = BABYLON.Vector3.Zero();
  5122. }
  5123. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  5124. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  5125. return;
  5126. }
  5127. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  5128. };
  5129. DirectionalLight.prototype._getWorldMatrix = function () {
  5130. if (!this._worldMatrix) {
  5131. this._worldMatrix = BABYLON.Matrix.Identity();
  5132. }
  5133. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  5134. return this._worldMatrix;
  5135. };
  5136. return DirectionalLight;
  5137. })(BABYLON.Light);
  5138. BABYLON.DirectionalLight = DirectionalLight;
  5139. })(BABYLON || (BABYLON = {}));
  5140. //# sourceMappingURL=babylon.directionalLight.js.map
  5141. var BABYLON;
  5142. (function (BABYLON) {
  5143. var ShadowGenerator = (function () {
  5144. function ShadowGenerator(mapSize, light) {
  5145. var _this = this;
  5146. // Members
  5147. this.filter = ShadowGenerator.FILTER_VARIANCESHADOWMAP;
  5148. this._darkness = 0;
  5149. this._transparencyShadow = false;
  5150. this._viewMatrix = BABYLON.Matrix.Zero();
  5151. this._projectionMatrix = BABYLON.Matrix.Zero();
  5152. this._transformMatrix = BABYLON.Matrix.Zero();
  5153. this._worldViewProjection = BABYLON.Matrix.Zero();
  5154. this._light = light;
  5155. this._scene = light.getScene();
  5156. light._shadowGenerator = this;
  5157. // Render target
  5158. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false);
  5159. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  5160. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  5161. this._shadowMap.renderParticles = false;
  5162. // Custom render function
  5163. var renderSubMesh = function (subMesh) {
  5164. var mesh = subMesh.getRenderingMesh();
  5165. var scene = _this._scene;
  5166. var engine = scene.getEngine();
  5167. // Culling
  5168. engine.setState(subMesh.getMaterial().backFaceCulling);
  5169. // Managing instances
  5170. var batch = mesh._getInstancesRenderList(subMesh._id);
  5171. if (batch.mustReturn) {
  5172. return;
  5173. }
  5174. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  5175. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  5176. engine.enableEffect(_this._effect);
  5177. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  5178. var material = subMesh.getMaterial();
  5179. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  5180. // Alpha test
  5181. if (material && material.needAlphaTesting()) {
  5182. var alphaTexture = material.getAlphaTestTexture();
  5183. _this._effect.setTexture("diffuseSampler", alphaTexture);
  5184. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  5185. }
  5186. // Bones
  5187. var useBones = mesh.skeleton && scene.skeletonsEnabled && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  5188. if (useBones) {
  5189. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  5190. }
  5191. if (hardwareInstancedRendering) {
  5192. mesh._renderWithInstances(subMesh, BABYLON.Material.TriangleFillMode, batch, _this._effect, engine);
  5193. } else {
  5194. if (batch.renderSelf[subMesh._id]) {
  5195. _this._effect.setMatrix("world", mesh.getWorldMatrix());
  5196. // Draw
  5197. mesh._draw(subMesh, BABYLON.Material.TriangleFillMode);
  5198. }
  5199. if (batch.visibleInstances[subMesh._id]) {
  5200. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  5201. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  5202. _this._effect.setMatrix("world", instance.getWorldMatrix());
  5203. // Draw
  5204. mesh._draw(subMesh, BABYLON.Material.TriangleFillMode);
  5205. }
  5206. }
  5207. }
  5208. } else {
  5209. // Need to reset refresh rate of the shadowMap
  5210. _this._shadowMap.resetRefreshCounter();
  5211. }
  5212. };
  5213. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  5214. var index;
  5215. for (index = 0; index < opaqueSubMeshes.length; index++) {
  5216. renderSubMesh(opaqueSubMeshes.data[index]);
  5217. }
  5218. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  5219. renderSubMesh(alphaTestSubMeshes.data[index]);
  5220. }
  5221. if (_this._transparencyShadow) {
  5222. for (index = 0; index < transparentSubMeshes.length; index++) {
  5223. renderSubMesh(transparentSubMeshes.data[index]);
  5224. }
  5225. }
  5226. };
  5227. }
  5228. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  5229. // Static
  5230. get: function () {
  5231. return ShadowGenerator._FILTER_NONE;
  5232. },
  5233. enumerable: true,
  5234. configurable: true
  5235. });
  5236. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  5237. get: function () {
  5238. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  5239. },
  5240. enumerable: true,
  5241. configurable: true
  5242. });
  5243. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  5244. get: function () {
  5245. return ShadowGenerator._FILTER_POISSONSAMPLING;
  5246. },
  5247. enumerable: true,
  5248. configurable: true
  5249. });
  5250. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  5251. get: function () {
  5252. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP;
  5253. },
  5254. set: function (value) {
  5255. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  5256. },
  5257. enumerable: true,
  5258. configurable: true
  5259. });
  5260. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  5261. get: function () {
  5262. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  5263. },
  5264. set: function (value) {
  5265. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  5266. },
  5267. enumerable: true,
  5268. configurable: true
  5269. });
  5270. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  5271. var defines = [];
  5272. if (this.useVarianceShadowMap) {
  5273. defines.push("#define VSM");
  5274. }
  5275. var attribs = [BABYLON.VertexBuffer.PositionKind];
  5276. var mesh = subMesh.getMesh();
  5277. var scene = mesh.getScene();
  5278. var material = subMesh.getMaterial();
  5279. // Alpha test
  5280. if (material && material.needAlphaTesting()) {
  5281. defines.push("#define ALPHATEST");
  5282. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  5283. attribs.push(BABYLON.VertexBuffer.UVKind);
  5284. defines.push("#define UV1");
  5285. }
  5286. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  5287. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  5288. defines.push("#define UV2");
  5289. }
  5290. }
  5291. // Bones
  5292. if (mesh.skeleton && scene.skeletonsEnabled && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  5293. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  5294. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  5295. defines.push("#define BONES");
  5296. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  5297. }
  5298. // Instances
  5299. if (useInstances) {
  5300. defines.push("#define INSTANCES");
  5301. attribs.push("world0");
  5302. attribs.push("world1");
  5303. attribs.push("world2");
  5304. attribs.push("world3");
  5305. }
  5306. // Get correct effect
  5307. var join = defines.join("\n");
  5308. if (this._cachedDefines != join) {
  5309. this._cachedDefines = join;
  5310. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  5311. }
  5312. return this._effect.isReady();
  5313. };
  5314. ShadowGenerator.prototype.getShadowMap = function () {
  5315. return this._shadowMap;
  5316. };
  5317. ShadowGenerator.prototype.getLight = function () {
  5318. return this._light;
  5319. };
  5320. // Methods
  5321. ShadowGenerator.prototype.getTransformMatrix = function () {
  5322. var lightPosition = this._light.position;
  5323. var lightDirection = this._light.direction;
  5324. if (this._light._computeTransformedPosition()) {
  5325. lightPosition = this._light._transformedPosition;
  5326. }
  5327. if (!this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !lightDirection.equals(this._cachedDirection)) {
  5328. this._cachedPosition = lightPosition.clone();
  5329. this._cachedDirection = lightDirection.clone();
  5330. var activeCamera = this._scene.activeCamera;
  5331. BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  5332. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2.0, 1.0, activeCamera.minZ, activeCamera.maxZ, this._projectionMatrix);
  5333. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  5334. }
  5335. return this._transformMatrix;
  5336. };
  5337. ShadowGenerator.prototype.getDarkness = function () {
  5338. return this._darkness;
  5339. };
  5340. ShadowGenerator.prototype.setDarkness = function (darkness) {
  5341. if (darkness >= 1.0)
  5342. this._darkness = 1.0;
  5343. else if (darkness <= 0.0)
  5344. this._darkness = 0.0;
  5345. else
  5346. this._darkness = darkness;
  5347. };
  5348. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  5349. this._transparencyShadow = hasShadow;
  5350. };
  5351. ShadowGenerator.prototype.dispose = function () {
  5352. this._shadowMap.dispose();
  5353. };
  5354. ShadowGenerator._FILTER_NONE = 0;
  5355. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  5356. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  5357. return ShadowGenerator;
  5358. })();
  5359. BABYLON.ShadowGenerator = ShadowGenerator;
  5360. })(BABYLON || (BABYLON = {}));
  5361. //# sourceMappingURL=babylon.shadowGenerator.js.map
  5362. var BABYLON;
  5363. (function (BABYLON) {
  5364. var HemisphericLight = (function (_super) {
  5365. __extends(HemisphericLight, _super);
  5366. function HemisphericLight(name, direction, scene) {
  5367. _super.call(this, name, scene);
  5368. this.direction = direction;
  5369. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  5370. }
  5371. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  5372. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  5373. return this.direction;
  5374. };
  5375. HemisphericLight.prototype.getShadowGenerator = function () {
  5376. return null;
  5377. };
  5378. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  5379. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  5380. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  5381. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  5382. };
  5383. HemisphericLight.prototype._getWorldMatrix = function () {
  5384. if (!this._worldMatrix) {
  5385. this._worldMatrix = BABYLON.Matrix.Identity();
  5386. }
  5387. return this._worldMatrix;
  5388. };
  5389. return HemisphericLight;
  5390. })(BABYLON.Light);
  5391. BABYLON.HemisphericLight = HemisphericLight;
  5392. })(BABYLON || (BABYLON = {}));
  5393. //# sourceMappingURL=babylon.hemisphericLight.js.map
  5394. var BABYLON;
  5395. (function (BABYLON) {
  5396. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  5397. if (boxMin.x > sphereCenter.x + sphereRadius)
  5398. return false;
  5399. if (sphereCenter.x - sphereRadius > boxMax.x)
  5400. return false;
  5401. if (boxMin.y > sphereCenter.y + sphereRadius)
  5402. return false;
  5403. if (sphereCenter.y - sphereRadius > boxMax.y)
  5404. return false;
  5405. if (boxMin.z > sphereCenter.z + sphereRadius)
  5406. return false;
  5407. if (sphereCenter.z - sphereRadius > boxMax.z)
  5408. return false;
  5409. return true;
  5410. };
  5411. var getLowestRoot = function (a, b, c, maxR) {
  5412. var determinant = b * b - 4.0 * a * c;
  5413. var result = { root: 0, found: false };
  5414. if (determinant < 0)
  5415. return result;
  5416. var sqrtD = Math.sqrt(determinant);
  5417. var r1 = (-b - sqrtD) / (2.0 * a);
  5418. var r2 = (-b + sqrtD) / (2.0 * a);
  5419. if (r1 > r2) {
  5420. var temp = r2;
  5421. r2 = r1;
  5422. r1 = temp;
  5423. }
  5424. if (r1 > 0 && r1 < maxR) {
  5425. result.root = r1;
  5426. result.found = true;
  5427. return result;
  5428. }
  5429. if (r2 > 0 && r2 < maxR) {
  5430. result.root = r2;
  5431. result.found = true;
  5432. return result;
  5433. }
  5434. return result;
  5435. };
  5436. var Collider = (function () {
  5437. function Collider() {
  5438. this.radius = new BABYLON.Vector3(1, 1, 1);
  5439. this.retry = 0;
  5440. this.basePointWorld = BABYLON.Vector3.Zero();
  5441. this.velocityWorld = BABYLON.Vector3.Zero();
  5442. this.normalizedVelocity = BABYLON.Vector3.Zero();
  5443. this._collisionPoint = BABYLON.Vector3.Zero();
  5444. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  5445. this._tempVector = BABYLON.Vector3.Zero();
  5446. this._tempVector2 = BABYLON.Vector3.Zero();
  5447. this._tempVector3 = BABYLON.Vector3.Zero();
  5448. this._tempVector4 = BABYLON.Vector3.Zero();
  5449. this._edge = BABYLON.Vector3.Zero();
  5450. this._baseToVertex = BABYLON.Vector3.Zero();
  5451. this._destinationPoint = BABYLON.Vector3.Zero();
  5452. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  5453. this._displacementVector = BABYLON.Vector3.Zero();
  5454. }
  5455. // Methods
  5456. Collider.prototype._initialize = function (source, dir, e) {
  5457. this.velocity = dir;
  5458. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  5459. this.basePoint = source;
  5460. source.multiplyToRef(this.radius, this.basePointWorld);
  5461. dir.multiplyToRef(this.radius, this.velocityWorld);
  5462. this.velocityWorldLength = this.velocityWorld.length();
  5463. this.epsilon = e;
  5464. this.collisionFound = false;
  5465. };
  5466. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  5467. pa.subtractToRef(point, this._tempVector);
  5468. pb.subtractToRef(point, this._tempVector2);
  5469. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  5470. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  5471. if (d < 0)
  5472. return false;
  5473. pc.subtractToRef(point, this._tempVector3);
  5474. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  5475. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  5476. if (d < 0)
  5477. return false;
  5478. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  5479. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  5480. return d >= 0;
  5481. };
  5482. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  5483. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  5484. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  5485. if (distance > this.velocityWorldLength + max + sphereRadius) {
  5486. return false;
  5487. }
  5488. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  5489. return false;
  5490. return true;
  5491. };
  5492. Collider.prototype._testTriangle = function (faceIndex, subMesh, p1, p2, p3) {
  5493. var t0;
  5494. var embeddedInPlane = false;
  5495. if (!subMesh._trianglePlanes) {
  5496. subMesh._trianglePlanes = [];
  5497. }
  5498. if (!subMesh._trianglePlanes[faceIndex]) {
  5499. subMesh._trianglePlanes[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  5500. subMesh._trianglePlanes[faceIndex].copyFromPoints(p1, p2, p3);
  5501. }
  5502. var trianglePlane = subMesh._trianglePlanes[faceIndex];
  5503. if ((!subMesh.getMaterial()) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  5504. return;
  5505. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  5506. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  5507. if (normalDotVelocity == 0) {
  5508. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  5509. return;
  5510. embeddedInPlane = true;
  5511. t0 = 0;
  5512. } else {
  5513. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  5514. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  5515. if (t0 > t1) {
  5516. var temp = t1;
  5517. t1 = t0;
  5518. t0 = temp;
  5519. }
  5520. if (t0 > 1.0 || t1 < 0.0)
  5521. return;
  5522. if (t0 < 0)
  5523. t0 = 0;
  5524. if (t0 > 1.0)
  5525. t0 = 1.0;
  5526. }
  5527. this._collisionPoint.copyFromFloats(0, 0, 0);
  5528. var found = false;
  5529. var t = 1.0;
  5530. if (!embeddedInPlane) {
  5531. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  5532. this.velocity.scaleToRef(t0, this._tempVector);
  5533. this._planeIntersectionPoint.addInPlace(this._tempVector);
  5534. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  5535. found = true;
  5536. t = t0;
  5537. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  5538. }
  5539. }
  5540. if (!found) {
  5541. var velocitySquaredLength = this.velocity.lengthSquared();
  5542. var a = velocitySquaredLength;
  5543. this.basePoint.subtractToRef(p1, this._tempVector);
  5544. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  5545. var c = this._tempVector.lengthSquared() - 1.0;
  5546. var lowestRoot = getLowestRoot(a, b, c, t);
  5547. if (lowestRoot.found) {
  5548. t = lowestRoot.root;
  5549. found = true;
  5550. this._collisionPoint.copyFrom(p1);
  5551. }
  5552. this.basePoint.subtractToRef(p2, this._tempVector);
  5553. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  5554. c = this._tempVector.lengthSquared() - 1.0;
  5555. lowestRoot = getLowestRoot(a, b, c, t);
  5556. if (lowestRoot.found) {
  5557. t = lowestRoot.root;
  5558. found = true;
  5559. this._collisionPoint.copyFrom(p2);
  5560. }
  5561. this.basePoint.subtractToRef(p3, this._tempVector);
  5562. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  5563. c = this._tempVector.lengthSquared() - 1.0;
  5564. lowestRoot = getLowestRoot(a, b, c, t);
  5565. if (lowestRoot.found) {
  5566. t = lowestRoot.root;
  5567. found = true;
  5568. this._collisionPoint.copyFrom(p3);
  5569. }
  5570. p2.subtractToRef(p1, this._edge);
  5571. p1.subtractToRef(this.basePoint, this._baseToVertex);
  5572. var edgeSquaredLength = this._edge.lengthSquared();
  5573. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  5574. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  5575. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  5576. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  5577. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  5578. lowestRoot = getLowestRoot(a, b, c, t);
  5579. if (lowestRoot.found) {
  5580. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  5581. if (f >= 0.0 && f <= 1.0) {
  5582. t = lowestRoot.root;
  5583. found = true;
  5584. this._edge.scaleInPlace(f);
  5585. p1.addToRef(this._edge, this._collisionPoint);
  5586. }
  5587. }
  5588. p3.subtractToRef(p2, this._edge);
  5589. p2.subtractToRef(this.basePoint, this._baseToVertex);
  5590. edgeSquaredLength = this._edge.lengthSquared();
  5591. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  5592. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  5593. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  5594. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  5595. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  5596. lowestRoot = getLowestRoot(a, b, c, t);
  5597. if (lowestRoot.found) {
  5598. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  5599. if (f >= 0.0 && f <= 1.0) {
  5600. t = lowestRoot.root;
  5601. found = true;
  5602. this._edge.scaleInPlace(f);
  5603. p2.addToRef(this._edge, this._collisionPoint);
  5604. }
  5605. }
  5606. p1.subtractToRef(p3, this._edge);
  5607. p3.subtractToRef(this.basePoint, this._baseToVertex);
  5608. edgeSquaredLength = this._edge.lengthSquared();
  5609. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  5610. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  5611. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  5612. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  5613. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  5614. lowestRoot = getLowestRoot(a, b, c, t);
  5615. if (lowestRoot.found) {
  5616. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  5617. if (f >= 0.0 && f <= 1.0) {
  5618. t = lowestRoot.root;
  5619. found = true;
  5620. this._edge.scaleInPlace(f);
  5621. p3.addToRef(this._edge, this._collisionPoint);
  5622. }
  5623. }
  5624. }
  5625. if (found) {
  5626. var distToCollision = t * this.velocity.length();
  5627. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  5628. if (!this.intersectionPoint) {
  5629. this.intersectionPoint = this._collisionPoint.clone();
  5630. } else {
  5631. this.intersectionPoint.copyFrom(this._collisionPoint);
  5632. }
  5633. this.nearestDistance = distToCollision;
  5634. this.collisionFound = true;
  5635. this.collidedMesh = subMesh.getMesh();
  5636. }
  5637. }
  5638. };
  5639. Collider.prototype._collide = function (subMesh, pts, indices, indexStart, indexEnd, decal) {
  5640. for (var i = indexStart; i < indexEnd; i += 3) {
  5641. var p1 = pts[indices[i] - decal];
  5642. var p2 = pts[indices[i + 1] - decal];
  5643. var p3 = pts[indices[i + 2] - decal];
  5644. this._testTriangle(i, subMesh, p3, p2, p1);
  5645. }
  5646. };
  5647. Collider.prototype._getResponse = function (pos, vel) {
  5648. pos.addToRef(vel, this._destinationPoint);
  5649. vel.scaleInPlace((this.nearestDistance / vel.length()));
  5650. this.basePoint.addToRef(vel, pos);
  5651. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  5652. this._slidePlaneNormal.normalize();
  5653. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  5654. pos.addInPlace(this._displacementVector);
  5655. this.intersectionPoint.addInPlace(this._displacementVector);
  5656. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  5657. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  5658. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  5659. };
  5660. return Collider;
  5661. })();
  5662. BABYLON.Collider = Collider;
  5663. })(BABYLON || (BABYLON = {}));
  5664. //# sourceMappingURL=babylon.collider.js.map
  5665. var BABYLON;
  5666. (function (BABYLON) {
  5667. var Camera = (function (_super) {
  5668. __extends(Camera, _super);
  5669. function Camera(name, position, scene) {
  5670. _super.call(this, name, scene);
  5671. this.position = position;
  5672. // Members
  5673. this.upVector = BABYLON.Vector3.Up();
  5674. this.orthoLeft = null;
  5675. this.orthoRight = null;
  5676. this.orthoBottom = null;
  5677. this.orthoTop = null;
  5678. this.fov = 0.8;
  5679. this.minZ = 1.0;
  5680. this.maxZ = 10000.0;
  5681. this.inertia = 0.9;
  5682. this.mode = Camera.PERSPECTIVE_CAMERA;
  5683. this.isIntermediate = false;
  5684. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  5685. this.subCameras = [];
  5686. this.layerMask = 0xFFFFFFFF;
  5687. this._computedViewMatrix = BABYLON.Matrix.Identity();
  5688. this._projectionMatrix = new BABYLON.Matrix();
  5689. this._postProcesses = new Array();
  5690. this._postProcessesTakenIndices = [];
  5691. scene.cameras.push(this);
  5692. if (!scene.activeCamera) {
  5693. scene.activeCamera = this;
  5694. }
  5695. }
  5696. //Cache
  5697. Camera.prototype._initCache = function () {
  5698. _super.prototype._initCache.call(this);
  5699. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5700. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5701. this._cache.mode = undefined;
  5702. this._cache.minZ = undefined;
  5703. this._cache.maxZ = undefined;
  5704. this._cache.fov = undefined;
  5705. this._cache.aspectRatio = undefined;
  5706. this._cache.orthoLeft = undefined;
  5707. this._cache.orthoRight = undefined;
  5708. this._cache.orthoBottom = undefined;
  5709. this._cache.orthoTop = undefined;
  5710. this._cache.renderWidth = undefined;
  5711. this._cache.renderHeight = undefined;
  5712. };
  5713. Camera.prototype._updateCache = function (ignoreParentClass) {
  5714. if (!ignoreParentClass) {
  5715. _super.prototype._updateCache.call(this);
  5716. }
  5717. var engine = this.getEngine();
  5718. this._cache.position.copyFrom(this.position);
  5719. this._cache.upVector.copyFrom(this.upVector);
  5720. this._cache.mode = this.mode;
  5721. this._cache.minZ = this.minZ;
  5722. this._cache.maxZ = this.maxZ;
  5723. this._cache.fov = this.fov;
  5724. this._cache.aspectRatio = engine.getAspectRatio(this);
  5725. this._cache.orthoLeft = this.orthoLeft;
  5726. this._cache.orthoRight = this.orthoRight;
  5727. this._cache.orthoBottom = this.orthoBottom;
  5728. this._cache.orthoTop = this.orthoTop;
  5729. this._cache.renderWidth = engine.getRenderWidth();
  5730. this._cache.renderHeight = engine.getRenderHeight();
  5731. };
  5732. Camera.prototype._updateFromScene = function () {
  5733. this.updateCache();
  5734. this._update();
  5735. };
  5736. // Synchronized
  5737. Camera.prototype._isSynchronized = function () {
  5738. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  5739. };
  5740. Camera.prototype._isSynchronizedViewMatrix = function () {
  5741. if (!_super.prototype._isSynchronized.call(this))
  5742. return false;
  5743. return this._cache.position.equals(this.position) && this._cache.upVector.equals(this.upVector) && this.isSynchronizedWithParent();
  5744. };
  5745. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  5746. var check = this._cache.mode === this.mode && this._cache.minZ === this.minZ && this._cache.maxZ === this.maxZ;
  5747. if (!check) {
  5748. return false;
  5749. }
  5750. var engine = this.getEngine();
  5751. if (this.mode === BABYLON.Camera.PERSPECTIVE_CAMERA) {
  5752. check = this._cache.fov === this.fov && this._cache.aspectRatio === engine.getAspectRatio(this);
  5753. } else {
  5754. 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();
  5755. }
  5756. return check;
  5757. };
  5758. // Controls
  5759. Camera.prototype.attachControl = function (element) {
  5760. };
  5761. Camera.prototype.detachControl = function (element) {
  5762. };
  5763. Camera.prototype._update = function () {
  5764. };
  5765. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  5766. if (typeof insertAt === "undefined") { insertAt = null; }
  5767. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  5768. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  5769. return 0;
  5770. }
  5771. if (insertAt == null || insertAt < 0) {
  5772. this._postProcesses.push(postProcess);
  5773. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  5774. return this._postProcesses.length - 1;
  5775. }
  5776. var add = 0;
  5777. if (this._postProcesses[insertAt]) {
  5778. var start = this._postProcesses.length - 1;
  5779. for (var i = start; i >= insertAt + 1; --i) {
  5780. this._postProcesses[i + 1] = this._postProcesses[i];
  5781. }
  5782. add = 1;
  5783. }
  5784. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  5785. if (this._postProcessesTakenIndices[i] < insertAt) {
  5786. continue;
  5787. }
  5788. start = this._postProcessesTakenIndices.length - 1;
  5789. for (var j = start; j >= i; --j) {
  5790. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  5791. }
  5792. this._postProcessesTakenIndices[i] = insertAt;
  5793. break;
  5794. }
  5795. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) == -1) {
  5796. this._postProcessesTakenIndices.push(insertAt);
  5797. }
  5798. var result = insertAt + add;
  5799. this._postProcesses[result] = postProcess;
  5800. return result;
  5801. };
  5802. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  5803. if (typeof atIndices === "undefined") { atIndices = null; }
  5804. var result = [];
  5805. if (!atIndices) {
  5806. var length = this._postProcesses.length;
  5807. for (var i = 0; i < length; i++) {
  5808. if (this._postProcesses[i] !== postProcess) {
  5809. continue;
  5810. }
  5811. delete this._postProcesses[i];
  5812. var index = this._postProcessesTakenIndices.indexOf(i);
  5813. this._postProcessesTakenIndices.splice(index, 1);
  5814. }
  5815. } else {
  5816. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  5817. for (i = 0; i < atIndices.length; i++) {
  5818. var foundPostProcess = this._postProcesses[atIndices[i]];
  5819. if (foundPostProcess !== postProcess) {
  5820. result.push(i);
  5821. continue;
  5822. }
  5823. delete this._postProcesses[atIndices[i]];
  5824. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  5825. this._postProcessesTakenIndices.splice(index, 1);
  5826. }
  5827. }
  5828. return result;
  5829. };
  5830. Camera.prototype.getWorldMatrix = function () {
  5831. if (!this._worldMatrix) {
  5832. this._worldMatrix = BABYLON.Matrix.Identity();
  5833. }
  5834. var viewMatrix = this.getViewMatrix();
  5835. viewMatrix.invertToRef(this._worldMatrix);
  5836. return this._worldMatrix;
  5837. };
  5838. Camera.prototype._getViewMatrix = function () {
  5839. return BABYLON.Matrix.Identity();
  5840. };
  5841. Camera.prototype.getViewMatrix = function () {
  5842. this._computedViewMatrix = this._computeViewMatrix();
  5843. if (!this.parent || !this.parent.getWorldMatrix || this.isSynchronized()) {
  5844. return this._computedViewMatrix;
  5845. }
  5846. if (!this._worldMatrix) {
  5847. this._worldMatrix = BABYLON.Matrix.Identity();
  5848. }
  5849. this._computedViewMatrix.invertToRef(this._worldMatrix);
  5850. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  5851. this._computedViewMatrix.invert();
  5852. this._currentRenderId = this.getScene().getRenderId();
  5853. return this._computedViewMatrix;
  5854. };
  5855. Camera.prototype._computeViewMatrix = function (force) {
  5856. if (!force && this._isSynchronizedViewMatrix()) {
  5857. return this._computedViewMatrix;
  5858. }
  5859. this._computedViewMatrix = this._getViewMatrix();
  5860. if (!this.parent || !this.parent.getWorldMatrix) {
  5861. this._currentRenderId = this.getScene().getRenderId();
  5862. }
  5863. return this._computedViewMatrix;
  5864. };
  5865. Camera.prototype.getProjectionMatrix = function (force) {
  5866. if (!force && this._isSynchronizedProjectionMatrix()) {
  5867. return this._projectionMatrix;
  5868. }
  5869. var engine = this.getEngine();
  5870. if (this.mode === BABYLON.Camera.PERSPECTIVE_CAMERA) {
  5871. if (this.minZ <= 0) {
  5872. this.minZ = 0.1;
  5873. }
  5874. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix);
  5875. return this._projectionMatrix;
  5876. }
  5877. var halfWidth = engine.getRenderWidth() / 2.0;
  5878. var halfHeight = engine.getRenderHeight() / 2.0;
  5879. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  5880. return this._projectionMatrix;
  5881. };
  5882. Camera.prototype.dispose = function () {
  5883. // Remove from scene
  5884. var index = this.getScene().cameras.indexOf(this);
  5885. this.getScene().cameras.splice(index, 1);
  5886. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  5887. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  5888. }
  5889. };
  5890. Camera.PERSPECTIVE_CAMERA = 0;
  5891. Camera.ORTHOGRAPHIC_CAMERA = 1;
  5892. return Camera;
  5893. })(BABYLON.Node);
  5894. BABYLON.Camera = Camera;
  5895. })(BABYLON || (BABYLON = {}));
  5896. //# sourceMappingURL=babylon.camera.js.map
  5897. var BABYLON;
  5898. (function (BABYLON) {
  5899. var TargetCamera = (function (_super) {
  5900. __extends(TargetCamera, _super);
  5901. function TargetCamera(name, position, scene) {
  5902. _super.call(this, name, position, scene);
  5903. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  5904. this.cameraRotation = new BABYLON.Vector2(0, 0);
  5905. this.rotation = new BABYLON.Vector3(0, 0, 0);
  5906. this.speed = 2.0;
  5907. this.noRotationConstraint = false;
  5908. this.lockedTarget = null;
  5909. this._currentTarget = BABYLON.Vector3.Zero();
  5910. this._viewMatrix = BABYLON.Matrix.Zero();
  5911. this._camMatrix = BABYLON.Matrix.Zero();
  5912. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  5913. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  5914. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  5915. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  5916. this._lookAtTemp = BABYLON.Matrix.Zero();
  5917. this._tempMatrix = BABYLON.Matrix.Zero();
  5918. }
  5919. TargetCamera.prototype._getLockedTargetPosition = function () {
  5920. if (!this.lockedTarget) {
  5921. return null;
  5922. }
  5923. return this.lockedTarget.position || this.lockedTarget;
  5924. };
  5925. // Cache
  5926. TargetCamera.prototype._initCache = function () {
  5927. _super.prototype._initCache.call(this);
  5928. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5929. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5930. };
  5931. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  5932. if (!ignoreParentClass) {
  5933. _super.prototype._updateCache.call(this);
  5934. }
  5935. var lockedTargetPosition = this._getLockedTargetPosition();
  5936. if (!lockedTargetPosition) {
  5937. this._cache.lockedTarget = null;
  5938. } else {
  5939. if (!this._cache.lockedTarget) {
  5940. this._cache.lockedTarget = lockedTargetPosition.clone();
  5941. } else {
  5942. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  5943. }
  5944. }
  5945. this._cache.rotation.copyFrom(this.rotation);
  5946. };
  5947. // Synchronized
  5948. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  5949. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  5950. return false;
  5951. }
  5952. var lockedTargetPosition = this._getLockedTargetPosition();
  5953. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition) && this._cache.rotation.equals(this.rotation);
  5954. };
  5955. // Methods
  5956. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  5957. var engine = this.getEngine();
  5958. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  5959. };
  5960. // Target
  5961. TargetCamera.prototype.setTarget = function (target) {
  5962. this.upVector.normalize();
  5963. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  5964. this._camMatrix.invert();
  5965. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  5966. var vDir = target.subtract(this.position);
  5967. if (vDir.x >= 0.0) {
  5968. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  5969. } else {
  5970. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  5971. }
  5972. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  5973. if (isNaN(this.rotation.x)) {
  5974. this.rotation.x = 0;
  5975. }
  5976. if (isNaN(this.rotation.y)) {
  5977. this.rotation.y = 0;
  5978. }
  5979. if (isNaN(this.rotation.z)) {
  5980. this.rotation.z = 0;
  5981. }
  5982. };
  5983. TargetCamera.prototype.getTarget = function () {
  5984. return this._currentTarget;
  5985. };
  5986. TargetCamera.prototype._decideIfNeedsToMove = function () {
  5987. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  5988. };
  5989. TargetCamera.prototype._updatePosition = function () {
  5990. this.position.addInPlace(this.cameraDirection);
  5991. };
  5992. TargetCamera.prototype._update = function () {
  5993. var needToMove = this._decideIfNeedsToMove();
  5994. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  5995. // Move
  5996. if (needToMove) {
  5997. this._updatePosition();
  5998. }
  5999. // Rotate
  6000. if (needToRotate) {
  6001. this.rotation.x += this.cameraRotation.x;
  6002. this.rotation.y += this.cameraRotation.y;
  6003. if (!this.noRotationConstraint) {
  6004. var limit = (Math.PI / 2) * 0.95;
  6005. if (this.rotation.x > limit)
  6006. this.rotation.x = limit;
  6007. if (this.rotation.x < -limit)
  6008. this.rotation.x = -limit;
  6009. }
  6010. }
  6011. // Inertia
  6012. if (needToMove) {
  6013. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  6014. this.cameraDirection.x = 0;
  6015. }
  6016. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  6017. this.cameraDirection.y = 0;
  6018. }
  6019. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  6020. this.cameraDirection.z = 0;
  6021. }
  6022. this.cameraDirection.scaleInPlace(this.inertia);
  6023. }
  6024. if (needToRotate) {
  6025. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  6026. this.cameraRotation.x = 0;
  6027. }
  6028. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  6029. this.cameraRotation.y = 0;
  6030. }
  6031. this.cameraRotation.scaleInPlace(this.inertia);
  6032. }
  6033. };
  6034. TargetCamera.prototype._getViewMatrix = function () {
  6035. if (!this.lockedTarget) {
  6036. // Compute
  6037. if (this.upVector.x != 0 || this.upVector.y != 1.0 || this.upVector.z != 0) {
  6038. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  6039. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  6040. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  6041. this._lookAtTemp.invert();
  6042. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  6043. } else {
  6044. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  6045. }
  6046. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  6047. // Computing target and final matrix
  6048. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  6049. } else {
  6050. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  6051. }
  6052. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  6053. return this._viewMatrix;
  6054. };
  6055. return TargetCamera;
  6056. })(BABYLON.Camera);
  6057. BABYLON.TargetCamera = TargetCamera;
  6058. })(BABYLON || (BABYLON = {}));
  6059. //# sourceMappingURL=babylon.targetCamera.js.map
  6060. var BABYLON;
  6061. (function (BABYLON) {
  6062. var FollowCamera = (function (_super) {
  6063. __extends(FollowCamera, _super);
  6064. function FollowCamera(name, position, scene) {
  6065. _super.call(this, name, position, scene);
  6066. this.radius = 12;
  6067. this.rotationOffset = 0;
  6068. this.heightOffset = 4;
  6069. this.cameraAcceleration = 0.05;
  6070. this.maxCameraSpeed = 20;
  6071. }
  6072. FollowCamera.prototype.getRadians = function (degrees) {
  6073. return degrees * Math.PI / 180;
  6074. };
  6075. FollowCamera.prototype.follow = function (cameraTarget) {
  6076. if (!cameraTarget)
  6077. return;
  6078. var radians = this.getRadians(this.rotationOffset) + cameraTarget.rotation.y;
  6079. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  6080. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  6081. var dx = targetX - this.position.x;
  6082. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  6083. var dz = (targetZ) - this.position.z;
  6084. var vx = dx * this.cameraAcceleration * 2;
  6085. var vy = dy * this.cameraAcceleration;
  6086. var vz = dz * this.cameraAcceleration * 2;
  6087. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  6088. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  6089. }
  6090. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  6091. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  6092. }
  6093. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  6094. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  6095. }
  6096. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  6097. this.setTarget(cameraTarget.position);
  6098. };
  6099. FollowCamera.prototype._update = function () {
  6100. _super.prototype._update.call(this);
  6101. this.follow(this.target);
  6102. };
  6103. return FollowCamera;
  6104. })(BABYLON.TargetCamera);
  6105. BABYLON.FollowCamera = FollowCamera;
  6106. })(BABYLON || (BABYLON = {}));
  6107. //# sourceMappingURL=babylon.followCamera.js.map
  6108. var BABYLON;
  6109. (function (BABYLON) {
  6110. var FreeCamera = (function (_super) {
  6111. __extends(FreeCamera, _super);
  6112. function FreeCamera(name, position, scene) {
  6113. _super.call(this, name, position, scene);
  6114. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  6115. this.keysUp = [38];
  6116. this.keysDown = [40];
  6117. this.keysLeft = [37];
  6118. this.keysRight = [39];
  6119. this.checkCollisions = false;
  6120. this.applyGravity = false;
  6121. this.angularSensibility = 2000.0;
  6122. this._keys = [];
  6123. this._collider = new BABYLON.Collider();
  6124. this._needMoveForGravity = true;
  6125. this._oldPosition = BABYLON.Vector3.Zero();
  6126. this._diffPosition = BABYLON.Vector3.Zero();
  6127. this._newPosition = BABYLON.Vector3.Zero();
  6128. }
  6129. // Controls
  6130. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  6131. var _this = this;
  6132. var previousPosition;
  6133. var engine = this.getEngine();
  6134. if (this._attachedElement) {
  6135. return;
  6136. }
  6137. this._attachedElement = element;
  6138. if (this._onMouseDown === undefined) {
  6139. this._onMouseDown = function (evt) {
  6140. previousPosition = {
  6141. x: evt.clientX,
  6142. y: evt.clientY
  6143. };
  6144. if (!noPreventDefault) {
  6145. evt.preventDefault();
  6146. }
  6147. };
  6148. this._onMouseUp = function (evt) {
  6149. previousPosition = null;
  6150. if (!noPreventDefault) {
  6151. evt.preventDefault();
  6152. }
  6153. };
  6154. this._onMouseOut = function (evt) {
  6155. previousPosition = null;
  6156. _this._keys = [];
  6157. if (!noPreventDefault) {
  6158. evt.preventDefault();
  6159. }
  6160. };
  6161. this._onMouseMove = function (evt) {
  6162. if (!previousPosition && !engine.isPointerLock) {
  6163. return;
  6164. }
  6165. var offsetX;
  6166. var offsetY;
  6167. if (!engine.isPointerLock) {
  6168. offsetX = evt.clientX - previousPosition.x;
  6169. offsetY = evt.clientY - previousPosition.y;
  6170. } else {
  6171. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  6172. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  6173. }
  6174. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  6175. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  6176. previousPosition = {
  6177. x: evt.clientX,
  6178. y: evt.clientY
  6179. };
  6180. if (!noPreventDefault) {
  6181. evt.preventDefault();
  6182. }
  6183. };
  6184. this._onKeyDown = function (evt) {
  6185. 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) {
  6186. var index = _this._keys.indexOf(evt.keyCode);
  6187. if (index === -1) {
  6188. _this._keys.push(evt.keyCode);
  6189. }
  6190. if (!noPreventDefault) {
  6191. evt.preventDefault();
  6192. }
  6193. }
  6194. };
  6195. this._onKeyUp = function (evt) {
  6196. 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) {
  6197. var index = _this._keys.indexOf(evt.keyCode);
  6198. if (index >= 0) {
  6199. _this._keys.splice(index, 1);
  6200. }
  6201. if (!noPreventDefault) {
  6202. evt.preventDefault();
  6203. }
  6204. }
  6205. };
  6206. this._onLostFocus = function () {
  6207. _this._keys = [];
  6208. };
  6209. this._reset = function () {
  6210. _this._keys = [];
  6211. previousPosition = null;
  6212. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  6213. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  6214. };
  6215. }
  6216. element.addEventListener("mousedown", this._onMouseDown, false);
  6217. element.addEventListener("mouseup", this._onMouseUp, false);
  6218. element.addEventListener("mouseout", this._onMouseOut, false);
  6219. element.addEventListener("mousemove", this._onMouseMove, false);
  6220. BABYLON.Tools.RegisterTopRootEvents([
  6221. { name: "keydown", handler: this._onKeyDown },
  6222. { name: "keyup", handler: this._onKeyUp },
  6223. { name: "blur", handler: this._onLostFocus }
  6224. ]);
  6225. };
  6226. FreeCamera.prototype.detachControl = function (element) {
  6227. if (this._attachedElement != element) {
  6228. return;
  6229. }
  6230. element.removeEventListener("mousedown", this._onMouseDown);
  6231. element.removeEventListener("mouseup", this._onMouseUp);
  6232. element.removeEventListener("mouseout", this._onMouseOut);
  6233. element.removeEventListener("mousemove", this._onMouseMove);
  6234. BABYLON.Tools.UnregisterTopRootEvents([
  6235. { name: "keydown", handler: this._onKeyDown },
  6236. { name: "keyup", handler: this._onKeyUp },
  6237. { name: "blur", handler: this._onLostFocus }
  6238. ]);
  6239. this._attachedElement = null;
  6240. if (this._reset) {
  6241. this._reset();
  6242. }
  6243. };
  6244. FreeCamera.prototype._collideWithWorld = function (velocity) {
  6245. var globalPosition;
  6246. if (this.parent) {
  6247. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  6248. } else {
  6249. globalPosition = this.position;
  6250. }
  6251. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  6252. this._collider.radius = this.ellipsoid;
  6253. this.getScene()._getNewPosition(this._oldPosition, velocity, this._collider, 3, this._newPosition);
  6254. this._newPosition.subtractToRef(this._oldPosition, this._diffPosition);
  6255. if (this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  6256. this.position.addInPlace(this._diffPosition);
  6257. if (this.onCollide) {
  6258. this.onCollide(this._collider.collidedMesh);
  6259. }
  6260. }
  6261. };
  6262. FreeCamera.prototype._checkInputs = function () {
  6263. if (!this._localDirection) {
  6264. this._localDirection = BABYLON.Vector3.Zero();
  6265. this._transformedDirection = BABYLON.Vector3.Zero();
  6266. }
  6267. for (var index = 0; index < this._keys.length; index++) {
  6268. var keyCode = this._keys[index];
  6269. var speed = this._computeLocalCameraSpeed();
  6270. if (this.keysLeft.indexOf(keyCode) !== -1) {
  6271. this._localDirection.copyFromFloats(-speed, 0, 0);
  6272. } else if (this.keysUp.indexOf(keyCode) !== -1) {
  6273. this._localDirection.copyFromFloats(0, 0, speed);
  6274. } else if (this.keysRight.indexOf(keyCode) !== -1) {
  6275. this._localDirection.copyFromFloats(speed, 0, 0);
  6276. } else if (this.keysDown.indexOf(keyCode) !== -1) {
  6277. this._localDirection.copyFromFloats(0, 0, -speed);
  6278. }
  6279. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  6280. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  6281. this.cameraDirection.addInPlace(this._transformedDirection);
  6282. }
  6283. };
  6284. FreeCamera.prototype._decideIfNeedsToMove = function () {
  6285. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  6286. };
  6287. FreeCamera.prototype._updatePosition = function () {
  6288. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  6289. this._collideWithWorld(this.cameraDirection);
  6290. if (this.applyGravity) {
  6291. var oldPosition = this.position;
  6292. this._collideWithWorld(this.getScene().gravity);
  6293. this._needMoveForGravity = (BABYLON.Vector3.DistanceSquared(oldPosition, this.position) != 0);
  6294. }
  6295. } else {
  6296. this.position.addInPlace(this.cameraDirection);
  6297. }
  6298. };
  6299. FreeCamera.prototype._update = function () {
  6300. this._checkInputs();
  6301. _super.prototype._update.call(this);
  6302. };
  6303. return FreeCamera;
  6304. })(BABYLON.TargetCamera);
  6305. BABYLON.FreeCamera = FreeCamera;
  6306. })(BABYLON || (BABYLON = {}));
  6307. //# sourceMappingURL=babylon.freeCamera.js.map
  6308. var BABYLON;
  6309. (function (BABYLON) {
  6310. // We're mainly based on the logic defined into the FreeCamera code
  6311. var TouchCamera = (function (_super) {
  6312. __extends(TouchCamera, _super);
  6313. function TouchCamera(name, position, scene) {
  6314. _super.call(this, name, position, scene);
  6315. this._offsetX = null;
  6316. this._offsetY = null;
  6317. this._pointerCount = 0;
  6318. this._pointerPressed = [];
  6319. this.angularSensibility = 200000.0;
  6320. this.moveSensibility = 500.0;
  6321. }
  6322. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  6323. var _this = this;
  6324. var previousPosition;
  6325. if (this._attachedCanvas) {
  6326. return;
  6327. }
  6328. this._attachedCanvas = canvas;
  6329. if (this._onPointerDown === undefined) {
  6330. this._onPointerDown = function (evt) {
  6331. if (!noPreventDefault) {
  6332. evt.preventDefault();
  6333. }
  6334. _this._pointerPressed.push(evt.pointerId);
  6335. if (_this._pointerPressed.length !== 1) {
  6336. return;
  6337. }
  6338. previousPosition = {
  6339. x: evt.clientX,
  6340. y: evt.clientY
  6341. };
  6342. };
  6343. this._onPointerUp = function (evt) {
  6344. if (!noPreventDefault) {
  6345. evt.preventDefault();
  6346. }
  6347. var index = _this._pointerPressed.indexOf(evt.pointerId);
  6348. if (index === -1) {
  6349. return;
  6350. }
  6351. _this._pointerPressed.splice(index, 1);
  6352. if (index != 0) {
  6353. return;
  6354. }
  6355. previousPosition = null;
  6356. _this._offsetX = null;
  6357. _this._offsetY = null;
  6358. };
  6359. this._onPointerMove = function (evt) {
  6360. if (!noPreventDefault) {
  6361. evt.preventDefault();
  6362. }
  6363. if (!previousPosition) {
  6364. return;
  6365. }
  6366. var index = _this._pointerPressed.indexOf(evt.pointerId);
  6367. if (index != 0) {
  6368. return;
  6369. }
  6370. _this._offsetX = evt.clientX - previousPosition.x;
  6371. _this._offsetY = -(evt.clientY - previousPosition.y);
  6372. };
  6373. this._onLostFocus = function () {
  6374. _this._offsetX = null;
  6375. _this._offsetY = null;
  6376. };
  6377. }
  6378. canvas.addEventListener("pointerdown", this._onPointerDown);
  6379. canvas.addEventListener("pointerup", this._onPointerUp);
  6380. canvas.addEventListener("pointerout", this._onPointerUp);
  6381. canvas.addEventListener("pointermove", this._onPointerMove);
  6382. BABYLON.Tools.RegisterTopRootEvents([
  6383. { name: "blur", handler: this._onLostFocus }
  6384. ]);
  6385. };
  6386. TouchCamera.prototype.detachControl = function (canvas) {
  6387. if (this._attachedCanvas != canvas) {
  6388. return;
  6389. }
  6390. canvas.removeEventListener("pointerdown", this._onPointerDown);
  6391. canvas.removeEventListener("pointerup", this._onPointerUp);
  6392. canvas.removeEventListener("pointerout", this._onPointerUp);
  6393. canvas.removeEventListener("pointermove", this._onPointerMove);
  6394. BABYLON.Tools.UnregisterTopRootEvents([
  6395. { name: "blur", handler: this._onLostFocus }
  6396. ]);
  6397. this._attachedCanvas = null;
  6398. };
  6399. TouchCamera.prototype._checkInputs = function () {
  6400. if (!this._offsetX) {
  6401. return;
  6402. }
  6403. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  6404. if (this._pointerPressed.length > 1) {
  6405. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  6406. } else {
  6407. var speed = this._computeLocalCameraSpeed();
  6408. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  6409. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  6410. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  6411. }
  6412. };
  6413. return TouchCamera;
  6414. })(BABYLON.FreeCamera);
  6415. BABYLON.TouchCamera = TouchCamera;
  6416. })(BABYLON || (BABYLON = {}));
  6417. //# sourceMappingURL=babylon.touchCamera.js.map
  6418. var BABYLON;
  6419. (function (BABYLON) {
  6420. // We're mainly based on the logic defined into the FreeCamera code
  6421. var DeviceOrientationCamera = (function (_super) {
  6422. __extends(DeviceOrientationCamera, _super);
  6423. function DeviceOrientationCamera(name, position, scene) {
  6424. var _this = this;
  6425. _super.call(this, name, position, scene);
  6426. this._offsetX = null;
  6427. this._offsetY = null;
  6428. this._orientationGamma = 0;
  6429. this._orientationBeta = 0;
  6430. this._initialOrientationGamma = 0;
  6431. this._initialOrientationBeta = 0;
  6432. this.angularSensibility = 10000.0;
  6433. this.moveSensibility = 50.0;
  6434. window.addEventListener("resize", function () {
  6435. _this._initialOrientationGamma = null;
  6436. }, false);
  6437. }
  6438. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  6439. var _this = this;
  6440. if (this._attachedCanvas) {
  6441. return;
  6442. }
  6443. this._attachedCanvas = canvas;
  6444. if (!this._orientationChanged) {
  6445. this._orientationChanged = function (evt) {
  6446. if (!_this._initialOrientationGamma) {
  6447. _this._initialOrientationGamma = evt.gamma;
  6448. _this._initialOrientationBeta = evt.beta;
  6449. }
  6450. _this._orientationGamma = evt.gamma;
  6451. _this._orientationBeta = evt.beta;
  6452. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  6453. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  6454. };
  6455. }
  6456. window.addEventListener("deviceorientation", this._orientationChanged);
  6457. };
  6458. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  6459. if (this._attachedCanvas != canvas) {
  6460. return;
  6461. }
  6462. window.removeEventListener("deviceorientation", this._orientationChanged);
  6463. this._attachedCanvas = null;
  6464. this._orientationGamma = 0;
  6465. this._orientationBeta = 0;
  6466. this._initialOrientationGamma = 0;
  6467. this._initialOrientationBeta = 0;
  6468. };
  6469. DeviceOrientationCamera.prototype._checkInputs = function () {
  6470. if (!this._offsetX) {
  6471. return;
  6472. }
  6473. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  6474. var speed = this._computeLocalCameraSpeed();
  6475. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  6476. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  6477. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  6478. };
  6479. return DeviceOrientationCamera;
  6480. })(BABYLON.FreeCamera);
  6481. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  6482. })(BABYLON || (BABYLON = {}));
  6483. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  6484. var BABYLON;
  6485. (function (BABYLON) {
  6486. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  6487. var ArcRotateCamera = (function (_super) {
  6488. __extends(ArcRotateCamera, _super);
  6489. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  6490. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  6491. this.alpha = alpha;
  6492. this.beta = beta;
  6493. this.radius = radius;
  6494. this.target = target;
  6495. this.inertialAlphaOffset = 0;
  6496. this.inertialBetaOffset = 0;
  6497. this.inertialRadiusOffset = 0;
  6498. this.lowerAlphaLimit = null;
  6499. this.upperAlphaLimit = null;
  6500. this.lowerBetaLimit = 0.01;
  6501. this.upperBetaLimit = Math.PI;
  6502. this.lowerRadiusLimit = null;
  6503. this.upperRadiusLimit = null;
  6504. this.angularSensibility = 1000.0;
  6505. this.wheelPrecision = 3.0;
  6506. this.keysUp = [38];
  6507. this.keysDown = [40];
  6508. this.keysLeft = [37];
  6509. this.keysRight = [39];
  6510. this.zoomOnFactor = 1;
  6511. this.targetScreenOffset = BABYLON.Vector2.Zero();
  6512. this._keys = [];
  6513. this._viewMatrix = new BABYLON.Matrix();
  6514. this.checkCollisions = false;
  6515. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  6516. this._collider = new BABYLON.Collider();
  6517. this._previousPosition = BABYLON.Vector3.Zero();
  6518. this._collisionVelocity = BABYLON.Vector3.Zero();
  6519. this._newPosition = BABYLON.Vector3.Zero();
  6520. // Pinch
  6521. // value for pinch step scaling
  6522. // set to 20 by default
  6523. this.pinchPrecision = 20;
  6524. this.getViewMatrix();
  6525. }
  6526. ArcRotateCamera.prototype._getTargetPosition = function () {
  6527. return this.target.position || this.target;
  6528. };
  6529. // Cache
  6530. ArcRotateCamera.prototype._initCache = function () {
  6531. _super.prototype._initCache.call(this);
  6532. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6533. this._cache.alpha = undefined;
  6534. this._cache.beta = undefined;
  6535. this._cache.radius = undefined;
  6536. this._cache.targetScreenOffset = undefined;
  6537. };
  6538. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  6539. if (!ignoreParentClass) {
  6540. _super.prototype._updateCache.call(this);
  6541. }
  6542. this._cache.target.copyFrom(this._getTargetPosition());
  6543. this._cache.alpha = this.alpha;
  6544. this._cache.beta = this.beta;
  6545. this._cache.radius = this.radius;
  6546. this._cache.targetScreenOffset = this.targetScreenOffset.clone();
  6547. };
  6548. // Synchronized
  6549. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  6550. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  6551. return false;
  6552. 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);
  6553. };
  6554. // Methods
  6555. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault) {
  6556. var _this = this;
  6557. var previousPosition;
  6558. var pointerId;
  6559. // to know if pinch started
  6560. var pinchStarted = false;
  6561. // two pinch point on X
  6562. // that will use for find if user action is pinch open or pinch close
  6563. var pinchPointX1, pinchPointX2;
  6564. if (this._attachedElement) {
  6565. return;
  6566. }
  6567. this._attachedElement = element;
  6568. var engine = this.getEngine();
  6569. if (this._onPointerDown === undefined) {
  6570. this._onPointerDown = function (evt) {
  6571. if (pointerId) {
  6572. return;
  6573. }
  6574. pointerId = evt.pointerId;
  6575. previousPosition = {
  6576. x: evt.clientX,
  6577. y: evt.clientY
  6578. };
  6579. if (!noPreventDefault) {
  6580. evt.preventDefault();
  6581. }
  6582. };
  6583. this._onPointerUp = function (evt) {
  6584. previousPosition = null;
  6585. pointerId = null;
  6586. if (!noPreventDefault) {
  6587. evt.preventDefault();
  6588. }
  6589. };
  6590. this._onPointerMove = function (evt) {
  6591. if (!previousPosition) {
  6592. return;
  6593. }
  6594. if (pointerId !== evt.pointerId) {
  6595. return;
  6596. }
  6597. // return pinch is started
  6598. if (pinchStarted) {
  6599. return;
  6600. }
  6601. var offsetX = evt.clientX - previousPosition.x;
  6602. var offsetY = evt.clientY - previousPosition.y;
  6603. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  6604. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  6605. previousPosition = {
  6606. x: evt.clientX,
  6607. y: evt.clientY
  6608. };
  6609. if (!noPreventDefault) {
  6610. evt.preventDefault();
  6611. }
  6612. };
  6613. this._onMouseMove = function (evt) {
  6614. if (!engine.isPointerLock) {
  6615. return;
  6616. }
  6617. // return pinch is started
  6618. if (pinchStarted) {
  6619. return;
  6620. }
  6621. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  6622. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  6623. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  6624. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  6625. if (!noPreventDefault) {
  6626. evt.preventDefault();
  6627. }
  6628. };
  6629. this._wheel = function (event) {
  6630. var delta = 0;
  6631. if (event.wheelDelta) {
  6632. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  6633. } else if (event.detail) {
  6634. delta = -event.detail / _this.wheelPrecision;
  6635. }
  6636. if (delta)
  6637. _this.inertialRadiusOffset += delta;
  6638. if (event.preventDefault) {
  6639. if (!noPreventDefault) {
  6640. event.preventDefault();
  6641. }
  6642. }
  6643. };
  6644. this._onKeyDown = function (evt) {
  6645. 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) {
  6646. var index = _this._keys.indexOf(evt.keyCode);
  6647. if (index === -1) {
  6648. _this._keys.push(evt.keyCode);
  6649. }
  6650. if (evt.preventDefault) {
  6651. if (!noPreventDefault) {
  6652. evt.preventDefault();
  6653. }
  6654. }
  6655. }
  6656. };
  6657. this._onKeyUp = function (evt) {
  6658. 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) {
  6659. var index = _this._keys.indexOf(evt.keyCode);
  6660. if (index >= 0) {
  6661. _this._keys.splice(index, 1);
  6662. }
  6663. if (evt.preventDefault) {
  6664. if (!noPreventDefault) {
  6665. evt.preventDefault();
  6666. }
  6667. }
  6668. }
  6669. };
  6670. this._onLostFocus = function () {
  6671. _this._keys = [];
  6672. pointerId = null;
  6673. };
  6674. this._onGestureStart = function (e) {
  6675. if (window.MSGesture === undefined) {
  6676. return;
  6677. }
  6678. if (!_this._MSGestureHandler) {
  6679. _this._MSGestureHandler = new MSGesture();
  6680. _this._MSGestureHandler.target = element;
  6681. }
  6682. _this._MSGestureHandler.addPointer(e.pointerId);
  6683. };
  6684. this._onGesture = function (e) {
  6685. _this.radius *= e.scale;
  6686. if (e.preventDefault) {
  6687. if (!noPreventDefault) {
  6688. e.stopPropagation();
  6689. e.preventDefault();
  6690. }
  6691. }
  6692. };
  6693. this._reset = function () {
  6694. _this._keys = [];
  6695. _this.inertialAlphaOffset = 0;
  6696. _this.inertialBetaOffset = 0;
  6697. _this.inertialRadiusOffset = 0;
  6698. previousPosition = null;
  6699. pointerId = null;
  6700. };
  6701. this._touchStart = function (event) {
  6702. if (event.touches.length == 2) {
  6703. //-- start pinch if two fingers on the screen
  6704. pinchStarted = true;
  6705. _this._pinchStart(event);
  6706. }
  6707. };
  6708. this._touchMove = function (event) {
  6709. if (pinchStarted) {
  6710. //-- make scaling
  6711. _this._pinchMove(event);
  6712. }
  6713. };
  6714. this._touchEnd = function (event) {
  6715. if (pinchStarted) {
  6716. //-- end of pinch
  6717. _this._pinchEnd(event);
  6718. }
  6719. };
  6720. this._pinchStart = function (event) {
  6721. // save origin touch point
  6722. pinchPointX1 = event.touches[0].clientX;
  6723. pinchPointX2 = event.touches[1].clientX;
  6724. // block the camera
  6725. // if not it rotate around target during pinch
  6726. pinchStarted = true;
  6727. };
  6728. this._pinchMove = function (event) {
  6729. // variable for new camera's radius
  6730. var delta = 0;
  6731. // variables to know if pinch open or pinch close
  6732. var direction = 1;
  6733. var distanceXOrigine, distanceXNow;
  6734. if (event.touches.length != 2)
  6735. return;
  6736. // calculate absolute distances of the two fingers
  6737. distanceXOrigine = Math.abs(pinchPointX1 - pinchPointX2);
  6738. distanceXNow = Math.abs(event.touches[0].clientX - event.touches[1].clientX);
  6739. // if distanceXNow < distanceXOrigine -> pinch close so direction = -1
  6740. if (distanceXNow < distanceXOrigine) {
  6741. direction = -1;
  6742. }
  6743. // calculate new radius
  6744. delta = (_this.pinchPrecision / (_this.wheelPrecision * 40)) * direction;
  6745. // set new radius
  6746. _this.inertialRadiusOffset += delta;
  6747. // save origin touch point
  6748. pinchPointX1 = event.touches[0].clientX;
  6749. pinchPointX2 = event.touches[1].clientX;
  6750. };
  6751. this._pinchEnd = function (event) {
  6752. // cancel pinch and deblock camera rotation
  6753. pinchStarted = false;
  6754. };
  6755. }
  6756. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  6757. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  6758. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  6759. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  6760. element.addEventListener("mousemove", this._onMouseMove, false);
  6761. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  6762. element.addEventListener("MSGestureChange", this._onGesture, false);
  6763. element.addEventListener('mousewheel', this._wheel, false);
  6764. element.addEventListener('DOMMouseScroll', this._wheel, false);
  6765. // pinch
  6766. element.addEventListener('touchstart', this._touchStart, false);
  6767. element.addEventListener('touchmove', this._touchMove, false);
  6768. element.addEventListener('touchend', this._touchEnd, false);
  6769. BABYLON.Tools.RegisterTopRootEvents([
  6770. { name: "keydown", handler: this._onKeyDown },
  6771. { name: "keyup", handler: this._onKeyUp },
  6772. { name: "blur", handler: this._onLostFocus }
  6773. ]);
  6774. };
  6775. ArcRotateCamera.prototype.detachControl = function (element) {
  6776. if (this._attachedElement != element) {
  6777. return;
  6778. }
  6779. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  6780. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  6781. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  6782. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  6783. element.removeEventListener("mousemove", this._onMouseMove);
  6784. element.removeEventListener("MSPointerDown", this._onGestureStart);
  6785. element.removeEventListener("MSGestureChange", this._onGesture);
  6786. element.removeEventListener('mousewheel', this._wheel);
  6787. element.removeEventListener('DOMMouseScroll', this._wheel);
  6788. // pinch
  6789. element.removeEventListener('touchstart', this._touchStart);
  6790. element.removeEventListener('touchmove', this._touchMove);
  6791. element.removeEventListener('touchend', this._touchEnd);
  6792. BABYLON.Tools.UnregisterTopRootEvents([
  6793. { name: "keydown", handler: this._onKeyDown },
  6794. { name: "keyup", handler: this._onKeyUp },
  6795. { name: "blur", handler: this._onLostFocus }
  6796. ]);
  6797. this._MSGestureHandler = null;
  6798. this._attachedElement = null;
  6799. if (this._reset) {
  6800. this._reset();
  6801. }
  6802. };
  6803. ArcRotateCamera.prototype._update = function () {
  6804. for (var index = 0; index < this._keys.length; index++) {
  6805. var keyCode = this._keys[index];
  6806. if (this.keysLeft.indexOf(keyCode) !== -1) {
  6807. this.inertialAlphaOffset -= 0.01;
  6808. } else if (this.keysUp.indexOf(keyCode) !== -1) {
  6809. this.inertialBetaOffset -= 0.01;
  6810. } else if (this.keysRight.indexOf(keyCode) !== -1) {
  6811. this.inertialAlphaOffset += 0.01;
  6812. } else if (this.keysDown.indexOf(keyCode) !== -1) {
  6813. this.inertialBetaOffset += 0.01;
  6814. }
  6815. }
  6816. // Inertia
  6817. if (this.inertialAlphaOffset != 0 || this.inertialBetaOffset != 0 || this.inertialRadiusOffset != 0) {
  6818. this.alpha += this.inertialAlphaOffset;
  6819. this.beta += this.inertialBetaOffset;
  6820. this.radius -= this.inertialRadiusOffset;
  6821. this.inertialAlphaOffset *= this.inertia;
  6822. this.inertialBetaOffset *= this.inertia;
  6823. this.inertialRadiusOffset *= this.inertia;
  6824. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  6825. this.inertialAlphaOffset = 0;
  6826. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  6827. this.inertialBetaOffset = 0;
  6828. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  6829. this.inertialRadiusOffset = 0;
  6830. }
  6831. // Limits
  6832. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  6833. this.alpha = this.lowerAlphaLimit;
  6834. }
  6835. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  6836. this.alpha = this.upperAlphaLimit;
  6837. }
  6838. if (this.lowerBetaLimit && this.beta < this.lowerBetaLimit) {
  6839. this.beta = this.lowerBetaLimit;
  6840. }
  6841. if (this.upperBetaLimit && this.beta > this.upperBetaLimit) {
  6842. this.beta = this.upperBetaLimit;
  6843. }
  6844. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  6845. this.radius = this.lowerRadiusLimit;
  6846. }
  6847. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  6848. this.radius = this.upperRadiusLimit;
  6849. }
  6850. };
  6851. ArcRotateCamera.prototype.setPosition = function (position) {
  6852. var radiusv3 = position.subtract(this._getTargetPosition());
  6853. this.radius = radiusv3.length();
  6854. // Alpha
  6855. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  6856. if (radiusv3.z < 0) {
  6857. this.alpha = 2 * Math.PI - this.alpha;
  6858. }
  6859. // Beta
  6860. this.beta = Math.acos(radiusv3.y / this.radius);
  6861. };
  6862. ArcRotateCamera.prototype._getViewMatrix = function () {
  6863. // Compute
  6864. var cosa = Math.cos(this.alpha);
  6865. var sina = Math.sin(this.alpha);
  6866. var cosb = Math.cos(this.beta);
  6867. var sinb = Math.sin(this.beta);
  6868. var target = this._getTargetPosition();
  6869. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this.position);
  6870. if (this.checkCollisions) {
  6871. this._collider.radius = this.collisionRadius;
  6872. this.position.subtractToRef(this._previousPosition, this._collisionVelocity);
  6873. this.getScene()._getNewPosition(this._previousPosition, this._collisionVelocity, this._collider, 3, this._newPosition);
  6874. if (!this._newPosition.equalsWithEpsilon(this.position)) {
  6875. this.position.copyFrom(this._previousPosition);
  6876. this.alpha = this._previousAlpha;
  6877. this.beta = this._previousBeta;
  6878. this.radius = this._previousRadius;
  6879. if (this.onCollide) {
  6880. this.onCollide(this._collider.collidedMesh);
  6881. }
  6882. }
  6883. }
  6884. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._viewMatrix);
  6885. this._previousAlpha = this.alpha;
  6886. this._previousBeta = this.beta;
  6887. this._previousRadius = this.radius;
  6888. this._previousPosition.copyFrom(this.position);
  6889. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  6890. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  6891. return this._viewMatrix;
  6892. };
  6893. ArcRotateCamera.prototype.zoomOn = function (meshes) {
  6894. meshes = meshes || this.getScene().meshes;
  6895. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  6896. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  6897. this.radius = distance * this.zoomOnFactor;
  6898. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance });
  6899. };
  6900. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance) {
  6901. var meshesOrMinMaxVector;
  6902. var distance;
  6903. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  6904. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  6905. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  6906. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  6907. } else {
  6908. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  6909. distance = meshesOrMinMaxVectorAndDistance.distance;
  6910. }
  6911. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  6912. this.maxZ = distance * 2;
  6913. };
  6914. return ArcRotateCamera;
  6915. })(BABYLON.Camera);
  6916. BABYLON.ArcRotateCamera = ArcRotateCamera;
  6917. })(BABYLON || (BABYLON = {}));
  6918. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  6919. var BABYLON;
  6920. (function (BABYLON) {
  6921. var Scene = (function () {
  6922. // Constructor
  6923. function Scene(engine) {
  6924. // Members
  6925. this.autoClear = true;
  6926. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  6927. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  6928. this.forceWireframe = false;
  6929. this.forcePointsCloud = false;
  6930. this.forceShowBoundingBoxes = false;
  6931. this.animationsEnabled = true;
  6932. this.cameraToUseForPointers = null;
  6933. // Fog
  6934. this.fogEnabled = true;
  6935. this.fogMode = Scene.FOGMODE_NONE;
  6936. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  6937. this.fogDensity = 0.1;
  6938. this.fogStart = 0;
  6939. this.fogEnd = 1000.0;
  6940. // Lights
  6941. this.shadowsEnabled = true;
  6942. this.lightsEnabled = true;
  6943. this.lights = new Array();
  6944. // Cameras
  6945. this.cameras = new Array();
  6946. this.activeCameras = new Array();
  6947. // Meshes
  6948. this.meshes = new Array();
  6949. // Geometries
  6950. this._geometries = new Array();
  6951. this.materials = new Array();
  6952. this.multiMaterials = new Array();
  6953. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  6954. // Textures
  6955. this.texturesEnabled = true;
  6956. this.textures = new Array();
  6957. // Particles
  6958. this.particlesEnabled = true;
  6959. this.particleSystems = new Array();
  6960. // Sprites
  6961. this.spriteManagers = new Array();
  6962. // Layers
  6963. this.layers = new Array();
  6964. // Skeletons
  6965. this.skeletonsEnabled = true;
  6966. this.skeletons = new Array();
  6967. // Lens flares
  6968. this.lensFlaresEnabled = true;
  6969. this.lensFlareSystems = new Array();
  6970. // Collisions
  6971. this.collisionsEnabled = true;
  6972. this.gravity = new BABYLON.Vector3(0, -9.0, 0);
  6973. // Postprocesses
  6974. this.postProcessesEnabled = true;
  6975. // Customs render targets
  6976. this.renderTargetsEnabled = true;
  6977. this.customRenderTargets = new Array();
  6978. // Imported meshes
  6979. this.importedMeshesFiles = new Array();
  6980. this._actionManagers = new Array();
  6981. this._meshesForIntersections = new BABYLON.SmartArray(256);
  6982. // Procedural textures
  6983. this.proceduralTexturesEnabled = true;
  6984. this._proceduralTextures = new Array();
  6985. this.soundTracks = new Array();
  6986. this._totalVertices = 0;
  6987. this._activeVertices = 0;
  6988. this._activeParticles = 0;
  6989. this._lastFrameDuration = 0;
  6990. this._evaluateActiveMeshesDuration = 0;
  6991. this._renderTargetsDuration = 0;
  6992. this._particlesDuration = 0;
  6993. this._renderDuration = 0;
  6994. this._spritesDuration = 0;
  6995. this._animationRatio = 0;
  6996. this._renderId = 0;
  6997. this._executeWhenReadyTimeoutId = -1;
  6998. this._toBeDisposed = new BABYLON.SmartArray(256);
  6999. this._onReadyCallbacks = new Array();
  7000. this._pendingData = [];
  7001. this._onBeforeRenderCallbacks = new Array();
  7002. this._onAfterRenderCallbacks = new Array();
  7003. this._activeMeshes = new BABYLON.SmartArray(256);
  7004. this._processedMaterials = new BABYLON.SmartArray(256);
  7005. this._renderTargets = new BABYLON.SmartArray(256);
  7006. this._activeParticleSystems = new BABYLON.SmartArray(256);
  7007. this._activeSkeletons = new BABYLON.SmartArray(32);
  7008. this._activeBones = 0;
  7009. this._activeAnimatables = new Array();
  7010. this._transformMatrix = BABYLON.Matrix.Zero();
  7011. this._scaledPosition = BABYLON.Vector3.Zero();
  7012. this._scaledVelocity = BABYLON.Vector3.Zero();
  7013. this._engine = engine;
  7014. engine.scenes.push(this);
  7015. this._renderingManager = new BABYLON.RenderingManager(this);
  7016. this.postProcessManager = new BABYLON.PostProcessManager(this);
  7017. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  7018. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  7019. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  7020. this.attachControl();
  7021. this._debugLayer = new BABYLON.DebugLayer(this);
  7022. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  7023. }
  7024. Object.defineProperty(Scene.prototype, "debugLayer", {
  7025. // Properties
  7026. get: function () {
  7027. return this._debugLayer;
  7028. },
  7029. enumerable: true,
  7030. configurable: true
  7031. });
  7032. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  7033. get: function () {
  7034. return this._meshUnderPointer;
  7035. },
  7036. enumerable: true,
  7037. configurable: true
  7038. });
  7039. Object.defineProperty(Scene.prototype, "pointerX", {
  7040. get: function () {
  7041. return this._pointerX;
  7042. },
  7043. enumerable: true,
  7044. configurable: true
  7045. });
  7046. Object.defineProperty(Scene.prototype, "pointerY", {
  7047. get: function () {
  7048. return this._pointerY;
  7049. },
  7050. enumerable: true,
  7051. configurable: true
  7052. });
  7053. Scene.prototype.getCachedMaterial = function () {
  7054. return this._cachedMaterial;
  7055. };
  7056. Scene.prototype.getBoundingBoxRenderer = function () {
  7057. return this._boundingBoxRenderer;
  7058. };
  7059. Scene.prototype.getOutlineRenderer = function () {
  7060. return this._outlineRenderer;
  7061. };
  7062. Scene.prototype.getEngine = function () {
  7063. return this._engine;
  7064. };
  7065. Scene.prototype.getTotalVertices = function () {
  7066. return this._totalVertices;
  7067. };
  7068. Scene.prototype.getActiveVertices = function () {
  7069. return this._activeVertices;
  7070. };
  7071. Scene.prototype.getActiveParticles = function () {
  7072. return this._activeParticles;
  7073. };
  7074. Scene.prototype.getActiveBones = function () {
  7075. return this._activeBones;
  7076. };
  7077. // Stats
  7078. Scene.prototype.getLastFrameDuration = function () {
  7079. return this._lastFrameDuration;
  7080. };
  7081. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  7082. return this._evaluateActiveMeshesDuration;
  7083. };
  7084. Scene.prototype.getActiveMeshes = function () {
  7085. return this._activeMeshes;
  7086. };
  7087. Scene.prototype.getRenderTargetsDuration = function () {
  7088. return this._renderTargetsDuration;
  7089. };
  7090. Scene.prototype.getRenderDuration = function () {
  7091. return this._renderDuration;
  7092. };
  7093. Scene.prototype.getParticlesDuration = function () {
  7094. return this._particlesDuration;
  7095. };
  7096. Scene.prototype.getSpritesDuration = function () {
  7097. return this._spritesDuration;
  7098. };
  7099. Scene.prototype.getAnimationRatio = function () {
  7100. return this._animationRatio;
  7101. };
  7102. Scene.prototype.getRenderId = function () {
  7103. return this._renderId;
  7104. };
  7105. Scene.prototype._updatePointerPosition = function (evt) {
  7106. var canvasRect = this._engine.getRenderingCanvasClientRect();
  7107. this._pointerX = evt.clientX - canvasRect.left;
  7108. this._pointerY = evt.clientY - canvasRect.top;
  7109. if (this.cameraToUseForPointers) {
  7110. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  7111. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  7112. }
  7113. };
  7114. // Pointers handling
  7115. Scene.prototype.attachControl = function () {
  7116. var _this = this;
  7117. this._onPointerMove = function (evt) {
  7118. var canvas = _this._engine.getRenderingCanvas();
  7119. _this._updatePointerPosition(evt);
  7120. var pickResult = _this.pick(_this._pointerX, _this._pointerY, function (mesh) {
  7121. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPointerTriggers;
  7122. }, false, _this.cameraToUseForPointers);
  7123. if (pickResult.hit) {
  7124. _this._meshUnderPointer = pickResult.pickedMesh;
  7125. _this.setPointerOverMesh(pickResult.pickedMesh);
  7126. canvas.style.cursor = "pointer";
  7127. } else {
  7128. _this.setPointerOverMesh(null);
  7129. canvas.style.cursor = "";
  7130. _this._meshUnderPointer = null;
  7131. }
  7132. };
  7133. this._onPointerDown = function (evt) {
  7134. var predicate = null;
  7135. if (!_this.onPointerDown) {
  7136. predicate = function (mesh) {
  7137. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  7138. };
  7139. }
  7140. _this._updatePointerPosition(evt);
  7141. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  7142. if (pickResult.hit) {
  7143. if (pickResult.pickedMesh.actionManager) {
  7144. switch (evt.button) {
  7145. case 0:
  7146. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  7147. break;
  7148. case 1:
  7149. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  7150. break;
  7151. case 2:
  7152. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  7153. break;
  7154. }
  7155. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  7156. }
  7157. }
  7158. if (_this.onPointerDown) {
  7159. _this.onPointerDown(evt, pickResult);
  7160. }
  7161. };
  7162. this._onKeyDown = function (evt) {
  7163. if (_this.actionManager) {
  7164. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  7165. }
  7166. };
  7167. this._onKeyUp = function (evt) {
  7168. if (_this.actionManager) {
  7169. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  7170. }
  7171. };
  7172. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  7173. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  7174. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  7175. window.addEventListener("keydown", this._onKeyDown, false);
  7176. window.addEventListener("keyup", this._onKeyUp, false);
  7177. };
  7178. Scene.prototype.detachControl = function () {
  7179. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  7180. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  7181. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  7182. window.removeEventListener("keydown", this._onKeyDown);
  7183. window.removeEventListener("keyup", this._onKeyUp);
  7184. };
  7185. // Ready
  7186. Scene.prototype.isReady = function () {
  7187. if (this._pendingData.length > 0) {
  7188. return false;
  7189. }
  7190. for (var index = 0; index < this._geometries.length; index++) {
  7191. var geometry = this._geometries[index];
  7192. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  7193. return false;
  7194. }
  7195. }
  7196. for (index = 0; index < this.meshes.length; index++) {
  7197. var mesh = this.meshes[index];
  7198. if (!mesh.isReady()) {
  7199. return false;
  7200. }
  7201. var mat = mesh.material;
  7202. if (mat) {
  7203. if (!mat.isReady(mesh)) {
  7204. return false;
  7205. }
  7206. }
  7207. }
  7208. return true;
  7209. };
  7210. Scene.prototype.resetCachedMaterial = function () {
  7211. this._cachedMaterial = null;
  7212. };
  7213. Scene.prototype.registerBeforeRender = function (func) {
  7214. this._onBeforeRenderCallbacks.push(func);
  7215. };
  7216. Scene.prototype.unregisterBeforeRender = function (func) {
  7217. var index = this._onBeforeRenderCallbacks.indexOf(func);
  7218. if (index > -1) {
  7219. this._onBeforeRenderCallbacks.splice(index, 1);
  7220. }
  7221. };
  7222. Scene.prototype.registerAfterRender = function (func) {
  7223. this._onAfterRenderCallbacks.push(func);
  7224. };
  7225. Scene.prototype.unregisterAfterRender = function (func) {
  7226. var index = this._onAfterRenderCallbacks.indexOf(func);
  7227. if (index > -1) {
  7228. this._onAfterRenderCallbacks.splice(index, 1);
  7229. }
  7230. };
  7231. Scene.prototype._addPendingData = function (data) {
  7232. this._pendingData.push(data);
  7233. };
  7234. Scene.prototype._removePendingData = function (data) {
  7235. var index = this._pendingData.indexOf(data);
  7236. if (index !== -1) {
  7237. this._pendingData.splice(index, 1);
  7238. }
  7239. };
  7240. Scene.prototype.getWaitingItemsCount = function () {
  7241. return this._pendingData.length;
  7242. };
  7243. Scene.prototype.executeWhenReady = function (func) {
  7244. var _this = this;
  7245. this._onReadyCallbacks.push(func);
  7246. if (this._executeWhenReadyTimeoutId !== -1) {
  7247. return;
  7248. }
  7249. this._executeWhenReadyTimeoutId = setTimeout(function () {
  7250. _this._checkIsReady();
  7251. }, 150);
  7252. };
  7253. Scene.prototype._checkIsReady = function () {
  7254. var _this = this;
  7255. if (this.isReady()) {
  7256. this._onReadyCallbacks.forEach(function (func) {
  7257. func();
  7258. });
  7259. this._onReadyCallbacks = [];
  7260. this._executeWhenReadyTimeoutId = -1;
  7261. return;
  7262. }
  7263. this._executeWhenReadyTimeoutId = setTimeout(function () {
  7264. _this._checkIsReady();
  7265. }, 150);
  7266. };
  7267. // Animations
  7268. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  7269. if (speedRatio === undefined) {
  7270. speedRatio = 1.0;
  7271. }
  7272. this.stopAnimation(target);
  7273. if (!animatable) {
  7274. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  7275. }
  7276. // Local animations
  7277. if (target.animations) {
  7278. animatable.appendAnimations(target, target.animations);
  7279. }
  7280. // Children animations
  7281. if (target.getAnimatables) {
  7282. var animatables = target.getAnimatables();
  7283. for (var index = 0; index < animatables.length; index++) {
  7284. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  7285. }
  7286. }
  7287. return animatable;
  7288. };
  7289. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  7290. if (speedRatio === undefined) {
  7291. speedRatio = 1.0;
  7292. }
  7293. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  7294. return animatable;
  7295. };
  7296. Scene.prototype.getAnimatableByTarget = function (target) {
  7297. for (var index = 0; index < this._activeAnimatables.length; index++) {
  7298. if (this._activeAnimatables[index].target === target) {
  7299. return this._activeAnimatables[index];
  7300. }
  7301. }
  7302. return null;
  7303. };
  7304. Scene.prototype.stopAnimation = function (target) {
  7305. var animatable = this.getAnimatableByTarget(target);
  7306. if (animatable) {
  7307. animatable.stop();
  7308. }
  7309. };
  7310. Scene.prototype._animate = function () {
  7311. if (!this.animationsEnabled) {
  7312. return;
  7313. }
  7314. if (!this._animationStartDate) {
  7315. this._animationStartDate = BABYLON.Tools.Now;
  7316. }
  7317. // Getting time
  7318. var now = BABYLON.Tools.Now;
  7319. var delay = now - this._animationStartDate;
  7320. for (var index = 0; index < this._activeAnimatables.length; index++) {
  7321. if (!this._activeAnimatables[index]._animate(delay)) {
  7322. this._activeAnimatables.splice(index, 1);
  7323. index--;
  7324. }
  7325. }
  7326. };
  7327. // Matrix
  7328. Scene.prototype.getViewMatrix = function () {
  7329. return this._viewMatrix;
  7330. };
  7331. Scene.prototype.getProjectionMatrix = function () {
  7332. return this._projectionMatrix;
  7333. };
  7334. Scene.prototype.getTransformMatrix = function () {
  7335. return this._transformMatrix;
  7336. };
  7337. Scene.prototype.setTransformMatrix = function (view, projection) {
  7338. this._viewMatrix = view;
  7339. this._projectionMatrix = projection;
  7340. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  7341. };
  7342. // Methods
  7343. Scene.prototype.setActiveCameraByID = function (id) {
  7344. var camera = this.getCameraByID(id);
  7345. if (camera) {
  7346. this.activeCamera = camera;
  7347. return camera;
  7348. }
  7349. return null;
  7350. };
  7351. Scene.prototype.setActiveCameraByName = function (name) {
  7352. var camera = this.getCameraByName(name);
  7353. if (camera) {
  7354. this.activeCamera = camera;
  7355. return camera;
  7356. }
  7357. return null;
  7358. };
  7359. Scene.prototype.getMaterialByID = function (id) {
  7360. for (var index = 0; index < this.materials.length; index++) {
  7361. if (this.materials[index].id === id) {
  7362. return this.materials[index];
  7363. }
  7364. }
  7365. return null;
  7366. };
  7367. Scene.prototype.getMaterialByName = function (name) {
  7368. for (var index = 0; index < this.materials.length; index++) {
  7369. if (this.materials[index].name === name) {
  7370. return this.materials[index];
  7371. }
  7372. }
  7373. return null;
  7374. };
  7375. Scene.prototype.getCameraByID = function (id) {
  7376. for (var index = 0; index < this.cameras.length; index++) {
  7377. if (this.cameras[index].id === id) {
  7378. return this.cameras[index];
  7379. }
  7380. }
  7381. return null;
  7382. };
  7383. Scene.prototype.getCameraByName = function (name) {
  7384. for (var index = 0; index < this.cameras.length; index++) {
  7385. if (this.cameras[index].name === name) {
  7386. return this.cameras[index];
  7387. }
  7388. }
  7389. return null;
  7390. };
  7391. Scene.prototype.getLightByName = function (name) {
  7392. for (var index = 0; index < this.lights.length; index++) {
  7393. if (this.lights[index].name === name) {
  7394. return this.lights[index];
  7395. }
  7396. }
  7397. return null;
  7398. };
  7399. Scene.prototype.getLightByID = function (id) {
  7400. for (var index = 0; index < this.lights.length; index++) {
  7401. if (this.lights[index].id === id) {
  7402. return this.lights[index];
  7403. }
  7404. }
  7405. return null;
  7406. };
  7407. Scene.prototype.getGeometryByID = function (id) {
  7408. for (var index = 0; index < this._geometries.length; index++) {
  7409. if (this._geometries[index].id === id) {
  7410. return this._geometries[index];
  7411. }
  7412. }
  7413. return null;
  7414. };
  7415. Scene.prototype.pushGeometry = function (geometry, force) {
  7416. if (!force && this.getGeometryByID(geometry.id)) {
  7417. return false;
  7418. }
  7419. this._geometries.push(geometry);
  7420. return true;
  7421. };
  7422. Scene.prototype.getGeometries = function () {
  7423. return this._geometries;
  7424. };
  7425. Scene.prototype.getMeshByID = function (id) {
  7426. for (var index = 0; index < this.meshes.length; index++) {
  7427. if (this.meshes[index].id === id) {
  7428. return this.meshes[index];
  7429. }
  7430. }
  7431. return null;
  7432. };
  7433. Scene.prototype.getLastMeshByID = function (id) {
  7434. for (var index = this.meshes.length - 1; index >= 0; index--) {
  7435. if (this.meshes[index].id === id) {
  7436. return this.meshes[index];
  7437. }
  7438. }
  7439. return null;
  7440. };
  7441. Scene.prototype.getLastEntryByID = function (id) {
  7442. for (var index = this.meshes.length - 1; index >= 0; index--) {
  7443. if (this.meshes[index].id === id) {
  7444. return this.meshes[index];
  7445. }
  7446. }
  7447. for (index = this.cameras.length - 1; index >= 0; index--) {
  7448. if (this.cameras[index].id === id) {
  7449. return this.cameras[index];
  7450. }
  7451. }
  7452. for (index = this.lights.length - 1; index >= 0; index--) {
  7453. if (this.lights[index].id === id) {
  7454. return this.lights[index];
  7455. }
  7456. }
  7457. return null;
  7458. };
  7459. Scene.prototype.getMeshByName = function (name) {
  7460. for (var index = 0; index < this.meshes.length; index++) {
  7461. if (this.meshes[index].name === name) {
  7462. return this.meshes[index];
  7463. }
  7464. }
  7465. return null;
  7466. };
  7467. Scene.prototype.getLastSkeletonByID = function (id) {
  7468. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  7469. if (this.skeletons[index].id === id) {
  7470. return this.skeletons[index];
  7471. }
  7472. }
  7473. return null;
  7474. };
  7475. Scene.prototype.getSkeletonById = function (id) {
  7476. for (var index = 0; index < this.skeletons.length; index++) {
  7477. if (this.skeletons[index].id === id) {
  7478. return this.skeletons[index];
  7479. }
  7480. }
  7481. return null;
  7482. };
  7483. Scene.prototype.getSkeletonByName = function (name) {
  7484. for (var index = 0; index < this.skeletons.length; index++) {
  7485. if (this.skeletons[index].name === name) {
  7486. return this.skeletons[index];
  7487. }
  7488. }
  7489. return null;
  7490. };
  7491. Scene.prototype.isActiveMesh = function (mesh) {
  7492. return (this._activeMeshes.indexOf(mesh) !== -1);
  7493. };
  7494. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  7495. if (mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  7496. var material = subMesh.getMaterial();
  7497. if (mesh.showSubMeshesBoundingBox) {
  7498. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  7499. }
  7500. if (material) {
  7501. // Render targets
  7502. if (material.getRenderTargetTextures) {
  7503. if (this._processedMaterials.indexOf(material) === -1) {
  7504. this._processedMaterials.push(material);
  7505. this._renderTargets.concat(material.getRenderTargetTextures());
  7506. }
  7507. }
  7508. // Dispatch
  7509. this._activeVertices += subMesh.indexCount;
  7510. this._renderingManager.dispatch(subMesh);
  7511. }
  7512. }
  7513. };
  7514. Scene.prototype._evaluateActiveMeshes = function () {
  7515. this._activeMeshes.reset();
  7516. this._renderingManager.reset();
  7517. this._processedMaterials.reset();
  7518. this._activeParticleSystems.reset();
  7519. this._activeSkeletons.reset();
  7520. this._boundingBoxRenderer.reset();
  7521. if (!this._frustumPlanes) {
  7522. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  7523. } else {
  7524. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  7525. }
  7526. // Meshes
  7527. var meshes;
  7528. var len;
  7529. if (this._selectionOctree) {
  7530. var selection = this._selectionOctree.select(this._frustumPlanes);
  7531. meshes = selection.data;
  7532. len = selection.length;
  7533. } else {
  7534. len = this.meshes.length;
  7535. meshes = this.meshes;
  7536. }
  7537. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  7538. var mesh = meshes[meshIndex];
  7539. if (mesh.isBlocked) {
  7540. continue;
  7541. }
  7542. this._totalVertices += mesh.getTotalVertices();
  7543. if (!mesh.isReady()) {
  7544. continue;
  7545. }
  7546. mesh.computeWorldMatrix();
  7547. // Intersections
  7548. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  7549. this._meshesForIntersections.pushNoDuplicate(mesh);
  7550. }
  7551. // Switch to current LOD
  7552. var meshLOD = mesh.getLOD(this.activeCamera);
  7553. if (!meshLOD) {
  7554. continue;
  7555. }
  7556. mesh._preActivate();
  7557. if (mesh.isEnabled() && mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  7558. this._activeMeshes.push(mesh);
  7559. mesh._activate(this._renderId);
  7560. this._activeMesh(meshLOD);
  7561. }
  7562. }
  7563. // Particle systems
  7564. var beforeParticlesDate = BABYLON.Tools.Now;
  7565. if (this.particlesEnabled) {
  7566. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  7567. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  7568. var particleSystem = this.particleSystems[particleIndex];
  7569. if (!particleSystem.isStarted()) {
  7570. continue;
  7571. }
  7572. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  7573. this._activeParticleSystems.push(particleSystem);
  7574. particleSystem.animate();
  7575. }
  7576. }
  7577. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  7578. }
  7579. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  7580. };
  7581. Scene.prototype._activeMesh = function (mesh) {
  7582. if (mesh.skeleton && this.skeletonsEnabled) {
  7583. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  7584. }
  7585. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  7586. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  7587. }
  7588. if (mesh && mesh.subMeshes) {
  7589. // Submeshes Octrees
  7590. var len;
  7591. var subMeshes;
  7592. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  7593. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  7594. len = intersections.length;
  7595. subMeshes = intersections.data;
  7596. } else {
  7597. subMeshes = mesh.subMeshes;
  7598. len = subMeshes.length;
  7599. }
  7600. for (var subIndex = 0; subIndex < len; subIndex++) {
  7601. var subMesh = subMeshes[subIndex];
  7602. this._evaluateSubMesh(subMesh, mesh);
  7603. }
  7604. }
  7605. };
  7606. Scene.prototype.updateTransformMatrix = function (force) {
  7607. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  7608. };
  7609. Scene.prototype._renderForCamera = function (camera) {
  7610. var engine = this._engine;
  7611. this.activeCamera = camera;
  7612. if (!this.activeCamera)
  7613. throw new Error("Active camera not set");
  7614. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  7615. // Viewport
  7616. engine.setViewport(this.activeCamera.viewport);
  7617. // Camera
  7618. this._renderId++;
  7619. this.updateTransformMatrix();
  7620. if (this.beforeCameraRender) {
  7621. this.beforeCameraRender(this.activeCamera);
  7622. }
  7623. // Meshes
  7624. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  7625. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  7626. this._evaluateActiveMeshes();
  7627. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  7628. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  7629. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  7630. var skeleton = this._activeSkeletons.data[skeletonIndex];
  7631. skeleton.prepare();
  7632. this._activeBones += skeleton.bones.length;
  7633. }
  7634. // Render targets
  7635. var beforeRenderTargetDate = BABYLON.Tools.Now;
  7636. if (this.renderTargetsEnabled) {
  7637. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  7638. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  7639. var renderTarget = this._renderTargets.data[renderIndex];
  7640. if (renderTarget._shouldRender()) {
  7641. this._renderId++;
  7642. renderTarget.render();
  7643. }
  7644. }
  7645. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  7646. this._renderId++;
  7647. }
  7648. if (this._renderTargets.length > 0) {
  7649. engine.restoreDefaultFramebuffer();
  7650. }
  7651. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  7652. // Prepare Frame
  7653. this.postProcessManager._prepareFrame();
  7654. var beforeRenderDate = BABYLON.Tools.Now;
  7655. // Backgrounds
  7656. if (this.layers.length) {
  7657. engine.setDepthBuffer(false);
  7658. var layerIndex;
  7659. var layer;
  7660. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  7661. layer = this.layers[layerIndex];
  7662. if (layer.isBackground) {
  7663. layer.render();
  7664. }
  7665. }
  7666. engine.setDepthBuffer(true);
  7667. }
  7668. // Render
  7669. BABYLON.Tools.StartPerformanceCounter("Main render");
  7670. this._renderingManager.render(null, null, true, true);
  7671. BABYLON.Tools.EndPerformanceCounter("Main render");
  7672. // Bounding boxes
  7673. this._boundingBoxRenderer.render();
  7674. // Lens flares
  7675. if (this.lensFlaresEnabled) {
  7676. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  7677. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  7678. this.lensFlareSystems[lensFlareSystemIndex].render();
  7679. }
  7680. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  7681. }
  7682. // Foregrounds
  7683. if (this.layers.length) {
  7684. engine.setDepthBuffer(false);
  7685. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  7686. layer = this.layers[layerIndex];
  7687. if (!layer.isBackground) {
  7688. layer.render();
  7689. }
  7690. }
  7691. engine.setDepthBuffer(true);
  7692. }
  7693. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  7694. // Finalize frame
  7695. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  7696. // Update camera
  7697. this.activeCamera._updateFromScene();
  7698. // Reset some special arrays
  7699. this._renderTargets.reset();
  7700. if (this.afterCameraRender) {
  7701. this.afterCameraRender(this.activeCamera);
  7702. }
  7703. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  7704. };
  7705. Scene.prototype._processSubCameras = function (camera) {
  7706. if (camera.subCameras.length === 0) {
  7707. this._renderForCamera(camera);
  7708. return;
  7709. }
  7710. for (var index = 0; index < camera.subCameras.length; index++) {
  7711. this._renderForCamera(camera.subCameras[index]);
  7712. }
  7713. this.activeCamera = camera;
  7714. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  7715. // Update camera
  7716. this.activeCamera._updateFromScene();
  7717. };
  7718. Scene.prototype._checkIntersections = function () {
  7719. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  7720. var sourceMesh = this._meshesForIntersections.data[index];
  7721. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  7722. var action = sourceMesh.actionManager.actions[actionIndex];
  7723. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  7724. var otherMesh = action.getTriggerParameter();
  7725. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, false);
  7726. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  7727. if (areIntersecting && currentIntersectionInProgress === -1 && action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  7728. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  7729. sourceMesh._intersectionsInProgress.push(otherMesh);
  7730. } else if (!areIntersecting && currentIntersectionInProgress > -1 && action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  7731. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  7732. var indexOfOther = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  7733. if (indexOfOther > -1) {
  7734. sourceMesh._intersectionsInProgress.splice(indexOfOther, 1);
  7735. }
  7736. }
  7737. }
  7738. }
  7739. }
  7740. };
  7741. Scene.prototype.render = function () {
  7742. var startDate = BABYLON.Tools.Now;
  7743. this._particlesDuration = 0;
  7744. this._spritesDuration = 0;
  7745. this._activeParticles = 0;
  7746. this._renderDuration = 0;
  7747. this._renderTargetsDuration = 0;
  7748. this._evaluateActiveMeshesDuration = 0;
  7749. this._totalVertices = 0;
  7750. this._activeVertices = 0;
  7751. this._activeBones = 0;
  7752. this.getEngine().resetDrawCalls();
  7753. this._meshesForIntersections.reset();
  7754. this.resetCachedMaterial();
  7755. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  7756. // Actions
  7757. if (this.actionManager) {
  7758. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  7759. }
  7760. // Before render
  7761. if (this.beforeRender) {
  7762. this.beforeRender();
  7763. }
  7764. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  7765. this._onBeforeRenderCallbacks[callbackIndex]();
  7766. }
  7767. // Animations
  7768. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  7769. this._animationRatio = deltaTime * (60.0 / 1000.0);
  7770. this._animate();
  7771. // Physics
  7772. if (this._physicsEngine) {
  7773. BABYLON.Tools.StartPerformanceCounter("Physics");
  7774. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  7775. BABYLON.Tools.EndPerformanceCounter("Physics");
  7776. }
  7777. // Customs render targets
  7778. var beforeRenderTargetDate = BABYLON.Tools.Now;
  7779. var engine = this.getEngine();
  7780. if (this.renderTargetsEnabled) {
  7781. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  7782. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  7783. var renderTarget = this.customRenderTargets[customIndex];
  7784. if (renderTarget._shouldRender()) {
  7785. this._renderId++;
  7786. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  7787. if (!this.activeCamera)
  7788. throw new Error("Active camera not set");
  7789. // Viewport
  7790. engine.setViewport(this.activeCamera.viewport);
  7791. // Camera
  7792. this.updateTransformMatrix();
  7793. renderTarget.render();
  7794. }
  7795. }
  7796. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  7797. this._renderId++;
  7798. }
  7799. if (this.customRenderTargets.length > 0) {
  7800. engine.restoreDefaultFramebuffer();
  7801. }
  7802. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  7803. // Procedural textures
  7804. if (this.proceduralTexturesEnabled) {
  7805. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  7806. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  7807. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  7808. if (proceduralTexture._shouldRender()) {
  7809. proceduralTexture.render();
  7810. }
  7811. }
  7812. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  7813. }
  7814. // Clear
  7815. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  7816. // Shadows
  7817. if (this.shadowsEnabled) {
  7818. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  7819. var light = this.lights[lightIndex];
  7820. var shadowGenerator = light.getShadowGenerator();
  7821. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  7822. this._renderTargets.push(shadowGenerator.getShadowMap());
  7823. }
  7824. }
  7825. }
  7826. // RenderPipeline
  7827. this.postProcessRenderPipelineManager.update();
  7828. // Multi-cameras?
  7829. if (this.activeCameras.length > 0) {
  7830. var currentRenderId = this._renderId;
  7831. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  7832. this._renderId = currentRenderId;
  7833. this._processSubCameras(this.activeCameras[cameraIndex]);
  7834. }
  7835. } else {
  7836. if (!this.activeCamera) {
  7837. throw new Error("No camera defined");
  7838. }
  7839. this._processSubCameras(this.activeCamera);
  7840. }
  7841. // Intersection checks
  7842. this._checkIntersections();
  7843. // Update the audio listener attached to the camera
  7844. this._updateAudioParameters();
  7845. // After render
  7846. if (this.afterRender) {
  7847. this.afterRender();
  7848. }
  7849. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  7850. this._onAfterRenderCallbacks[callbackIndex]();
  7851. }
  7852. for (var index = 0; index < this._toBeDisposed.length; index++) {
  7853. this._toBeDisposed.data[index].dispose();
  7854. this._toBeDisposed[index] = null;
  7855. }
  7856. this._toBeDisposed.reset();
  7857. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  7858. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  7859. };
  7860. Scene.prototype._updateAudioParameters = function () {
  7861. var listeningCamera;
  7862. var audioEngine = this._engine.getAudioEngine();
  7863. if (this.activeCameras.length > 0) {
  7864. listeningCamera = this.activeCameras[0];
  7865. } else {
  7866. listeningCamera = this.activeCamera;
  7867. }
  7868. if (listeningCamera && audioEngine.canUseWebAudio) {
  7869. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  7870. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  7871. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  7872. cameraDirection.normalize();
  7873. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  7874. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  7875. var sound = this.mainSoundTrack.soundCollection[i];
  7876. if (sound.useBabylonJSAttenuation) {
  7877. sound.updateDistanceFromListener();
  7878. }
  7879. }
  7880. for (var i = 0; i < this.soundTracks.length; i++) {
  7881. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  7882. var sound = this.soundTracks[i].soundCollection[j];
  7883. if (sound.useBabylonJSAttenuation) {
  7884. sound.updateDistanceFromListener();
  7885. }
  7886. }
  7887. }
  7888. }
  7889. };
  7890. Scene.prototype.dispose = function () {
  7891. this.beforeRender = null;
  7892. this.afterRender = null;
  7893. this.skeletons = [];
  7894. this._boundingBoxRenderer.dispose();
  7895. // Debug layer
  7896. this.debugLayer.hide();
  7897. // Events
  7898. if (this.onDispose) {
  7899. this.onDispose();
  7900. }
  7901. this._onBeforeRenderCallbacks = [];
  7902. this._onAfterRenderCallbacks = [];
  7903. this.detachControl();
  7904. // Detach cameras
  7905. var canvas = this._engine.getRenderingCanvas();
  7906. var index;
  7907. for (index = 0; index < this.cameras.length; index++) {
  7908. this.cameras[index].detachControl(canvas);
  7909. }
  7910. while (this.lights.length) {
  7911. this.lights[0].dispose();
  7912. }
  7913. while (this.meshes.length) {
  7914. this.meshes[0].dispose(true);
  7915. }
  7916. while (this.cameras.length) {
  7917. this.cameras[0].dispose();
  7918. }
  7919. while (this.materials.length) {
  7920. this.materials[0].dispose();
  7921. }
  7922. while (this.particleSystems.length) {
  7923. this.particleSystems[0].dispose();
  7924. }
  7925. while (this.spriteManagers.length) {
  7926. this.spriteManagers[0].dispose();
  7927. }
  7928. while (this.layers.length) {
  7929. this.layers[0].dispose();
  7930. }
  7931. while (this.textures.length) {
  7932. this.textures[0].dispose();
  7933. }
  7934. // Post-processes
  7935. this.postProcessManager.dispose();
  7936. // Physics
  7937. if (this._physicsEngine) {
  7938. this.disablePhysicsEngine();
  7939. }
  7940. // Remove from engine
  7941. index = this._engine.scenes.indexOf(this);
  7942. if (index > -1) {
  7943. this._engine.scenes.splice(index, 1);
  7944. }
  7945. this._engine.wipeCaches();
  7946. };
  7947. // Collisions
  7948. Scene.prototype._getNewPosition = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  7949. if (typeof excludedMesh === "undefined") { excludedMesh = null; }
  7950. position.divideToRef(collider.radius, this._scaledPosition);
  7951. velocity.divideToRef(collider.radius, this._scaledVelocity);
  7952. collider.retry = 0;
  7953. collider.initialVelocity = this._scaledVelocity;
  7954. collider.initialPosition = this._scaledPosition;
  7955. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, finalPosition, excludedMesh);
  7956. finalPosition.multiplyInPlace(collider.radius);
  7957. };
  7958. Scene.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  7959. if (typeof excludedMesh === "undefined") { excludedMesh = null; }
  7960. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  7961. if (collider.retry >= maximumRetry) {
  7962. finalPosition.copyFrom(position);
  7963. return;
  7964. }
  7965. collider._initialize(position, velocity, closeDistance);
  7966. for (var index = 0; index < this.meshes.length; index++) {
  7967. var mesh = this.meshes[index];
  7968. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  7969. mesh._checkCollision(collider);
  7970. }
  7971. }
  7972. if (!collider.collisionFound) {
  7973. position.addToRef(velocity, finalPosition);
  7974. return;
  7975. }
  7976. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  7977. collider._getResponse(position, velocity);
  7978. }
  7979. if (velocity.length() <= closeDistance) {
  7980. finalPosition.copyFrom(position);
  7981. return;
  7982. }
  7983. collider.retry++;
  7984. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  7985. };
  7986. // Octrees
  7987. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  7988. if (typeof maxCapacity === "undefined") { maxCapacity = 64; }
  7989. if (typeof maxDepth === "undefined") { maxDepth = 2; }
  7990. if (!this._selectionOctree) {
  7991. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  7992. }
  7993. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7994. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  7995. for (var index = 0; index < this.meshes.length; index++) {
  7996. var mesh = this.meshes[index];
  7997. mesh.computeWorldMatrix(true);
  7998. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  7999. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  8000. BABYLON.Tools.CheckExtends(minBox, min, max);
  8001. BABYLON.Tools.CheckExtends(maxBox, min, max);
  8002. }
  8003. // Update octree
  8004. this._selectionOctree.update(min, max, this.meshes);
  8005. return this._selectionOctree;
  8006. };
  8007. // Picking
  8008. Scene.prototype.createPickingRay = function (x, y, world, camera) {
  8009. var engine = this._engine;
  8010. if (!camera) {
  8011. if (!this.activeCamera)
  8012. throw new Error("Active camera not set");
  8013. camera = this.activeCamera;
  8014. }
  8015. var cameraViewport = camera.viewport;
  8016. var viewport = cameraViewport.toGlobal(engine);
  8017. // Moving coordinates to local viewport world
  8018. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  8019. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  8020. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  8021. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  8022. };
  8023. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  8024. var pickingInfo = null;
  8025. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  8026. var mesh = this.meshes[meshIndex];
  8027. if (predicate) {
  8028. if (!predicate(mesh)) {
  8029. continue;
  8030. }
  8031. } else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  8032. continue;
  8033. }
  8034. var world = mesh.getWorldMatrix();
  8035. var ray = rayFunction(world);
  8036. var result = mesh.intersects(ray, fastCheck);
  8037. if (!result || !result.hit)
  8038. continue;
  8039. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  8040. continue;
  8041. pickingInfo = result;
  8042. if (fastCheck) {
  8043. break;
  8044. }
  8045. }
  8046. return pickingInfo || new BABYLON.PickingInfo();
  8047. };
  8048. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  8049. var _this = this;
  8050. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  8051. /// <param name="x">X position on screen</param>
  8052. /// <param name="y">Y position on screen</param>
  8053. /// <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>
  8054. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  8055. /// <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>
  8056. return this._internalPick(function (world) {
  8057. return _this.createPickingRay(x, y, world, camera);
  8058. }, predicate, fastCheck);
  8059. };
  8060. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  8061. var _this = this;
  8062. return this._internalPick(function (world) {
  8063. if (!_this._pickWithRayInverseMatrix) {
  8064. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  8065. }
  8066. world.invertToRef(_this._pickWithRayInverseMatrix);
  8067. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  8068. }, predicate, fastCheck);
  8069. };
  8070. Scene.prototype.setPointerOverMesh = function (mesh) {
  8071. if (this._pointerOverMesh === mesh) {
  8072. return;
  8073. }
  8074. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  8075. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  8076. }
  8077. this._pointerOverMesh = mesh;
  8078. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  8079. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  8080. }
  8081. };
  8082. Scene.prototype.getPointerOverMesh = function () {
  8083. return this._pointerOverMesh;
  8084. };
  8085. // Physics
  8086. Scene.prototype.getPhysicsEngine = function () {
  8087. return this._physicsEngine;
  8088. };
  8089. Scene.prototype.enablePhysics = function (gravity, plugin) {
  8090. if (this._physicsEngine) {
  8091. return true;
  8092. }
  8093. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  8094. if (!this._physicsEngine.isSupported()) {
  8095. this._physicsEngine = null;
  8096. return false;
  8097. }
  8098. this._physicsEngine._initialize(gravity);
  8099. return true;
  8100. };
  8101. Scene.prototype.disablePhysicsEngine = function () {
  8102. if (!this._physicsEngine) {
  8103. return;
  8104. }
  8105. this._physicsEngine.dispose();
  8106. this._physicsEngine = undefined;
  8107. };
  8108. Scene.prototype.isPhysicsEnabled = function () {
  8109. return this._physicsEngine !== undefined;
  8110. };
  8111. Scene.prototype.setGravity = function (gravity) {
  8112. if (!this._physicsEngine) {
  8113. return;
  8114. }
  8115. this._physicsEngine._setGravity(gravity);
  8116. };
  8117. Scene.prototype.createCompoundImpostor = function (parts, options) {
  8118. if (parts.parts) {
  8119. options = parts;
  8120. parts = parts.parts;
  8121. }
  8122. if (!this._physicsEngine) {
  8123. return null;
  8124. }
  8125. for (var index = 0; index < parts.length; index++) {
  8126. var mesh = parts[index].mesh;
  8127. mesh._physicImpostor = parts[index].impostor;
  8128. mesh._physicsMass = options.mass / parts.length;
  8129. mesh._physicsFriction = options.friction;
  8130. mesh._physicRestitution = options.restitution;
  8131. }
  8132. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  8133. };
  8134. //ANY
  8135. Scene.prototype.deleteCompoundImpostor = function (compound) {
  8136. for (var index = 0; index < compound.parts.length; index++) {
  8137. var mesh = compound.parts[index].mesh;
  8138. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  8139. this._physicsEngine._unregisterMesh(mesh);
  8140. }
  8141. };
  8142. // Tags
  8143. Scene.prototype._getByTags = function (list, tagsQuery) {
  8144. if (tagsQuery === undefined) {
  8145. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  8146. return list;
  8147. }
  8148. var listByTags = [];
  8149. for (var i in list) {
  8150. var item = list[i];
  8151. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  8152. listByTags.push(item);
  8153. }
  8154. }
  8155. return listByTags;
  8156. };
  8157. Scene.prototype.getMeshesByTags = function (tagsQuery) {
  8158. return this._getByTags(this.meshes, tagsQuery);
  8159. };
  8160. Scene.prototype.getCamerasByTags = function (tagsQuery) {
  8161. return this._getByTags(this.cameras, tagsQuery);
  8162. };
  8163. Scene.prototype.getLightsByTags = function (tagsQuery) {
  8164. return this._getByTags(this.lights, tagsQuery);
  8165. };
  8166. Scene.prototype.getMaterialByTags = function (tagsQuery) {
  8167. return this._getByTags(this.materials, tagsQuery).concat(this._getByTags(this.multiMaterials, tagsQuery));
  8168. };
  8169. Scene.FOGMODE_NONE = 0;
  8170. Scene.FOGMODE_EXP = 1;
  8171. Scene.FOGMODE_EXP2 = 2;
  8172. Scene.FOGMODE_LINEAR = 3;
  8173. Scene.MinDeltaTime = 1.0;
  8174. Scene.MaxDeltaTime = 1000.0;
  8175. return Scene;
  8176. })();
  8177. BABYLON.Scene = Scene;
  8178. })(BABYLON || (BABYLON = {}));
  8179. //# sourceMappingURL=babylon.scene.js.map
  8180. var BABYLON;
  8181. (function (BABYLON) {
  8182. var VertexBuffer = (function () {
  8183. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  8184. if (engine instanceof BABYLON.Mesh) {
  8185. this._engine = engine.getScene().getEngine();
  8186. } else {
  8187. this._engine = engine;
  8188. }
  8189. this._updatable = updatable;
  8190. this._data = data;
  8191. if (!postponeInternalCreation) {
  8192. this.create();
  8193. }
  8194. this._kind = kind;
  8195. if (stride) {
  8196. this._strideSize = stride;
  8197. return;
  8198. }
  8199. switch (kind) {
  8200. case VertexBuffer.PositionKind:
  8201. this._strideSize = 3;
  8202. break;
  8203. case VertexBuffer.NormalKind:
  8204. this._strideSize = 3;
  8205. break;
  8206. case VertexBuffer.UVKind:
  8207. this._strideSize = 2;
  8208. break;
  8209. case VertexBuffer.UV2Kind:
  8210. this._strideSize = 2;
  8211. break;
  8212. case VertexBuffer.ColorKind:
  8213. this._strideSize = 4;
  8214. break;
  8215. case VertexBuffer.MatricesIndicesKind:
  8216. this._strideSize = 4;
  8217. break;
  8218. case VertexBuffer.MatricesWeightsKind:
  8219. this._strideSize = 4;
  8220. break;
  8221. }
  8222. }
  8223. // Properties
  8224. VertexBuffer.prototype.isUpdatable = function () {
  8225. return this._updatable;
  8226. };
  8227. VertexBuffer.prototype.getData = function () {
  8228. return this._data;
  8229. };
  8230. VertexBuffer.prototype.getBuffer = function () {
  8231. return this._buffer;
  8232. };
  8233. VertexBuffer.prototype.getStrideSize = function () {
  8234. return this._strideSize;
  8235. };
  8236. // Methods
  8237. VertexBuffer.prototype.create = function (data) {
  8238. if (!data && this._buffer) {
  8239. return;
  8240. }
  8241. data = data || this._data;
  8242. if (!this._buffer) {
  8243. if (this._updatable) {
  8244. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  8245. } else {
  8246. this._buffer = this._engine.createVertexBuffer(data);
  8247. }
  8248. }
  8249. if (this._updatable) {
  8250. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  8251. this._data = data;
  8252. }
  8253. };
  8254. VertexBuffer.prototype.update = function (data) {
  8255. this.create(data);
  8256. };
  8257. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  8258. if (!this._buffer) {
  8259. return;
  8260. }
  8261. if (this._updatable) {
  8262. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  8263. this._data = null;
  8264. }
  8265. };
  8266. VertexBuffer.prototype.dispose = function () {
  8267. if (!this._buffer) {
  8268. return;
  8269. }
  8270. if (this._engine._releaseBuffer(this._buffer)) {
  8271. this._buffer = null;
  8272. }
  8273. };
  8274. Object.defineProperty(VertexBuffer, "PositionKind", {
  8275. get: function () {
  8276. return VertexBuffer._PositionKind;
  8277. },
  8278. enumerable: true,
  8279. configurable: true
  8280. });
  8281. Object.defineProperty(VertexBuffer, "NormalKind", {
  8282. get: function () {
  8283. return VertexBuffer._NormalKind;
  8284. },
  8285. enumerable: true,
  8286. configurable: true
  8287. });
  8288. Object.defineProperty(VertexBuffer, "UVKind", {
  8289. get: function () {
  8290. return VertexBuffer._UVKind;
  8291. },
  8292. enumerable: true,
  8293. configurable: true
  8294. });
  8295. Object.defineProperty(VertexBuffer, "UV2Kind", {
  8296. get: function () {
  8297. return VertexBuffer._UV2Kind;
  8298. },
  8299. enumerable: true,
  8300. configurable: true
  8301. });
  8302. Object.defineProperty(VertexBuffer, "ColorKind", {
  8303. get: function () {
  8304. return VertexBuffer._ColorKind;
  8305. },
  8306. enumerable: true,
  8307. configurable: true
  8308. });
  8309. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  8310. get: function () {
  8311. return VertexBuffer._MatricesIndicesKind;
  8312. },
  8313. enumerable: true,
  8314. configurable: true
  8315. });
  8316. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  8317. get: function () {
  8318. return VertexBuffer._MatricesWeightsKind;
  8319. },
  8320. enumerable: true,
  8321. configurable: true
  8322. });
  8323. VertexBuffer._PositionKind = "position";
  8324. VertexBuffer._NormalKind = "normal";
  8325. VertexBuffer._UVKind = "uv";
  8326. VertexBuffer._UV2Kind = "uv2";
  8327. VertexBuffer._ColorKind = "color";
  8328. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  8329. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  8330. return VertexBuffer;
  8331. })();
  8332. BABYLON.VertexBuffer = VertexBuffer;
  8333. })(BABYLON || (BABYLON = {}));
  8334. //# sourceMappingURL=babylon.vertexBuffer.js.map
  8335. var BABYLON;
  8336. (function (BABYLON) {
  8337. var AbstractMesh = (function (_super) {
  8338. __extends(AbstractMesh, _super);
  8339. function AbstractMesh(name, scene) {
  8340. _super.call(this, name, scene);
  8341. // Properties
  8342. this.position = new BABYLON.Vector3(0, 0, 0);
  8343. this.rotation = new BABYLON.Vector3(0, 0, 0);
  8344. this.scaling = new BABYLON.Vector3(1, 1, 1);
  8345. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  8346. this.visibility = 1.0;
  8347. this.alphaIndex = Number.MAX_VALUE;
  8348. this.infiniteDistance = false;
  8349. this.isVisible = true;
  8350. this.isPickable = true;
  8351. this.showBoundingBox = false;
  8352. this.showSubMeshesBoundingBox = false;
  8353. this.onDispose = null;
  8354. this.checkCollisions = false;
  8355. this.isBlocker = false;
  8356. this.renderingGroupId = 0;
  8357. this.receiveShadows = false;
  8358. this.renderOutline = false;
  8359. this.outlineColor = BABYLON.Color3.Red();
  8360. this.outlineWidth = 0.02;
  8361. this.renderOverlay = false;
  8362. this.overlayColor = BABYLON.Color3.Red();
  8363. this.overlayAlpha = 0.5;
  8364. this.hasVertexAlpha = false;
  8365. this.useVertexColors = true;
  8366. this.applyFog = true;
  8367. this.useOctreeForRenderingSelection = true;
  8368. this.useOctreeForPicking = true;
  8369. this.useOctreeForCollisions = true;
  8370. this.layerMask = 0xFFFFFFFF;
  8371. // Physics
  8372. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  8373. // Collisions
  8374. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  8375. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  8376. this._collider = new BABYLON.Collider();
  8377. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8378. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8379. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8380. // Cache
  8381. this._localScaling = BABYLON.Matrix.Zero();
  8382. this._localRotation = BABYLON.Matrix.Zero();
  8383. this._localTranslation = BABYLON.Matrix.Zero();
  8384. this._localBillboard = BABYLON.Matrix.Zero();
  8385. this._localPivotScaling = BABYLON.Matrix.Zero();
  8386. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  8387. this._localWorld = BABYLON.Matrix.Zero();
  8388. this._worldMatrix = BABYLON.Matrix.Zero();
  8389. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  8390. this._absolutePosition = BABYLON.Vector3.Zero();
  8391. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  8392. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  8393. this._isDirty = false;
  8394. this._pivotMatrix = BABYLON.Matrix.Identity();
  8395. this._isDisposed = false;
  8396. this._renderId = 0;
  8397. this._intersectionsInProgress = new Array();
  8398. this._onAfterWorldMatrixUpdate = new Array();
  8399. scene.meshes.push(this);
  8400. }
  8401. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  8402. get: function () {
  8403. return AbstractMesh._BILLBOARDMODE_NONE;
  8404. },
  8405. enumerable: true,
  8406. configurable: true
  8407. });
  8408. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  8409. get: function () {
  8410. return AbstractMesh._BILLBOARDMODE_X;
  8411. },
  8412. enumerable: true,
  8413. configurable: true
  8414. });
  8415. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  8416. get: function () {
  8417. return AbstractMesh._BILLBOARDMODE_Y;
  8418. },
  8419. enumerable: true,
  8420. configurable: true
  8421. });
  8422. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  8423. get: function () {
  8424. return AbstractMesh._BILLBOARDMODE_Z;
  8425. },
  8426. enumerable: true,
  8427. configurable: true
  8428. });
  8429. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  8430. get: function () {
  8431. return AbstractMesh._BILLBOARDMODE_ALL;
  8432. },
  8433. enumerable: true,
  8434. configurable: true
  8435. });
  8436. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  8437. // Methods
  8438. get: function () {
  8439. return false;
  8440. },
  8441. enumerable: true,
  8442. configurable: true
  8443. });
  8444. AbstractMesh.prototype.getLOD = function (camera) {
  8445. return this;
  8446. };
  8447. AbstractMesh.prototype.getTotalVertices = function () {
  8448. return 0;
  8449. };
  8450. AbstractMesh.prototype.getIndices = function () {
  8451. return null;
  8452. };
  8453. AbstractMesh.prototype.getVerticesData = function (kind) {
  8454. return null;
  8455. };
  8456. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  8457. return false;
  8458. };
  8459. AbstractMesh.prototype.getBoundingInfo = function () {
  8460. if (this._masterMesh) {
  8461. return this._masterMesh.getBoundingInfo();
  8462. }
  8463. if (!this._boundingInfo) {
  8464. this._updateBoundingInfo();
  8465. }
  8466. return this._boundingInfo;
  8467. };
  8468. AbstractMesh.prototype._preActivate = function () {
  8469. };
  8470. AbstractMesh.prototype._activate = function (renderId) {
  8471. this._renderId = renderId;
  8472. };
  8473. AbstractMesh.prototype.getWorldMatrix = function () {
  8474. if (this._masterMesh) {
  8475. return this._masterMesh.getWorldMatrix();
  8476. }
  8477. if (this._currentRenderId !== this.getScene().getRenderId()) {
  8478. this.computeWorldMatrix();
  8479. }
  8480. return this._worldMatrix;
  8481. };
  8482. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  8483. get: function () {
  8484. return this._worldMatrix;
  8485. },
  8486. enumerable: true,
  8487. configurable: true
  8488. });
  8489. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  8490. get: function () {
  8491. return this._absolutePosition;
  8492. },
  8493. enumerable: true,
  8494. configurable: true
  8495. });
  8496. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  8497. if (!this.rotationQuaternion) {
  8498. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  8499. this.rotation = BABYLON.Vector3.Zero();
  8500. }
  8501. if (!space || space == 0 /* LOCAL */) {
  8502. var rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  8503. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  8504. } else {
  8505. if (this.parent) {
  8506. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  8507. invertParentWorldMatrix.invert();
  8508. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  8509. }
  8510. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  8511. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  8512. }
  8513. };
  8514. AbstractMesh.prototype.translate = function (axis, distance, space) {
  8515. var displacementVector = axis.scale(distance);
  8516. if (!space || space == 0 /* LOCAL */) {
  8517. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  8518. this.setPositionWithLocalVector(tempV3);
  8519. } else {
  8520. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  8521. }
  8522. };
  8523. AbstractMesh.prototype.getAbsolutePosition = function () {
  8524. this.computeWorldMatrix();
  8525. return this._absolutePosition;
  8526. };
  8527. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  8528. if (!absolutePosition) {
  8529. return;
  8530. }
  8531. var absolutePositionX;
  8532. var absolutePositionY;
  8533. var absolutePositionZ;
  8534. if (absolutePosition.x === undefined) {
  8535. if (arguments.length < 3) {
  8536. return;
  8537. }
  8538. absolutePositionX = arguments[0];
  8539. absolutePositionY = arguments[1];
  8540. absolutePositionZ = arguments[2];
  8541. } else {
  8542. absolutePositionX = absolutePosition.x;
  8543. absolutePositionY = absolutePosition.y;
  8544. absolutePositionZ = absolutePosition.z;
  8545. }
  8546. if (this.parent) {
  8547. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  8548. invertParentWorldMatrix.invert();
  8549. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  8550. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  8551. } else {
  8552. this.position.x = absolutePositionX;
  8553. this.position.y = absolutePositionY;
  8554. this.position.z = absolutePositionZ;
  8555. }
  8556. };
  8557. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  8558. this._pivotMatrix = matrix;
  8559. this._cache.pivotMatrixUpdated = true;
  8560. };
  8561. AbstractMesh.prototype.getPivotMatrix = function () {
  8562. return this._pivotMatrix;
  8563. };
  8564. AbstractMesh.prototype._isSynchronized = function () {
  8565. if (this._isDirty) {
  8566. return false;
  8567. }
  8568. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  8569. return false;
  8570. if (this._cache.pivotMatrixUpdated) {
  8571. return false;
  8572. }
  8573. if (this.infiniteDistance) {
  8574. return false;
  8575. }
  8576. if (!this._cache.position.equals(this.position))
  8577. return false;
  8578. if (this.rotationQuaternion) {
  8579. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  8580. return false;
  8581. } else {
  8582. if (!this._cache.rotation.equals(this.rotation))
  8583. return false;
  8584. }
  8585. if (!this._cache.scaling.equals(this.scaling))
  8586. return false;
  8587. return true;
  8588. };
  8589. AbstractMesh.prototype._initCache = function () {
  8590. _super.prototype._initCache.call(this);
  8591. this._cache.localMatrixUpdated = false;
  8592. this._cache.position = BABYLON.Vector3.Zero();
  8593. this._cache.scaling = BABYLON.Vector3.Zero();
  8594. this._cache.rotation = BABYLON.Vector3.Zero();
  8595. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  8596. };
  8597. AbstractMesh.prototype.markAsDirty = function (property) {
  8598. if (property === "rotation") {
  8599. this.rotationQuaternion = null;
  8600. }
  8601. this._currentRenderId = Number.MAX_VALUE;
  8602. this._isDirty = true;
  8603. };
  8604. AbstractMesh.prototype._updateBoundingInfo = function () {
  8605. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  8606. this._boundingInfo._update(this.worldMatrixFromCache);
  8607. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  8608. };
  8609. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  8610. if (!this.subMeshes) {
  8611. return;
  8612. }
  8613. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  8614. var subMesh = this.subMeshes[subIndex];
  8615. subMesh.updateBoundingInfo(matrix);
  8616. }
  8617. };
  8618. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  8619. if (!force && (this._currentRenderId == this.getScene().getRenderId() || this.isSynchronized(true))) {
  8620. return this._worldMatrix;
  8621. }
  8622. this._cache.position.copyFrom(this.position);
  8623. this._cache.scaling.copyFrom(this.scaling);
  8624. this._cache.pivotMatrixUpdated = false;
  8625. this._currentRenderId = this.getScene().getRenderId();
  8626. this._isDirty = false;
  8627. // Scaling
  8628. BABYLON.Matrix.ScalingToRef(this.scaling.x, this.scaling.y, this.scaling.z, this._localScaling);
  8629. // Rotation
  8630. if (this.rotationQuaternion) {
  8631. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  8632. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  8633. } else {
  8634. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  8635. this._cache.rotation.copyFrom(this.rotation);
  8636. }
  8637. // Translation
  8638. if (this.infiniteDistance && !this.parent) {
  8639. var camera = this.getScene().activeCamera;
  8640. var cameraWorldMatrix = camera.getWorldMatrix();
  8641. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  8642. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  8643. } else {
  8644. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  8645. }
  8646. // Composing transformations
  8647. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  8648. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  8649. // Billboarding
  8650. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  8651. var localPosition = this.position.clone();
  8652. var zero = this.getScene().activeCamera.position.clone();
  8653. if (this.parent && this.parent.position) {
  8654. localPosition.addInPlace(this.parent.position);
  8655. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  8656. }
  8657. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) === AbstractMesh.BILLBOARDMODE_ALL) {
  8658. zero = this.getScene().activeCamera.position;
  8659. } else {
  8660. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X)
  8661. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  8662. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y)
  8663. zero.y = localPosition.y + 0.001;
  8664. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z)
  8665. zero.z = localPosition.z + 0.001;
  8666. }
  8667. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  8668. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  8669. this._localBillboard.invert();
  8670. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  8671. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  8672. }
  8673. // Local world
  8674. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  8675. // Parent
  8676. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  8677. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  8678. } else {
  8679. this._worldMatrix.copyFrom(this._localWorld);
  8680. }
  8681. // Bounding info
  8682. this._updateBoundingInfo();
  8683. // Absolute position
  8684. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  8685. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  8686. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  8687. }
  8688. return this._worldMatrix;
  8689. };
  8690. /**
  8691. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  8692. * @param func: callback function to add
  8693. */
  8694. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  8695. this._onAfterWorldMatrixUpdate.push(func);
  8696. };
  8697. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  8698. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  8699. if (index > -1) {
  8700. this._onAfterWorldMatrixUpdate.splice(index, 1);
  8701. }
  8702. };
  8703. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  8704. this.computeWorldMatrix();
  8705. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  8706. };
  8707. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  8708. this.computeWorldMatrix();
  8709. var invLocalWorldMatrix = this._localWorld.clone();
  8710. invLocalWorldMatrix.invert();
  8711. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  8712. };
  8713. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  8714. this.computeWorldMatrix();
  8715. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  8716. };
  8717. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  8718. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  8719. /// <param name="targetPoint" type="BABYLON.Vector3">The position (must be in same space as current mesh) to look at</param>
  8720. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  8721. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  8722. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  8723. /// <returns>Mesh oriented towards targetMesh</returns>
  8724. yawCor = yawCor || 0; // default to zero if undefined
  8725. pitchCor = pitchCor || 0;
  8726. rollCor = rollCor || 0;
  8727. var dv = targetPoint.subtract(this.position);
  8728. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  8729. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  8730. var pitch = Math.atan2(dv.y, len);
  8731. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  8732. };
  8733. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  8734. if (!this._boundingInfo.isInFrustum(frustumPlanes)) {
  8735. return false;
  8736. }
  8737. return true;
  8738. };
  8739. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  8740. if (!camera) {
  8741. camera = this.getScene().activeCamera;
  8742. }
  8743. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  8744. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  8745. return false;
  8746. }
  8747. return true;
  8748. };
  8749. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  8750. if (!this._boundingInfo || !mesh._boundingInfo) {
  8751. return false;
  8752. }
  8753. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  8754. };
  8755. AbstractMesh.prototype.intersectsPoint = function (point) {
  8756. if (!this._boundingInfo) {
  8757. return false;
  8758. }
  8759. return this._boundingInfo.intersectsPoint(point);
  8760. };
  8761. // Physics
  8762. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  8763. var physicsEngine = this.getScene().getPhysicsEngine();
  8764. if (!physicsEngine) {
  8765. return;
  8766. }
  8767. if (impostor.impostor) {
  8768. // Old API
  8769. options = impostor;
  8770. impostor = impostor.impostor;
  8771. }
  8772. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  8773. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  8774. physicsEngine._unregisterMesh(this);
  8775. return;
  8776. }
  8777. options.mass = options.mass || 0;
  8778. options.friction = options.friction || 0.2;
  8779. options.restitution = options.restitution || 0.2;
  8780. this._physicImpostor = impostor;
  8781. this._physicsMass = options.mass;
  8782. this._physicsFriction = options.friction;
  8783. this._physicRestitution = options.restitution;
  8784. return physicsEngine._registerMesh(this, impostor, options);
  8785. };
  8786. AbstractMesh.prototype.getPhysicsImpostor = function () {
  8787. if (!this._physicImpostor) {
  8788. return BABYLON.PhysicsEngine.NoImpostor;
  8789. }
  8790. return this._physicImpostor;
  8791. };
  8792. AbstractMesh.prototype.getPhysicsMass = function () {
  8793. if (!this._physicsMass) {
  8794. return 0;
  8795. }
  8796. return this._physicsMass;
  8797. };
  8798. AbstractMesh.prototype.getPhysicsFriction = function () {
  8799. if (!this._physicsFriction) {
  8800. return 0;
  8801. }
  8802. return this._physicsFriction;
  8803. };
  8804. AbstractMesh.prototype.getPhysicsRestitution = function () {
  8805. if (!this._physicRestitution) {
  8806. return 0;
  8807. }
  8808. return this._physicRestitution;
  8809. };
  8810. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  8811. if (!camera) {
  8812. camera = this.getScene().activeCamera;
  8813. }
  8814. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  8815. };
  8816. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  8817. if (!camera) {
  8818. camera = this.getScene().activeCamera;
  8819. }
  8820. return this.absolutePosition.subtract(camera.position).length();
  8821. };
  8822. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  8823. if (!this._physicImpostor) {
  8824. return;
  8825. }
  8826. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  8827. };
  8828. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  8829. if (!this._physicImpostor) {
  8830. return;
  8831. }
  8832. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  8833. };
  8834. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  8835. if (!this._physicImpostor) {
  8836. return;
  8837. }
  8838. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  8839. };
  8840. // Collisions
  8841. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  8842. var globalPosition = this.getAbsolutePosition();
  8843. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  8844. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  8845. this._collider.radius = this.ellipsoid;
  8846. this.getScene()._getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this._newPositionForCollisions, this);
  8847. this._newPositionForCollisions.subtractToRef(this._oldPositionForCollisions, this._diffPositionForCollisions);
  8848. if (this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  8849. this.position.addInPlace(this._diffPositionForCollisions);
  8850. }
  8851. };
  8852. // Submeshes octree
  8853. /**
  8854. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  8855. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  8856. */
  8857. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  8858. if (typeof maxCapacity === "undefined") { maxCapacity = 64; }
  8859. if (typeof maxDepth === "undefined") { maxDepth = 2; }
  8860. if (!this._submeshesOctree) {
  8861. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  8862. }
  8863. this.computeWorldMatrix(true);
  8864. // Update octree
  8865. var bbox = this.getBoundingInfo().boundingBox;
  8866. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  8867. return this._submeshesOctree;
  8868. };
  8869. // Collisions
  8870. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  8871. this._generatePointsArray();
  8872. // Transformation
  8873. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  8874. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  8875. subMesh._lastColliderWorldVertices = [];
  8876. subMesh._trianglePlanes = [];
  8877. var start = subMesh.verticesStart;
  8878. var end = (subMesh.verticesStart + subMesh.verticesCount);
  8879. for (var i = start; i < end; i++) {
  8880. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  8881. }
  8882. }
  8883. // Collide
  8884. collider._collide(subMesh, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart);
  8885. };
  8886. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  8887. var subMeshes;
  8888. var len;
  8889. // Octrees
  8890. if (this._submeshesOctree && this.useOctreeForCollisions) {
  8891. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  8892. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  8893. len = intersections.length;
  8894. subMeshes = intersections.data;
  8895. } else {
  8896. subMeshes = this.subMeshes;
  8897. len = subMeshes.length;
  8898. }
  8899. for (var index = 0; index < len; index++) {
  8900. var subMesh = subMeshes[index];
  8901. // Bounding test
  8902. if (len > 1 && !subMesh._checkCollision(collider))
  8903. continue;
  8904. this._collideForSubMesh(subMesh, transformMatrix, collider);
  8905. }
  8906. };
  8907. AbstractMesh.prototype._checkCollision = function (collider) {
  8908. // Bounding box test
  8909. if (!this._boundingInfo._checkCollision(collider))
  8910. return;
  8911. // Transformation matrix
  8912. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  8913. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  8914. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  8915. };
  8916. // Picking
  8917. AbstractMesh.prototype._generatePointsArray = function () {
  8918. return false;
  8919. };
  8920. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  8921. var pickingInfo = new BABYLON.PickingInfo();
  8922. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  8923. return pickingInfo;
  8924. }
  8925. if (!this._generatePointsArray()) {
  8926. return pickingInfo;
  8927. }
  8928. var intersectInfo = null;
  8929. // Octrees
  8930. var subMeshes;
  8931. var len;
  8932. if (this._submeshesOctree && this.useOctreeForPicking) {
  8933. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  8934. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  8935. len = intersections.length;
  8936. subMeshes = intersections.data;
  8937. } else {
  8938. subMeshes = this.subMeshes;
  8939. len = subMeshes.length;
  8940. }
  8941. for (var index = 0; index < len; index++) {
  8942. var subMesh = subMeshes[index];
  8943. // Bounding test
  8944. if (len > 1 && !subMesh.canIntersects(ray))
  8945. continue;
  8946. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  8947. if (currentIntersectInfo) {
  8948. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  8949. intersectInfo = currentIntersectInfo;
  8950. if (fastCheck) {
  8951. break;
  8952. }
  8953. }
  8954. }
  8955. }
  8956. if (intersectInfo) {
  8957. // Get picked point
  8958. var world = this.getWorldMatrix();
  8959. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  8960. var direction = ray.direction.clone();
  8961. direction.normalize();
  8962. direction = direction.scale(intersectInfo.distance);
  8963. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  8964. var pickedPoint = worldOrigin.add(worldDirection);
  8965. // Return result
  8966. pickingInfo.hit = true;
  8967. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  8968. pickingInfo.pickedPoint = pickedPoint;
  8969. pickingInfo.pickedMesh = this;
  8970. pickingInfo.bu = intersectInfo.bu;
  8971. pickingInfo.bv = intersectInfo.bv;
  8972. pickingInfo.faceId = intersectInfo.faceId;
  8973. return pickingInfo;
  8974. }
  8975. return pickingInfo;
  8976. };
  8977. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  8978. return null;
  8979. };
  8980. AbstractMesh.prototype.releaseSubMeshes = function () {
  8981. if (this.subMeshes) {
  8982. while (this.subMeshes.length) {
  8983. this.subMeshes[0].dispose();
  8984. }
  8985. } else {
  8986. this.subMeshes = new Array();
  8987. }
  8988. };
  8989. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  8990. // Physics
  8991. if (this.getPhysicsImpostor() != BABYLON.PhysicsEngine.NoImpostor) {
  8992. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  8993. }
  8994. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  8995. var other = this._intersectionsInProgress[index];
  8996. var pos = other._intersectionsInProgress.indexOf(this);
  8997. other._intersectionsInProgress.splice(pos, 1);
  8998. }
  8999. this._intersectionsInProgress = [];
  9000. // SubMeshes
  9001. this.releaseSubMeshes();
  9002. // Remove from scene
  9003. var index = this.getScene().meshes.indexOf(this);
  9004. if (index != -1) {
  9005. // Remove from the scene if mesh found
  9006. this.getScene().meshes.splice(index, 1);
  9007. }
  9008. if (!doNotRecurse) {
  9009. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  9010. if (this.getScene().particleSystems[index].emitter == this) {
  9011. this.getScene().particleSystems[index].dispose();
  9012. index--;
  9013. }
  9014. }
  9015. // Children
  9016. var objects = this.getScene().meshes.slice(0);
  9017. for (index = 0; index < objects.length; index++) {
  9018. if (objects[index].parent == this) {
  9019. objects[index].dispose();
  9020. }
  9021. }
  9022. } else {
  9023. for (index = 0; index < this.getScene().meshes.length; index++) {
  9024. var obj = this.getScene().meshes[index];
  9025. if (obj.parent === this) {
  9026. obj.parent = null;
  9027. obj.computeWorldMatrix(true);
  9028. }
  9029. }
  9030. }
  9031. this._onAfterWorldMatrixUpdate = [];
  9032. this._isDisposed = true;
  9033. // Callback
  9034. if (this.onDispose) {
  9035. this.onDispose();
  9036. }
  9037. };
  9038. AbstractMesh._BILLBOARDMODE_NONE = 0;
  9039. AbstractMesh._BILLBOARDMODE_X = 1;
  9040. AbstractMesh._BILLBOARDMODE_Y = 2;
  9041. AbstractMesh._BILLBOARDMODE_Z = 4;
  9042. AbstractMesh._BILLBOARDMODE_ALL = 7;
  9043. return AbstractMesh;
  9044. })(BABYLON.Node);
  9045. BABYLON.AbstractMesh = AbstractMesh;
  9046. })(BABYLON || (BABYLON = {}));
  9047. //# sourceMappingURL=babylon.abstractMesh.js.map
  9048. var BABYLON;
  9049. (function (BABYLON) {
  9050. var _InstancesBatch = (function () {
  9051. function _InstancesBatch() {
  9052. this.mustReturn = false;
  9053. this.visibleInstances = new Array();
  9054. this.renderSelf = new Array();
  9055. }
  9056. return _InstancesBatch;
  9057. })();
  9058. BABYLON._InstancesBatch = _InstancesBatch;
  9059. var Mesh = (function (_super) {
  9060. __extends(Mesh, _super);
  9061. /**
  9062. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  9063. * @param {BABYLON.Scene} scene - The scene to add this mesh to.
  9064. * @param {BABYLON.Node} parent - The parent of this mesh, if it has one
  9065. * @param {BABYLON.Mesh} source - An optional Mesh from which geometry is shared, cloned.
  9066. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  9067. * When false, achieved by calling a clone(), also passing False.
  9068. * This will make creation of children, recursive.
  9069. */
  9070. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  9071. if (typeof parent === "undefined") { parent = null; }
  9072. _super.call(this, name, scene);
  9073. // Members
  9074. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  9075. this.instances = new Array();
  9076. this._LODLevels = new Array();
  9077. this._onBeforeRenderCallbacks = new Array();
  9078. this._onAfterRenderCallbacks = new Array();
  9079. this._visibleInstances = {};
  9080. this._renderIdForInstances = new Array();
  9081. this._batchCache = new _InstancesBatch();
  9082. this._instancesBufferSize = 32 * 16 * 4;
  9083. if (source) {
  9084. // Geometry
  9085. if (source._geometry) {
  9086. source._geometry.applyToMesh(this);
  9087. }
  9088. // Deep copy
  9089. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton"], []);
  9090. // Material
  9091. this.material = source.material;
  9092. if (!doNotCloneChildren) {
  9093. for (var index = 0; index < scene.meshes.length; index++) {
  9094. var mesh = scene.meshes[index];
  9095. if (mesh.parent === source) {
  9096. // doNotCloneChildren is always going to be False
  9097. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  9098. }
  9099. }
  9100. }
  9101. for (index = 0; index < scene.particleSystems.length; index++) {
  9102. var system = scene.particleSystems[index];
  9103. if (system.emitter === source) {
  9104. system.clone(system.name, this);
  9105. }
  9106. }
  9107. this.computeWorldMatrix(true);
  9108. }
  9109. // Parent
  9110. if (parent !== null) {
  9111. this.parent = parent;
  9112. }
  9113. }
  9114. Mesh.prototype._clone = function () {
  9115. };
  9116. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  9117. // Methods
  9118. get: function () {
  9119. return this._LODLevels.length > 0;
  9120. },
  9121. enumerable: true,
  9122. configurable: true
  9123. });
  9124. Mesh.prototype._sortLODLevels = function () {
  9125. this._LODLevels.sort(function (a, b) {
  9126. if (a.distance < b.distance) {
  9127. return 1;
  9128. }
  9129. if (a.distance > b.distance) {
  9130. return -1;
  9131. }
  9132. return 0;
  9133. });
  9134. };
  9135. Mesh.prototype.addLODLevel = function (distance, mesh) {
  9136. if (mesh && mesh._masterMesh) {
  9137. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  9138. return this;
  9139. }
  9140. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  9141. this._LODLevels.push(level);
  9142. if (mesh) {
  9143. mesh._masterMesh = this;
  9144. }
  9145. this._sortLODLevels();
  9146. return this;
  9147. };
  9148. Mesh.prototype.removeLODLevel = function (mesh) {
  9149. for (var index = 0; index < this._LODLevels.length; index++) {
  9150. if (this._LODLevels[index].mesh === mesh) {
  9151. this._LODLevels.splice(index, 1);
  9152. if (mesh) {
  9153. mesh._masterMesh = null;
  9154. }
  9155. }
  9156. }
  9157. this._sortLODLevels();
  9158. return this;
  9159. };
  9160. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  9161. if (!this._LODLevels || this._LODLevels.length === 0) {
  9162. return this;
  9163. }
  9164. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  9165. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  9166. return this;
  9167. }
  9168. for (var index = 0; index < this._LODLevels.length; index++) {
  9169. var level = this._LODLevels[index];
  9170. if (level.distance < distanceToCamera) {
  9171. if (level.mesh) {
  9172. level.mesh._preActivate();
  9173. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  9174. }
  9175. return level.mesh;
  9176. }
  9177. }
  9178. return this;
  9179. };
  9180. Object.defineProperty(Mesh.prototype, "geometry", {
  9181. get: function () {
  9182. return this._geometry;
  9183. },
  9184. enumerable: true,
  9185. configurable: true
  9186. });
  9187. Mesh.prototype.getTotalVertices = function () {
  9188. if (!this._geometry) {
  9189. return 0;
  9190. }
  9191. return this._geometry.getTotalVertices();
  9192. };
  9193. Mesh.prototype.getVerticesData = function (kind) {
  9194. if (!this._geometry) {
  9195. return null;
  9196. }
  9197. return this._geometry.getVerticesData(kind);
  9198. };
  9199. Mesh.prototype.getVertexBuffer = function (kind) {
  9200. if (!this._geometry) {
  9201. return undefined;
  9202. }
  9203. return this._geometry.getVertexBuffer(kind);
  9204. };
  9205. Mesh.prototype.isVerticesDataPresent = function (kind) {
  9206. if (!this._geometry) {
  9207. if (this._delayInfo) {
  9208. return this._delayInfo.indexOf(kind) !== -1;
  9209. }
  9210. return false;
  9211. }
  9212. return this._geometry.isVerticesDataPresent(kind);
  9213. };
  9214. Mesh.prototype.getVerticesDataKinds = function () {
  9215. if (!this._geometry) {
  9216. var result = [];
  9217. if (this._delayInfo) {
  9218. for (var kind in this._delayInfo) {
  9219. result.push(kind);
  9220. }
  9221. }
  9222. return result;
  9223. }
  9224. return this._geometry.getVerticesDataKinds();
  9225. };
  9226. Mesh.prototype.getTotalIndices = function () {
  9227. if (!this._geometry) {
  9228. return 0;
  9229. }
  9230. return this._geometry.getTotalIndices();
  9231. };
  9232. Mesh.prototype.getIndices = function () {
  9233. if (!this._geometry) {
  9234. return [];
  9235. }
  9236. return this._geometry.getIndices();
  9237. };
  9238. Object.defineProperty(Mesh.prototype, "isBlocked", {
  9239. get: function () {
  9240. return this._masterMesh !== null && this._masterMesh !== undefined;
  9241. },
  9242. enumerable: true,
  9243. configurable: true
  9244. });
  9245. Mesh.prototype.isReady = function () {
  9246. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  9247. return false;
  9248. }
  9249. return _super.prototype.isReady.call(this);
  9250. };
  9251. Mesh.prototype.isDisposed = function () {
  9252. return this._isDisposed;
  9253. };
  9254. // Methods
  9255. Mesh.prototype._preActivate = function () {
  9256. var sceneRenderId = this.getScene().getRenderId();
  9257. if (this._preActivateId == sceneRenderId) {
  9258. return;
  9259. }
  9260. this._preActivateId = sceneRenderId;
  9261. this._visibleInstances = null;
  9262. };
  9263. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  9264. if (!this._visibleInstances) {
  9265. this._visibleInstances = {};
  9266. this._visibleInstances.defaultRenderId = renderId;
  9267. this._visibleInstances.selfDefaultRenderId = this._renderId;
  9268. }
  9269. if (!this._visibleInstances[renderId]) {
  9270. this._visibleInstances[renderId] = new Array();
  9271. }
  9272. this._visibleInstances[renderId].push(instance);
  9273. };
  9274. Mesh.prototype.refreshBoundingInfo = function () {
  9275. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  9276. if (data) {
  9277. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  9278. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  9279. }
  9280. if (this.subMeshes) {
  9281. for (var index = 0; index < this.subMeshes.length; index++) {
  9282. this.subMeshes[index].refreshBoundingInfo();
  9283. }
  9284. }
  9285. this._updateBoundingInfo();
  9286. };
  9287. Mesh.prototype._createGlobalSubMesh = function () {
  9288. var totalVertices = this.getTotalVertices();
  9289. if (!totalVertices || !this.getIndices()) {
  9290. return null;
  9291. }
  9292. this.releaseSubMeshes();
  9293. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  9294. };
  9295. Mesh.prototype.subdivide = function (count) {
  9296. if (count < 1) {
  9297. return;
  9298. }
  9299. var totalIndices = this.getTotalIndices();
  9300. var subdivisionSize = (totalIndices / count) | 0;
  9301. var offset = 0;
  9302. while (subdivisionSize % 3 != 0) {
  9303. subdivisionSize++;
  9304. }
  9305. this.releaseSubMeshes();
  9306. for (var index = 0; index < count; index++) {
  9307. if (offset >= totalIndices) {
  9308. break;
  9309. }
  9310. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  9311. offset += subdivisionSize;
  9312. }
  9313. this.synchronizeInstances();
  9314. };
  9315. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  9316. if (kind instanceof Array) {
  9317. var temp = data;
  9318. data = kind;
  9319. kind = temp;
  9320. BABYLON.Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  9321. }
  9322. if (!this._geometry) {
  9323. var vertexData = new BABYLON.VertexData();
  9324. vertexData.set(data, kind);
  9325. var scene = this.getScene();
  9326. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  9327. } else {
  9328. this._geometry.setVerticesData(kind, data, updatable, stride);
  9329. }
  9330. };
  9331. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  9332. if (!this._geometry) {
  9333. return;
  9334. }
  9335. if (!makeItUnique) {
  9336. this._geometry.updateVerticesData(kind, data, updateExtends);
  9337. } else {
  9338. this.makeGeometryUnique();
  9339. this.updateVerticesData(kind, data, updateExtends, false);
  9340. }
  9341. };
  9342. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  9343. if (!this._geometry) {
  9344. return;
  9345. }
  9346. if (!makeItUnique) {
  9347. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  9348. } else {
  9349. this.makeGeometryUnique();
  9350. this.updateVerticesDataDirectly(kind, data, offset, false);
  9351. }
  9352. };
  9353. Mesh.prototype.makeGeometryUnique = function () {
  9354. if (!this._geometry) {
  9355. return;
  9356. }
  9357. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  9358. geometry.applyToMesh(this);
  9359. };
  9360. Mesh.prototype.setIndices = function (indices, totalVertices) {
  9361. if (!this._geometry) {
  9362. var vertexData = new BABYLON.VertexData();
  9363. vertexData.indices = indices;
  9364. var scene = this.getScene();
  9365. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  9366. } else {
  9367. this._geometry.setIndices(indices, totalVertices);
  9368. }
  9369. };
  9370. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  9371. var engine = this.getScene().getEngine();
  9372. // Wireframe
  9373. var indexToBind;
  9374. switch (fillMode) {
  9375. case BABYLON.Material.PointFillMode:
  9376. indexToBind = null;
  9377. break;
  9378. case BABYLON.Material.WireFrameFillMode:
  9379. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  9380. break;
  9381. default:
  9382. case BABYLON.Material.TriangleFillMode:
  9383. indexToBind = this._geometry.getIndexBuffer();
  9384. break;
  9385. }
  9386. // VBOs
  9387. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  9388. };
  9389. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  9390. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  9391. return;
  9392. }
  9393. var engine = this.getScene().getEngine();
  9394. switch (fillMode) {
  9395. case BABYLON.Material.PointFillMode:
  9396. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  9397. break;
  9398. case BABYLON.Material.WireFrameFillMode:
  9399. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  9400. break;
  9401. default:
  9402. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  9403. }
  9404. };
  9405. Mesh.prototype.registerBeforeRender = function (func) {
  9406. this._onBeforeRenderCallbacks.push(func);
  9407. };
  9408. Mesh.prototype.unregisterBeforeRender = function (func) {
  9409. var index = this._onBeforeRenderCallbacks.indexOf(func);
  9410. if (index > -1) {
  9411. this._onBeforeRenderCallbacks.splice(index, 1);
  9412. }
  9413. };
  9414. Mesh.prototype.registerAfterRender = function (func) {
  9415. this._onAfterRenderCallbacks.push(func);
  9416. };
  9417. Mesh.prototype.unregisterAfterRender = function (func) {
  9418. var index = this._onAfterRenderCallbacks.indexOf(func);
  9419. if (index > -1) {
  9420. this._onAfterRenderCallbacks.splice(index, 1);
  9421. }
  9422. };
  9423. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  9424. var scene = this.getScene();
  9425. this._batchCache.mustReturn = false;
  9426. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  9427. this._batchCache.visibleInstances[subMeshId] = null;
  9428. if (this._visibleInstances) {
  9429. var currentRenderId = scene.getRenderId();
  9430. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  9431. var selfRenderId = this._renderId;
  9432. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  9433. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  9434. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  9435. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  9436. }
  9437. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  9438. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  9439. this._batchCache.mustReturn = true;
  9440. return this._batchCache;
  9441. }
  9442. if (currentRenderId !== selfRenderId) {
  9443. this._batchCache.renderSelf[subMeshId] = false;
  9444. }
  9445. }
  9446. this._renderIdForInstances[subMeshId] = currentRenderId;
  9447. }
  9448. return this._batchCache;
  9449. };
  9450. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  9451. var visibleInstances = batch.visibleInstances[subMesh._id];
  9452. var matricesCount = visibleInstances.length + 1;
  9453. var bufferSize = matricesCount * 16 * 4;
  9454. while (this._instancesBufferSize < bufferSize) {
  9455. this._instancesBufferSize *= 2;
  9456. }
  9457. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  9458. if (this._worldMatricesInstancesBuffer) {
  9459. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  9460. }
  9461. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  9462. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  9463. }
  9464. var offset = 0;
  9465. var instancesCount = 0;
  9466. var world = this.getWorldMatrix();
  9467. if (batch.renderSelf[subMesh._id]) {
  9468. world.copyToArray(this._worldMatricesInstancesArray, offset);
  9469. offset += 16;
  9470. instancesCount++;
  9471. }
  9472. if (visibleInstances) {
  9473. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  9474. var instance = visibleInstances[instanceIndex];
  9475. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  9476. offset += 16;
  9477. instancesCount++;
  9478. }
  9479. }
  9480. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  9481. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  9482. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  9483. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  9484. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  9485. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  9486. this._draw(subMesh, fillMode, instancesCount);
  9487. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  9488. };
  9489. Mesh.prototype.render = function (subMesh) {
  9490. var scene = this.getScene();
  9491. // Managing instances
  9492. var batch = this._getInstancesRenderList(subMesh._id);
  9493. if (batch.mustReturn) {
  9494. return;
  9495. }
  9496. // Checking geometry state
  9497. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  9498. return;
  9499. }
  9500. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  9501. this._onBeforeRenderCallbacks[callbackIndex]();
  9502. }
  9503. var engine = scene.getEngine();
  9504. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  9505. // Material
  9506. var effectiveMaterial = subMesh.getMaterial();
  9507. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  9508. return;
  9509. }
  9510. // Outline - step 1
  9511. var savedDepthWrite = engine.getDepthWrite();
  9512. if (this.renderOutline) {
  9513. engine.setDepthWrite(false);
  9514. scene.getOutlineRenderer().render(subMesh, batch);
  9515. engine.setDepthWrite(savedDepthWrite);
  9516. }
  9517. effectiveMaterial._preBind();
  9518. var effect = effectiveMaterial.getEffect();
  9519. // Bind
  9520. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  9521. this._bind(subMesh, effect, fillMode);
  9522. var world = this.getWorldMatrix();
  9523. effectiveMaterial.bind(world, this);
  9524. // Instances rendering
  9525. if (hardwareInstancedRendering) {
  9526. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  9527. } else {
  9528. if (batch.renderSelf[subMesh._id]) {
  9529. // Draw
  9530. this._draw(subMesh, fillMode);
  9531. }
  9532. if (batch.visibleInstances[subMesh._id]) {
  9533. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  9534. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  9535. // World
  9536. world = instance.getWorldMatrix();
  9537. effectiveMaterial.bindOnlyWorldMatrix(world);
  9538. // Draw
  9539. this._draw(subMesh, fillMode);
  9540. }
  9541. }
  9542. }
  9543. // Unbind
  9544. effectiveMaterial.unbind();
  9545. // Outline - step 2
  9546. if (this.renderOutline && savedDepthWrite) {
  9547. engine.setDepthWrite(true);
  9548. engine.setColorWrite(false);
  9549. scene.getOutlineRenderer().render(subMesh, batch);
  9550. engine.setColorWrite(true);
  9551. }
  9552. // Overlay
  9553. if (this.renderOverlay) {
  9554. var currentMode = engine.getAlphaMode();
  9555. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  9556. scene.getOutlineRenderer().render(subMesh, batch, true);
  9557. engine.setAlphaMode(currentMode);
  9558. }
  9559. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  9560. this._onAfterRenderCallbacks[callbackIndex]();
  9561. }
  9562. };
  9563. Mesh.prototype.getEmittedParticleSystems = function () {
  9564. var results = new Array();
  9565. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  9566. var particleSystem = this.getScene().particleSystems[index];
  9567. if (particleSystem.emitter === this) {
  9568. results.push(particleSystem);
  9569. }
  9570. }
  9571. return results;
  9572. };
  9573. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  9574. var results = new Array();
  9575. var descendants = this.getDescendants();
  9576. descendants.push(this);
  9577. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  9578. var particleSystem = this.getScene().particleSystems[index];
  9579. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  9580. results.push(particleSystem);
  9581. }
  9582. }
  9583. return results;
  9584. };
  9585. Mesh.prototype.getChildren = function () {
  9586. var results = [];
  9587. for (var index = 0; index < this.getScene().meshes.length; index++) {
  9588. var mesh = this.getScene().meshes[index];
  9589. if (mesh.parent == this) {
  9590. results.push(mesh);
  9591. }
  9592. }
  9593. return results;
  9594. };
  9595. Mesh.prototype._checkDelayState = function () {
  9596. var _this = this;
  9597. var that = this;
  9598. var scene = this.getScene();
  9599. if (this._geometry) {
  9600. this._geometry.load(scene);
  9601. } else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  9602. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  9603. scene._addPendingData(that);
  9604. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1) ? true : false;
  9605. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  9606. if (data instanceof ArrayBuffer) {
  9607. _this._delayLoadingFunction(data, _this);
  9608. } else {
  9609. _this._delayLoadingFunction(JSON.parse(data), _this);
  9610. }
  9611. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  9612. scene._removePendingData(_this);
  9613. }, function () {
  9614. }, scene.database, getBinaryData);
  9615. }
  9616. };
  9617. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  9618. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  9619. return false;
  9620. }
  9621. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  9622. return false;
  9623. }
  9624. this._checkDelayState();
  9625. return true;
  9626. };
  9627. Mesh.prototype.setMaterialByID = function (id) {
  9628. var materials = this.getScene().materials;
  9629. for (var index = 0; index < materials.length; index++) {
  9630. if (materials[index].id == id) {
  9631. this.material = materials[index];
  9632. return;
  9633. }
  9634. }
  9635. // Multi
  9636. var multiMaterials = this.getScene().multiMaterials;
  9637. for (index = 0; index < multiMaterials.length; index++) {
  9638. if (multiMaterials[index].id == id) {
  9639. this.material = multiMaterials[index];
  9640. return;
  9641. }
  9642. }
  9643. };
  9644. Mesh.prototype.getAnimatables = function () {
  9645. var results = [];
  9646. if (this.material) {
  9647. results.push(this.material);
  9648. }
  9649. if (this.skeleton) {
  9650. results.push(this.skeleton);
  9651. }
  9652. return results;
  9653. };
  9654. // Geometry
  9655. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  9656. // Position
  9657. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  9658. return;
  9659. }
  9660. this._resetPointsArrayCache();
  9661. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  9662. var temp = [];
  9663. for (var index = 0; index < data.length; index += 3) {
  9664. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  9665. }
  9666. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  9667. // Normals
  9668. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  9669. return;
  9670. }
  9671. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  9672. for (index = 0; index < data.length; index += 3) {
  9673. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  9674. }
  9675. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  9676. };
  9677. // Cache
  9678. Mesh.prototype._resetPointsArrayCache = function () {
  9679. this._positions = null;
  9680. };
  9681. Mesh.prototype._generatePointsArray = function () {
  9682. if (this._positions)
  9683. return true;
  9684. this._positions = [];
  9685. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  9686. if (!data) {
  9687. return false;
  9688. }
  9689. for (var index = 0; index < data.length; index += 3) {
  9690. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  9691. }
  9692. return true;
  9693. };
  9694. // Clone
  9695. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  9696. return new BABYLON.Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  9697. };
  9698. // Dispose
  9699. Mesh.prototype.dispose = function (doNotRecurse) {
  9700. if (this._geometry) {
  9701. this._geometry.releaseForMesh(this, true);
  9702. }
  9703. // Instances
  9704. if (this._worldMatricesInstancesBuffer) {
  9705. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  9706. this._worldMatricesInstancesBuffer = null;
  9707. }
  9708. while (this.instances.length) {
  9709. this.instances[0].dispose();
  9710. }
  9711. _super.prototype.dispose.call(this, doNotRecurse);
  9712. };
  9713. // Geometric tools
  9714. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight) {
  9715. var _this = this;
  9716. var scene = this.getScene();
  9717. var onload = function (img) {
  9718. // Getting height map data
  9719. var canvas = document.createElement("canvas");
  9720. var context = canvas.getContext("2d");
  9721. var heightMapWidth = img.width;
  9722. var heightMapHeight = img.height;
  9723. canvas.width = heightMapWidth;
  9724. canvas.height = heightMapHeight;
  9725. context.drawImage(img, 0, 0);
  9726. // Create VertexData from map data
  9727. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  9728. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  9729. };
  9730. BABYLON.Tools.LoadImage(url, onload, function () {
  9731. }, scene.database);
  9732. };
  9733. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  9734. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  9735. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  9736. return;
  9737. }
  9738. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  9739. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  9740. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  9741. var position = BABYLON.Vector3.Zero();
  9742. var normal = BABYLON.Vector3.Zero();
  9743. var uv = BABYLON.Vector2.Zero();
  9744. for (var index = 0; index < positions.length; index += 3) {
  9745. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  9746. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  9747. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  9748. // Compute height
  9749. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  9750. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  9751. var pos = (u + v * heightMapWidth) * 4;
  9752. var r = buffer[pos] / 255.0;
  9753. var g = buffer[pos + 1] / 255.0;
  9754. var b = buffer[pos + 2] / 255.0;
  9755. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  9756. normal.normalize();
  9757. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  9758. position = position.add(normal);
  9759. position.toArray(positions, index);
  9760. }
  9761. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  9762. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  9763. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  9764. };
  9765. Mesh.prototype.convertToFlatShadedMesh = function () {
  9766. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  9767. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  9768. var kinds = this.getVerticesDataKinds();
  9769. var vbs = [];
  9770. var data = [];
  9771. var newdata = [];
  9772. var updatableNormals = false;
  9773. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  9774. var kind = kinds[kindIndex];
  9775. var vertexBuffer = this.getVertexBuffer(kind);
  9776. if (kind === BABYLON.VertexBuffer.NormalKind) {
  9777. updatableNormals = vertexBuffer.isUpdatable();
  9778. kinds.splice(kindIndex, 1);
  9779. kindIndex--;
  9780. continue;
  9781. }
  9782. vbs[kind] = vertexBuffer;
  9783. data[kind] = vbs[kind].getData();
  9784. newdata[kind] = [];
  9785. }
  9786. // Save previous submeshes
  9787. var previousSubmeshes = this.subMeshes.slice(0);
  9788. var indices = this.getIndices();
  9789. var totalIndices = this.getTotalIndices();
  9790. for (index = 0; index < totalIndices; index++) {
  9791. var vertexIndex = indices[index];
  9792. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  9793. kind = kinds[kindIndex];
  9794. var stride = vbs[kind].getStrideSize();
  9795. for (var offset = 0; offset < stride; offset++) {
  9796. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  9797. }
  9798. }
  9799. }
  9800. // Updating faces & normal
  9801. var normals = [];
  9802. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  9803. for (var index = 0; index < totalIndices; index += 3) {
  9804. indices[index] = index;
  9805. indices[index + 1] = index + 1;
  9806. indices[index + 2] = index + 2;
  9807. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  9808. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  9809. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  9810. var p1p2 = p1.subtract(p2);
  9811. var p3p2 = p3.subtract(p2);
  9812. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  9813. for (var localIndex = 0; localIndex < 3; localIndex++) {
  9814. normals.push(normal.x);
  9815. normals.push(normal.y);
  9816. normals.push(normal.z);
  9817. }
  9818. }
  9819. this.setIndices(indices);
  9820. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  9821. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  9822. kind = kinds[kindIndex];
  9823. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  9824. }
  9825. // Updating submeshes
  9826. this.releaseSubMeshes();
  9827. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  9828. var previousOne = previousSubmeshes[submeshIndex];
  9829. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  9830. }
  9831. this.synchronizeInstances();
  9832. };
  9833. // Instances
  9834. Mesh.prototype.createInstance = function (name) {
  9835. return new BABYLON.InstancedMesh(name, this);
  9836. };
  9837. Mesh.prototype.synchronizeInstances = function () {
  9838. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  9839. var instance = this.instances[instanceIndex];
  9840. instance._syncSubMeshes();
  9841. }
  9842. };
  9843. // Statics
  9844. Mesh.CreateBox = function (name, size, scene, updatable) {
  9845. var box = new BABYLON.Mesh(name, scene);
  9846. var vertexData = BABYLON.VertexData.CreateBox(size);
  9847. vertexData.applyToMesh(box, updatable);
  9848. return box;
  9849. };
  9850. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable) {
  9851. var sphere = new BABYLON.Mesh(name, scene);
  9852. var vertexData = BABYLON.VertexData.CreateSphere(segments, diameter);
  9853. vertexData.applyToMesh(sphere, updatable);
  9854. return sphere;
  9855. };
  9856. // Cylinder and cone (Code inspired by SharpDX.org)
  9857. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable) {
  9858. // subdivisions is a new parameter, we need to support old signature
  9859. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  9860. if (scene !== undefined) {
  9861. updatable = scene;
  9862. }
  9863. scene = subdivisions;
  9864. subdivisions = 1;
  9865. }
  9866. var cylinder = new BABYLON.Mesh(name, scene);
  9867. var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions);
  9868. vertexData.applyToMesh(cylinder, updatable);
  9869. return cylinder;
  9870. };
  9871. // Torus (Code from SharpDX.org)
  9872. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable) {
  9873. var torus = new BABYLON.Mesh(name, scene);
  9874. var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation);
  9875. vertexData.applyToMesh(torus, updatable);
  9876. return torus;
  9877. };
  9878. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable) {
  9879. var torusKnot = new BABYLON.Mesh(name, scene);
  9880. var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q);
  9881. vertexData.applyToMesh(torusKnot, updatable);
  9882. return torusKnot;
  9883. };
  9884. // Lines
  9885. Mesh.CreateLines = function (name, points, scene, updatable) {
  9886. var lines = new BABYLON.LinesMesh(name, scene, updatable);
  9887. var vertexData = BABYLON.VertexData.CreateLines(points);
  9888. vertexData.applyToMesh(lines, updatable);
  9889. return lines;
  9890. };
  9891. // Plane & ground
  9892. Mesh.CreatePlane = function (name, size, scene, updatable) {
  9893. var plane = new BABYLON.Mesh(name, scene);
  9894. var vertexData = BABYLON.VertexData.CreatePlane(size);
  9895. vertexData.applyToMesh(plane, updatable);
  9896. return plane;
  9897. };
  9898. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  9899. var ground = new BABYLON.GroundMesh(name, scene);
  9900. ground._setReady(false);
  9901. ground._subdivisions = subdivisions;
  9902. var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
  9903. vertexData.applyToMesh(ground, updatable);
  9904. ground._setReady(true);
  9905. return ground;
  9906. };
  9907. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  9908. var tiledGround = new BABYLON.Mesh(name, scene);
  9909. var vertexData = BABYLON.VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  9910. vertexData.applyToMesh(tiledGround, updatable);
  9911. return tiledGround;
  9912. };
  9913. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable) {
  9914. var ground = new BABYLON.GroundMesh(name, scene);
  9915. ground._subdivisions = subdivisions;
  9916. ground._setReady(false);
  9917. var onload = function (img) {
  9918. // Getting height map data
  9919. var canvas = document.createElement("canvas");
  9920. var context = canvas.getContext("2d");
  9921. var heightMapWidth = img.width;
  9922. var heightMapHeight = img.height;
  9923. canvas.width = heightMapWidth;
  9924. canvas.height = heightMapHeight;
  9925. context.drawImage(img, 0, 0);
  9926. // Create VertexData from map data
  9927. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  9928. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  9929. vertexData.applyToMesh(ground, updatable);
  9930. ground._setReady(true);
  9931. };
  9932. BABYLON.Tools.LoadImage(url, onload, function () {
  9933. }, scene.database);
  9934. return ground;
  9935. };
  9936. // Tools
  9937. Mesh.MinMax = function (meshes) {
  9938. var minVector = null;
  9939. var maxVector = null;
  9940. for (var i in meshes) {
  9941. var mesh = meshes[i];
  9942. var boundingBox = mesh.getBoundingInfo().boundingBox;
  9943. if (!minVector) {
  9944. minVector = boundingBox.minimumWorld;
  9945. maxVector = boundingBox.maximumWorld;
  9946. continue;
  9947. }
  9948. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  9949. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  9950. }
  9951. return {
  9952. min: minVector,
  9953. max: maxVector
  9954. };
  9955. };
  9956. Mesh.Center = function (meshesOrMinMaxVector) {
  9957. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  9958. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  9959. };
  9960. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices) {
  9961. if (typeof disposeSource === "undefined") { disposeSource = true; }
  9962. var source = meshes[0];
  9963. var material = source.material;
  9964. var scene = source.getScene();
  9965. if (!allow32BitsIndices) {
  9966. var totalVertices = 0;
  9967. for (var index = 0; index < meshes.length; index++) {
  9968. totalVertices += meshes[index].getTotalVertices();
  9969. if (totalVertices > 65536) {
  9970. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  9971. return null;
  9972. }
  9973. }
  9974. }
  9975. // Merge
  9976. var vertexData = BABYLON.VertexData.ExtractFromMesh(source);
  9977. vertexData.transform(source.getWorldMatrix());
  9978. for (index = 1; index < meshes.length; index++) {
  9979. var otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index]);
  9980. otherVertexData.transform(meshes[index].getWorldMatrix());
  9981. vertexData.merge(otherVertexData);
  9982. }
  9983. var newMesh = new Mesh(source.name + "_merged", scene);
  9984. vertexData.applyToMesh(newMesh);
  9985. // Setting properties
  9986. newMesh.material = material;
  9987. newMesh.checkCollisions = source.checkCollisions;
  9988. // Cleaning
  9989. if (disposeSource) {
  9990. for (index = 0; index < meshes.length; index++) {
  9991. meshes[index].dispose();
  9992. }
  9993. }
  9994. return newMesh;
  9995. };
  9996. return Mesh;
  9997. })(BABYLON.AbstractMesh);
  9998. BABYLON.Mesh = Mesh;
  9999. })(BABYLON || (BABYLON = {}));
  10000. //# sourceMappingURL=babylon.mesh.js.map
  10001. var BABYLON;
  10002. (function (BABYLON) {
  10003. var GroundMesh = (function (_super) {
  10004. __extends(GroundMesh, _super);
  10005. function GroundMesh(name, scene) {
  10006. _super.call(this, name, scene);
  10007. this.generateOctree = false;
  10008. this._worldInverse = new BABYLON.Matrix();
  10009. }
  10010. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  10011. get: function () {
  10012. return this._subdivisions;
  10013. },
  10014. enumerable: true,
  10015. configurable: true
  10016. });
  10017. GroundMesh.prototype.optimize = function (chunksCount) {
  10018. this.subdivide(this._subdivisions);
  10019. this.createOrUpdateSubmeshesOctree(32);
  10020. };
  10021. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  10022. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  10023. this.getWorldMatrix().invertToRef(this._worldInverse);
  10024. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  10025. var pickInfo = this.intersects(ray);
  10026. if (pickInfo.hit) {
  10027. return pickInfo.pickedPoint.y;
  10028. }
  10029. return 0;
  10030. };
  10031. return GroundMesh;
  10032. })(BABYLON.Mesh);
  10033. BABYLON.GroundMesh = GroundMesh;
  10034. })(BABYLON || (BABYLON = {}));
  10035. //# sourceMappingURL=babylon.groundMesh.js.map
  10036. var BABYLON;
  10037. (function (BABYLON) {
  10038. var InstancedMesh = (function (_super) {
  10039. __extends(InstancedMesh, _super);
  10040. function InstancedMesh(name, source) {
  10041. _super.call(this, name, source.getScene());
  10042. source.instances.push(this);
  10043. this._sourceMesh = source;
  10044. this.position.copyFrom(source.position);
  10045. this.rotation.copyFrom(source.rotation);
  10046. this.scaling.copyFrom(source.scaling);
  10047. if (source.rotationQuaternion) {
  10048. this.rotationQuaternion = source.rotationQuaternion.clone();
  10049. }
  10050. this.infiniteDistance = source.infiniteDistance;
  10051. this.setPivotMatrix(source.getPivotMatrix());
  10052. this.refreshBoundingInfo();
  10053. this._syncSubMeshes();
  10054. }
  10055. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  10056. // Methods
  10057. get: function () {
  10058. return this._sourceMesh.receiveShadows;
  10059. },
  10060. enumerable: true,
  10061. configurable: true
  10062. });
  10063. Object.defineProperty(InstancedMesh.prototype, "material", {
  10064. get: function () {
  10065. return this._sourceMesh.material;
  10066. },
  10067. enumerable: true,
  10068. configurable: true
  10069. });
  10070. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  10071. get: function () {
  10072. return this._sourceMesh.visibility;
  10073. },
  10074. enumerable: true,
  10075. configurable: true
  10076. });
  10077. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  10078. get: function () {
  10079. return this._sourceMesh.skeleton;
  10080. },
  10081. enumerable: true,
  10082. configurable: true
  10083. });
  10084. InstancedMesh.prototype.getTotalVertices = function () {
  10085. return this._sourceMesh.getTotalVertices();
  10086. };
  10087. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  10088. get: function () {
  10089. return this._sourceMesh;
  10090. },
  10091. enumerable: true,
  10092. configurable: true
  10093. });
  10094. InstancedMesh.prototype.getVerticesData = function (kind) {
  10095. return this._sourceMesh.getVerticesData(kind);
  10096. };
  10097. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  10098. return this._sourceMesh.isVerticesDataPresent(kind);
  10099. };
  10100. InstancedMesh.prototype.getIndices = function () {
  10101. return this._sourceMesh.getIndices();
  10102. };
  10103. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  10104. get: function () {
  10105. return this._sourceMesh._positions;
  10106. },
  10107. enumerable: true,
  10108. configurable: true
  10109. });
  10110. InstancedMesh.prototype.refreshBoundingInfo = function () {
  10111. var data = this._sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  10112. if (data) {
  10113. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._sourceMesh.getTotalVertices());
  10114. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  10115. }
  10116. this._updateBoundingInfo();
  10117. };
  10118. InstancedMesh.prototype._preActivate = function () {
  10119. if (this._currentLOD) {
  10120. this._currentLOD._preActivate();
  10121. }
  10122. };
  10123. InstancedMesh.prototype._activate = function (renderId) {
  10124. if (this._currentLOD) {
  10125. this._currentLOD._registerInstanceForRenderId(this, renderId);
  10126. }
  10127. };
  10128. InstancedMesh.prototype.getLOD = function (camera) {
  10129. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  10130. return this._currentLOD;
  10131. };
  10132. InstancedMesh.prototype._syncSubMeshes = function () {
  10133. this.releaseSubMeshes();
  10134. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  10135. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  10136. }
  10137. };
  10138. InstancedMesh.prototype._generatePointsArray = function () {
  10139. return this._sourceMesh._generatePointsArray();
  10140. };
  10141. // Clone
  10142. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  10143. var result = this._sourceMesh.createInstance(name);
  10144. // Deep copy
  10145. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  10146. // Bounding info
  10147. this.refreshBoundingInfo();
  10148. // Parent
  10149. if (newParent) {
  10150. result.parent = newParent;
  10151. }
  10152. if (!doNotCloneChildren) {
  10153. for (var index = 0; index < this.getScene().meshes.length; index++) {
  10154. var mesh = this.getScene().meshes[index];
  10155. if (mesh.parent == this) {
  10156. mesh.clone(mesh.name, result);
  10157. }
  10158. }
  10159. }
  10160. result.computeWorldMatrix(true);
  10161. return result;
  10162. };
  10163. // Dispoe
  10164. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  10165. // Remove from mesh
  10166. var index = this._sourceMesh.instances.indexOf(this);
  10167. this._sourceMesh.instances.splice(index, 1);
  10168. _super.prototype.dispose.call(this, doNotRecurse);
  10169. };
  10170. return InstancedMesh;
  10171. })(BABYLON.AbstractMesh);
  10172. BABYLON.InstancedMesh = InstancedMesh;
  10173. })(BABYLON || (BABYLON = {}));
  10174. //# sourceMappingURL=babylon.instancedMesh.js.map
  10175. var BABYLON;
  10176. (function (BABYLON) {
  10177. var SubMesh = (function () {
  10178. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  10179. if (typeof createBoundingBox === "undefined") { createBoundingBox = true; }
  10180. this.materialIndex = materialIndex;
  10181. this.verticesStart = verticesStart;
  10182. this.verticesCount = verticesCount;
  10183. this.indexStart = indexStart;
  10184. this.indexCount = indexCount;
  10185. this._renderId = 0;
  10186. this._mesh = mesh;
  10187. this._renderingMesh = renderingMesh || mesh;
  10188. mesh.subMeshes.push(this);
  10189. this._id = mesh.subMeshes.length - 1;
  10190. if (createBoundingBox) {
  10191. this.refreshBoundingInfo();
  10192. }
  10193. }
  10194. SubMesh.prototype.getBoundingInfo = function () {
  10195. return this._boundingInfo;
  10196. };
  10197. SubMesh.prototype.getMesh = function () {
  10198. return this._mesh;
  10199. };
  10200. SubMesh.prototype.getRenderingMesh = function () {
  10201. return this._renderingMesh;
  10202. };
  10203. SubMesh.prototype.getMaterial = function () {
  10204. var rootMaterial = this._renderingMesh.material;
  10205. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  10206. var multiMaterial = rootMaterial;
  10207. return multiMaterial.getSubMaterial(this.materialIndex);
  10208. }
  10209. if (!rootMaterial) {
  10210. return this._mesh.getScene().defaultMaterial;
  10211. }
  10212. return rootMaterial;
  10213. };
  10214. // Methods
  10215. SubMesh.prototype.refreshBoundingInfo = function () {
  10216. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  10217. if (!data) {
  10218. this._boundingInfo = this._mesh._boundingInfo;
  10219. return;
  10220. }
  10221. var indices = this._renderingMesh.getIndices();
  10222. var extend;
  10223. if (this.indexStart === 0 && this.indexCount === indices.length) {
  10224. extend = BABYLON.Tools.ExtractMinAndMax(data, this.verticesStart, this.verticesCount);
  10225. } else {
  10226. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  10227. }
  10228. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  10229. };
  10230. SubMesh.prototype._checkCollision = function (collider) {
  10231. return this._boundingInfo._checkCollision(collider);
  10232. };
  10233. SubMesh.prototype.updateBoundingInfo = function (world) {
  10234. if (!this._boundingInfo) {
  10235. this.refreshBoundingInfo();
  10236. }
  10237. this._boundingInfo._update(world);
  10238. };
  10239. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  10240. return this._boundingInfo.isInFrustum(frustumPlanes);
  10241. };
  10242. SubMesh.prototype.render = function () {
  10243. this._renderingMesh.render(this);
  10244. };
  10245. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  10246. if (!this._linesIndexBuffer) {
  10247. var linesIndices = [];
  10248. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  10249. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  10250. }
  10251. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  10252. this.linesIndexCount = linesIndices.length;
  10253. }
  10254. return this._linesIndexBuffer;
  10255. };
  10256. SubMesh.prototype.canIntersects = function (ray) {
  10257. return ray.intersectsBox(this._boundingInfo.boundingBox);
  10258. };
  10259. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  10260. var intersectInfo = null;
  10261. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  10262. var p0 = positions[indices[index]];
  10263. var p1 = positions[indices[index + 1]];
  10264. var p2 = positions[indices[index + 2]];
  10265. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  10266. if (currentIntersectInfo) {
  10267. if (currentIntersectInfo.distance < 0) {
  10268. continue;
  10269. }
  10270. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  10271. intersectInfo = currentIntersectInfo;
  10272. intersectInfo.faceId = index / 3;
  10273. if (fastCheck) {
  10274. break;
  10275. }
  10276. }
  10277. }
  10278. }
  10279. return intersectInfo;
  10280. };
  10281. // Clone
  10282. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  10283. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  10284. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  10285. return result;
  10286. };
  10287. // Dispose
  10288. SubMesh.prototype.dispose = function () {
  10289. if (this._linesIndexBuffer) {
  10290. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  10291. this._linesIndexBuffer = null;
  10292. }
  10293. // Remove from mesh
  10294. var index = this._mesh.subMeshes.indexOf(this);
  10295. this._mesh.subMeshes.splice(index, 1);
  10296. };
  10297. // Statics
  10298. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  10299. var minVertexIndex = Number.MAX_VALUE;
  10300. var maxVertexIndex = -Number.MAX_VALUE;
  10301. renderingMesh = renderingMesh || mesh;
  10302. var indices = renderingMesh.getIndices();
  10303. for (var index = startIndex; index < startIndex + indexCount; index++) {
  10304. var vertexIndex = indices[index];
  10305. if (vertexIndex < minVertexIndex)
  10306. minVertexIndex = vertexIndex;
  10307. if (vertexIndex > maxVertexIndex)
  10308. maxVertexIndex = vertexIndex;
  10309. }
  10310. return new BABYLON.SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  10311. };
  10312. return SubMesh;
  10313. })();
  10314. BABYLON.SubMesh = SubMesh;
  10315. })(BABYLON || (BABYLON = {}));
  10316. //# sourceMappingURL=babylon.subMesh.js.map
  10317. var BABYLON;
  10318. (function (BABYLON) {
  10319. var BaseTexture = (function () {
  10320. function BaseTexture(scene) {
  10321. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  10322. this.hasAlpha = false;
  10323. this.getAlphaFromRGB = false;
  10324. this.level = 1;
  10325. this.isCube = false;
  10326. this.isRenderTarget = false;
  10327. this.animations = new Array();
  10328. this.coordinatesIndex = 0;
  10329. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  10330. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  10331. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  10332. this.anisotropicFilteringLevel = 4;
  10333. this._scene = scene;
  10334. this._scene.textures.push(this);
  10335. }
  10336. BaseTexture.prototype.getScene = function () {
  10337. return this._scene;
  10338. };
  10339. BaseTexture.prototype.getTextureMatrix = function () {
  10340. return null;
  10341. };
  10342. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  10343. return null;
  10344. };
  10345. BaseTexture.prototype.getInternalTexture = function () {
  10346. return this._texture;
  10347. };
  10348. BaseTexture.prototype.isReady = function () {
  10349. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  10350. return true;
  10351. }
  10352. if (this._texture) {
  10353. return this._texture.isReady;
  10354. }
  10355. return false;
  10356. };
  10357. BaseTexture.prototype.getSize = function () {
  10358. if (this._texture._width) {
  10359. return { width: this._texture._width, height: this._texture._height };
  10360. }
  10361. if (this._texture._size) {
  10362. return { width: this._texture._size, height: this._texture._size };
  10363. }
  10364. return { width: 0, height: 0 };
  10365. };
  10366. BaseTexture.prototype.getBaseSize = function () {
  10367. if (!this.isReady())
  10368. return { width: 0, height: 0 };
  10369. if (this._texture._size) {
  10370. return { width: this._texture._size, height: this._texture._size };
  10371. }
  10372. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  10373. };
  10374. BaseTexture.prototype.scale = function (ratio) {
  10375. };
  10376. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  10377. get: function () {
  10378. return false;
  10379. },
  10380. enumerable: true,
  10381. configurable: true
  10382. });
  10383. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  10384. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  10385. for (var index = 0; index < texturesCache.length; index++) {
  10386. var texturesCacheEntry = texturesCache[index];
  10387. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  10388. texturesCache.splice(index, 1);
  10389. return;
  10390. }
  10391. }
  10392. };
  10393. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  10394. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  10395. for (var index = 0; index < texturesCache.length; index++) {
  10396. var texturesCacheEntry = texturesCache[index];
  10397. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  10398. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  10399. texturesCacheEntry.references++;
  10400. return texturesCacheEntry;
  10401. }
  10402. }
  10403. }
  10404. return null;
  10405. };
  10406. BaseTexture.prototype.delayLoad = function () {
  10407. };
  10408. BaseTexture.prototype.releaseInternalTexture = function () {
  10409. if (!this._texture) {
  10410. return;
  10411. }
  10412. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  10413. this._texture.references--;
  10414. // Final reference ?
  10415. if (this._texture.references === 0) {
  10416. var index = texturesCache.indexOf(this._texture);
  10417. texturesCache.splice(index, 1);
  10418. this._scene.getEngine()._releaseTexture(this._texture);
  10419. delete this._texture;
  10420. }
  10421. };
  10422. BaseTexture.prototype.clone = function () {
  10423. return null;
  10424. };
  10425. BaseTexture.prototype.dispose = function () {
  10426. // Remove from scene
  10427. var index = this._scene.textures.indexOf(this);
  10428. if (index >= 0) {
  10429. this._scene.textures.splice(index, 1);
  10430. }
  10431. if (this._texture === undefined) {
  10432. return;
  10433. }
  10434. this.releaseInternalTexture();
  10435. // Callback
  10436. if (this.onDispose) {
  10437. this.onDispose();
  10438. }
  10439. };
  10440. return BaseTexture;
  10441. })();
  10442. BABYLON.BaseTexture = BaseTexture;
  10443. })(BABYLON || (BABYLON = {}));
  10444. //# sourceMappingURL=babylon.baseTexture.js.map
  10445. var BABYLON;
  10446. (function (BABYLON) {
  10447. var RenderingGroup = (function () {
  10448. function RenderingGroup(index, scene) {
  10449. this.index = index;
  10450. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  10451. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  10452. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  10453. this._scene = scene;
  10454. }
  10455. RenderingGroup.prototype.render = function (customRenderFunction) {
  10456. if (customRenderFunction) {
  10457. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  10458. return true;
  10459. }
  10460. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  10461. return false;
  10462. }
  10463. var engine = this._scene.getEngine();
  10464. // Opaque
  10465. var subIndex;
  10466. var submesh;
  10467. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  10468. submesh = this._opaqueSubMeshes.data[subIndex];
  10469. submesh.render();
  10470. }
  10471. // Alpha test
  10472. engine.setAlphaTesting(true);
  10473. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  10474. submesh = this._alphaTestSubMeshes.data[subIndex];
  10475. submesh.render();
  10476. }
  10477. engine.setAlphaTesting(false);
  10478. // Transparent
  10479. if (this._transparentSubMeshes.length) {
  10480. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  10481. submesh = this._transparentSubMeshes.data[subIndex];
  10482. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  10483. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.position).length();
  10484. }
  10485. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  10486. sortedArray.sort(function (a, b) {
  10487. // Alpha index first
  10488. if (a._alphaIndex > b._alphaIndex) {
  10489. return 1;
  10490. }
  10491. if (a._alphaIndex < b._alphaIndex) {
  10492. return -1;
  10493. }
  10494. // Then distance to camera
  10495. if (a._distanceToCamera < b._distanceToCamera) {
  10496. return 1;
  10497. }
  10498. if (a._distanceToCamera > b._distanceToCamera) {
  10499. return -1;
  10500. }
  10501. return 0;
  10502. });
  10503. // Rendering
  10504. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  10505. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  10506. submesh = sortedArray[subIndex];
  10507. submesh.render();
  10508. }
  10509. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  10510. }
  10511. return true;
  10512. };
  10513. RenderingGroup.prototype.prepare = function () {
  10514. this._opaqueSubMeshes.reset();
  10515. this._transparentSubMeshes.reset();
  10516. this._alphaTestSubMeshes.reset();
  10517. };
  10518. RenderingGroup.prototype.dispatch = function (subMesh) {
  10519. var material = subMesh.getMaterial();
  10520. var mesh = subMesh.getMesh();
  10521. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  10522. this._transparentSubMeshes.push(subMesh);
  10523. } else if (material.needAlphaTesting()) {
  10524. this._alphaTestSubMeshes.push(subMesh);
  10525. } else {
  10526. this._opaqueSubMeshes.push(subMesh); // Opaque
  10527. }
  10528. };
  10529. return RenderingGroup;
  10530. })();
  10531. BABYLON.RenderingGroup = RenderingGroup;
  10532. })(BABYLON || (BABYLON = {}));
  10533. //# sourceMappingURL=babylon.renderingGroup.js.map
  10534. var BABYLON;
  10535. (function (BABYLON) {
  10536. var RenderingManager = (function () {
  10537. function RenderingManager(scene) {
  10538. this._renderingGroups = new Array();
  10539. this._scene = scene;
  10540. }
  10541. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  10542. if (this._scene._activeParticleSystems.length === 0) {
  10543. return;
  10544. }
  10545. // Particles
  10546. var beforeParticlesDate = BABYLON.Tools.Now;
  10547. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  10548. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  10549. if (particleSystem.renderingGroupId !== index) {
  10550. continue;
  10551. }
  10552. this._clearDepthBuffer();
  10553. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  10554. this._scene._activeParticles += particleSystem.render();
  10555. }
  10556. }
  10557. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  10558. };
  10559. RenderingManager.prototype._renderSprites = function (index) {
  10560. if (this._scene.spriteManagers.length === 0) {
  10561. return;
  10562. }
  10563. // Sprites
  10564. var beforeSpritessDate = BABYLON.Tools.Now;
  10565. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  10566. var spriteManager = this._scene.spriteManagers[id];
  10567. if (spriteManager.renderingGroupId === index) {
  10568. this._clearDepthBuffer();
  10569. spriteManager.render();
  10570. }
  10571. }
  10572. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  10573. };
  10574. RenderingManager.prototype._clearDepthBuffer = function () {
  10575. if (this._depthBufferAlreadyCleaned) {
  10576. return;
  10577. }
  10578. this._scene.getEngine().clear(0, false, true);
  10579. this._depthBufferAlreadyCleaned = true;
  10580. };
  10581. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  10582. for (var index = 0; index < BABYLON.RenderingManager.MAX_RENDERINGGROUPS; index++) {
  10583. this._depthBufferAlreadyCleaned = false;
  10584. var renderingGroup = this._renderingGroups[index];
  10585. if (renderingGroup) {
  10586. this._clearDepthBuffer();
  10587. if (!renderingGroup.render(customRenderFunction)) {
  10588. this._renderingGroups.splice(index, 1);
  10589. }
  10590. }
  10591. this._renderSprites(index);
  10592. if (renderParticles) {
  10593. this._renderParticles(index, activeMeshes);
  10594. }
  10595. }
  10596. };
  10597. RenderingManager.prototype.reset = function () {
  10598. for (var index in this._renderingGroups) {
  10599. var renderingGroup = this._renderingGroups[index];
  10600. renderingGroup.prepare();
  10601. }
  10602. };
  10603. RenderingManager.prototype.dispatch = function (subMesh) {
  10604. var mesh = subMesh.getMesh();
  10605. var renderingGroupId = mesh.renderingGroupId || 0;
  10606. if (!this._renderingGroups[renderingGroupId]) {
  10607. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  10608. }
  10609. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  10610. };
  10611. RenderingManager.MAX_RENDERINGGROUPS = 4;
  10612. return RenderingManager;
  10613. })();
  10614. BABYLON.RenderingManager = RenderingManager;
  10615. })(BABYLON || (BABYLON = {}));
  10616. //# sourceMappingURL=babylon.renderingManager.js.map
  10617. var BABYLON;
  10618. (function (BABYLON) {
  10619. var Texture = (function (_super) {
  10620. __extends(Texture, _super);
  10621. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  10622. if (typeof samplingMode === "undefined") { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  10623. if (typeof onLoad === "undefined") { onLoad = null; }
  10624. if (typeof onError === "undefined") { onError = null; }
  10625. if (typeof buffer === "undefined") { buffer = null; }
  10626. if (typeof deleteBuffer === "undefined") { deleteBuffer = false; }
  10627. _super.call(this, scene);
  10628. this.uOffset = 0;
  10629. this.vOffset = 0;
  10630. this.uScale = 1.0;
  10631. this.vScale = 1.0;
  10632. this.uAng = 0;
  10633. this.vAng = 0;
  10634. this.wAng = 0;
  10635. this.name = url;
  10636. this.url = url;
  10637. this._noMipmap = noMipmap;
  10638. this._invertY = invertY;
  10639. this._samplingMode = samplingMode;
  10640. this._buffer = buffer;
  10641. this._deleteBuffer = deleteBuffer;
  10642. if (!url) {
  10643. return;
  10644. }
  10645. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  10646. if (!this._texture) {
  10647. if (!scene.useDelayedTextureLoading) {
  10648. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  10649. if (deleteBuffer) {
  10650. delete this._buffer;
  10651. }
  10652. } else {
  10653. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  10654. }
  10655. }
  10656. }
  10657. Texture.prototype.delayLoad = function () {
  10658. if (this.delayLoadState != BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  10659. return;
  10660. }
  10661. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  10662. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  10663. if (!this._texture) {
  10664. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  10665. if (this._deleteBuffer) {
  10666. delete this._buffer;
  10667. }
  10668. }
  10669. };
  10670. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  10671. x -= this.uOffset + 0.5;
  10672. y -= this.vOffset + 0.5;
  10673. z -= 0.5;
  10674. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  10675. t.x *= this.uScale;
  10676. t.y *= this.vScale;
  10677. t.x += 0.5;
  10678. t.y += 0.5;
  10679. t.z += 0.5;
  10680. };
  10681. Texture.prototype.getTextureMatrix = function () {
  10682. 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) {
  10683. return this._cachedTextureMatrix;
  10684. }
  10685. this._cachedUOffset = this.uOffset;
  10686. this._cachedVOffset = this.vOffset;
  10687. this._cachedUScale = this.uScale;
  10688. this._cachedVScale = this.vScale;
  10689. this._cachedUAng = this.uAng;
  10690. this._cachedVAng = this.vAng;
  10691. this._cachedWAng = this.wAng;
  10692. if (!this._cachedTextureMatrix) {
  10693. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  10694. this._rowGenerationMatrix = new BABYLON.Matrix();
  10695. this._t0 = BABYLON.Vector3.Zero();
  10696. this._t1 = BABYLON.Vector3.Zero();
  10697. this._t2 = BABYLON.Vector3.Zero();
  10698. }
  10699. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  10700. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  10701. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  10702. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  10703. this._t1.subtractInPlace(this._t0);
  10704. this._t2.subtractInPlace(this._t0);
  10705. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  10706. this._cachedTextureMatrix.m[0] = this._t1.x;
  10707. this._cachedTextureMatrix.m[1] = this._t1.y;
  10708. this._cachedTextureMatrix.m[2] = this._t1.z;
  10709. this._cachedTextureMatrix.m[4] = this._t2.x;
  10710. this._cachedTextureMatrix.m[5] = this._t2.y;
  10711. this._cachedTextureMatrix.m[6] = this._t2.z;
  10712. this._cachedTextureMatrix.m[8] = this._t0.x;
  10713. this._cachedTextureMatrix.m[9] = this._t0.y;
  10714. this._cachedTextureMatrix.m[10] = this._t0.z;
  10715. return this._cachedTextureMatrix;
  10716. };
  10717. Texture.prototype.getReflectionTextureMatrix = function () {
  10718. if (this.uOffset === this._cachedUOffset && this.vOffset === this._cachedVOffset && this.uScale === this._cachedUScale && this.vScale === this._cachedVScale && this.coordinatesMode === this._cachedCoordinatesMode) {
  10719. return this._cachedTextureMatrix;
  10720. }
  10721. if (!this._cachedTextureMatrix) {
  10722. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  10723. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  10724. }
  10725. this._cachedCoordinatesMode = this.coordinatesMode;
  10726. switch (this.coordinatesMode) {
  10727. case BABYLON.Texture.SPHERICAL_MODE:
  10728. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  10729. this._cachedTextureMatrix[0] = -0.5 * this.uScale;
  10730. this._cachedTextureMatrix[5] = -0.5 * this.vScale;
  10731. this._cachedTextureMatrix[12] = 0.5 + this.uOffset;
  10732. this._cachedTextureMatrix[13] = 0.5 + this.vOffset;
  10733. break;
  10734. case BABYLON.Texture.PLANAR_MODE:
  10735. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  10736. this._cachedTextureMatrix[0] = this.uScale;
  10737. this._cachedTextureMatrix[5] = this.vScale;
  10738. this._cachedTextureMatrix[12] = this.uOffset;
  10739. this._cachedTextureMatrix[13] = this.vOffset;
  10740. break;
  10741. case BABYLON.Texture.PROJECTION_MODE:
  10742. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  10743. this._projectionModeMatrix.m[0] = 0.5;
  10744. this._projectionModeMatrix.m[5] = -0.5;
  10745. this._projectionModeMatrix.m[10] = 0.0;
  10746. this._projectionModeMatrix.m[12] = 0.5;
  10747. this._projectionModeMatrix.m[13] = 0.5;
  10748. this._projectionModeMatrix.m[14] = 1.0;
  10749. this._projectionModeMatrix.m[15] = 1.0;
  10750. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  10751. break;
  10752. default:
  10753. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  10754. break;
  10755. }
  10756. return this._cachedTextureMatrix;
  10757. };
  10758. Texture.prototype.clone = function () {
  10759. var newTexture = new BABYLON.Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY);
  10760. // Base texture
  10761. newTexture.hasAlpha = this.hasAlpha;
  10762. newTexture.level = this.level;
  10763. newTexture.wrapU = this.wrapU;
  10764. newTexture.wrapV = this.wrapV;
  10765. newTexture.coordinatesIndex = this.coordinatesIndex;
  10766. newTexture.coordinatesMode = this.coordinatesMode;
  10767. // Texture
  10768. newTexture.uOffset = this.uOffset;
  10769. newTexture.vOffset = this.vOffset;
  10770. newTexture.uScale = this.uScale;
  10771. newTexture.vScale = this.vScale;
  10772. newTexture.uAng = this.uAng;
  10773. newTexture.vAng = this.vAng;
  10774. newTexture.wAng = this.wAng;
  10775. return newTexture;
  10776. };
  10777. // Statics
  10778. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  10779. if (typeof samplingMode === "undefined") { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  10780. if (typeof onLoad === "undefined") { onLoad = null; }
  10781. if (typeof onError === "undefined") { onError = null; }
  10782. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  10783. };
  10784. Texture.NEAREST_SAMPLINGMODE = 1;
  10785. Texture.BILINEAR_SAMPLINGMODE = 2;
  10786. Texture.TRILINEAR_SAMPLINGMODE = 3;
  10787. Texture.EXPLICIT_MODE = 0;
  10788. Texture.SPHERICAL_MODE = 1;
  10789. Texture.PLANAR_MODE = 2;
  10790. Texture.CUBIC_MODE = 3;
  10791. Texture.PROJECTION_MODE = 4;
  10792. Texture.SKYBOX_MODE = 5;
  10793. Texture.CLAMP_ADDRESSMODE = 0;
  10794. Texture.WRAP_ADDRESSMODE = 1;
  10795. Texture.MIRROR_ADDRESSMODE = 2;
  10796. return Texture;
  10797. })(BABYLON.BaseTexture);
  10798. BABYLON.Texture = Texture;
  10799. })(BABYLON || (BABYLON = {}));
  10800. //# sourceMappingURL=babylon.texture.js.map
  10801. var BABYLON;
  10802. (function (BABYLON) {
  10803. var CubeTexture = (function (_super) {
  10804. __extends(CubeTexture, _super);
  10805. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  10806. _super.call(this, scene);
  10807. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  10808. this.name = rootUrl;
  10809. this.url = rootUrl;
  10810. this._noMipmap = noMipmap;
  10811. this.hasAlpha = false;
  10812. this._texture = this._getFromCache(rootUrl, noMipmap);
  10813. if (!extensions) {
  10814. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  10815. }
  10816. this._extensions = extensions;
  10817. if (!this._texture) {
  10818. if (!scene.useDelayedTextureLoading) {
  10819. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  10820. } else {
  10821. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  10822. }
  10823. }
  10824. this.isCube = true;
  10825. this._textureMatrix = BABYLON.Matrix.Identity();
  10826. }
  10827. CubeTexture.prototype.clone = function () {
  10828. var newTexture = new BABYLON.CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  10829. // Base texture
  10830. newTexture.level = this.level;
  10831. newTexture.wrapU = this.wrapU;
  10832. newTexture.wrapV = this.wrapV;
  10833. newTexture.coordinatesIndex = this.coordinatesIndex;
  10834. newTexture.coordinatesMode = this.coordinatesMode;
  10835. return newTexture;
  10836. };
  10837. // Methods
  10838. CubeTexture.prototype.delayLoad = function () {
  10839. if (this.delayLoadState != BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  10840. return;
  10841. }
  10842. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  10843. this._texture = this._getFromCache(this.url, this._noMipmap);
  10844. if (!this._texture) {
  10845. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  10846. }
  10847. };
  10848. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  10849. return this._textureMatrix;
  10850. };
  10851. return CubeTexture;
  10852. })(BABYLON.BaseTexture);
  10853. BABYLON.CubeTexture = CubeTexture;
  10854. })(BABYLON || (BABYLON = {}));
  10855. //# sourceMappingURL=babylon.cubeTexture.js.map
  10856. var BABYLON;
  10857. (function (BABYLON) {
  10858. var RenderTargetTexture = (function (_super) {
  10859. __extends(RenderTargetTexture, _super);
  10860. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio) {
  10861. if (typeof doNotChangeAspectRatio === "undefined") { doNotChangeAspectRatio = true; }
  10862. _super.call(this, null, scene, !generateMipMaps);
  10863. this.renderList = new Array();
  10864. this.renderParticles = true;
  10865. this.renderSprites = false;
  10866. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  10867. this._currentRefreshId = -1;
  10868. this._refreshRate = 1;
  10869. this.name = name;
  10870. this.isRenderTarget = true;
  10871. this._size = size;
  10872. this._generateMipMaps = generateMipMaps;
  10873. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  10874. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  10875. // Rendering groups
  10876. this._renderingManager = new BABYLON.RenderingManager(scene);
  10877. }
  10878. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  10879. this._currentRefreshId = -1;
  10880. };
  10881. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  10882. get: function () {
  10883. return this._refreshRate;
  10884. },
  10885. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  10886. set: function (value) {
  10887. this._refreshRate = value;
  10888. this.resetRefreshCounter();
  10889. },
  10890. enumerable: true,
  10891. configurable: true
  10892. });
  10893. RenderTargetTexture.prototype._shouldRender = function () {
  10894. if (this._currentRefreshId === -1) {
  10895. this._currentRefreshId = 1;
  10896. return true;
  10897. }
  10898. if (this.refreshRate == this._currentRefreshId) {
  10899. this._currentRefreshId = 1;
  10900. return true;
  10901. }
  10902. this._currentRefreshId++;
  10903. return false;
  10904. };
  10905. RenderTargetTexture.prototype.isReady = function () {
  10906. if (!this.getScene().renderTargetsEnabled) {
  10907. return false;
  10908. }
  10909. return _super.prototype.isReady.call(this);
  10910. };
  10911. RenderTargetTexture.prototype.getRenderSize = function () {
  10912. return this._size;
  10913. };
  10914. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  10915. get: function () {
  10916. return true;
  10917. },
  10918. enumerable: true,
  10919. configurable: true
  10920. });
  10921. RenderTargetTexture.prototype.scale = function (ratio) {
  10922. var newSize = this._size * ratio;
  10923. this.resize(newSize, this._generateMipMaps);
  10924. };
  10925. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  10926. this.releaseInternalTexture();
  10927. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  10928. };
  10929. RenderTargetTexture.prototype.render = function (useCameraPostProcess) {
  10930. var scene = this.getScene();
  10931. var engine = scene.getEngine();
  10932. if (this._waitingRenderList) {
  10933. this.renderList = [];
  10934. for (var index = 0; index < this._waitingRenderList.length; index++) {
  10935. var id = this._waitingRenderList[index];
  10936. this.renderList.push(scene.getMeshByID(id));
  10937. }
  10938. delete this._waitingRenderList;
  10939. }
  10940. if (!this.renderList) {
  10941. return;
  10942. }
  10943. // Bind
  10944. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  10945. engine.bindFramebuffer(this._texture);
  10946. }
  10947. // Clear
  10948. engine.clear(scene.clearColor, true, true);
  10949. this._renderingManager.reset();
  10950. for (var meshIndex = 0; meshIndex < this.renderList.length; meshIndex++) {
  10951. var mesh = this.renderList[meshIndex];
  10952. if (mesh) {
  10953. if (!mesh.isReady() || (mesh.material && !mesh.material.isReady())) {
  10954. // Reset _currentRefreshId
  10955. this.resetRefreshCounter();
  10956. continue;
  10957. }
  10958. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) != 0)) {
  10959. mesh._activate(scene.getRenderId());
  10960. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  10961. var subMesh = mesh.subMeshes[subIndex];
  10962. scene._activeVertices += subMesh.indexCount;
  10963. this._renderingManager.dispatch(subMesh);
  10964. }
  10965. }
  10966. }
  10967. }
  10968. if (!this._doNotChangeAspectRatio) {
  10969. scene.updateTransformMatrix(true);
  10970. }
  10971. if (this.onBeforeRender) {
  10972. this.onBeforeRender();
  10973. }
  10974. // Render
  10975. this._renderingManager.render(this.customRenderFunction, this.renderList, this.renderParticles, this.renderSprites);
  10976. if (useCameraPostProcess) {
  10977. scene.postProcessManager._finalizeFrame(false, this._texture);
  10978. }
  10979. if (this.onAfterRender) {
  10980. this.onAfterRender();
  10981. }
  10982. // Unbind
  10983. engine.unBindFramebuffer(this._texture);
  10984. if (!this._doNotChangeAspectRatio) {
  10985. scene.updateTransformMatrix(true);
  10986. }
  10987. };
  10988. RenderTargetTexture.prototype.clone = function () {
  10989. var textureSize = this.getSize();
  10990. var newTexture = new BABYLON.RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  10991. // Base texture
  10992. newTexture.hasAlpha = this.hasAlpha;
  10993. newTexture.level = this.level;
  10994. // RenderTarget Texture
  10995. newTexture.coordinatesMode = this.coordinatesMode;
  10996. newTexture.renderList = this.renderList.slice(0);
  10997. return newTexture;
  10998. };
  10999. return RenderTargetTexture;
  11000. })(BABYLON.Texture);
  11001. BABYLON.RenderTargetTexture = RenderTargetTexture;
  11002. })(BABYLON || (BABYLON = {}));
  11003. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  11004. var BABYLON;
  11005. (function (BABYLON) {
  11006. var ProceduralTexture = (function (_super) {
  11007. __extends(ProceduralTexture, _super);
  11008. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps) {
  11009. if (typeof generateMipMaps === "undefined") { generateMipMaps = true; }
  11010. _super.call(this, null, scene, !generateMipMaps);
  11011. this._currentRefreshId = -1;
  11012. this._refreshRate = 1;
  11013. this._vertexDeclaration = [2];
  11014. this._vertexStrideSize = 2 * 4;
  11015. this._uniforms = new Array();
  11016. this._samplers = new Array();
  11017. this._textures = new Array();
  11018. this._floats = new Array();
  11019. this._floatsArrays = {};
  11020. this._colors3 = new Array();
  11021. this._colors4 = new Array();
  11022. this._vectors2 = new Array();
  11023. this._vectors3 = new Array();
  11024. this._matrices = new Array();
  11025. this._fallbackTextureUsed = false;
  11026. scene._proceduralTextures.push(this);
  11027. this.name = name;
  11028. this.isRenderTarget = true;
  11029. this._size = size;
  11030. this._generateMipMaps = generateMipMaps;
  11031. this.setFragment(fragment);
  11032. this._fallbackTexture = fallbackTexture;
  11033. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  11034. // VBO
  11035. var vertices = [];
  11036. vertices.push(1, 1);
  11037. vertices.push(-1, 1);
  11038. vertices.push(-1, -1);
  11039. vertices.push(1, -1);
  11040. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  11041. // Indices
  11042. var indices = [];
  11043. indices.push(0);
  11044. indices.push(1);
  11045. indices.push(2);
  11046. indices.push(0);
  11047. indices.push(2);
  11048. indices.push(3);
  11049. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  11050. }
  11051. ProceduralTexture.prototype.reset = function () {
  11052. if (this._effect === undefined) {
  11053. return;
  11054. }
  11055. var engine = this.getScene().getEngine();
  11056. engine._releaseEffect(this._effect);
  11057. };
  11058. ProceduralTexture.prototype.isReady = function () {
  11059. var _this = this;
  11060. var engine = this.getScene().getEngine();
  11061. var shaders;
  11062. if (!this._fragment) {
  11063. return false;
  11064. }
  11065. if (this._fallbackTextureUsed) {
  11066. return true;
  11067. }
  11068. if (this._fragment.fragmentElement !== undefined) {
  11069. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  11070. } else {
  11071. shaders = { vertex: "procedural", fragment: this._fragment };
  11072. }
  11073. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  11074. _this.releaseInternalTexture();
  11075. if (_this._fallbackTexture) {
  11076. _this._texture = _this._fallbackTexture._texture;
  11077. _this._texture.references++;
  11078. }
  11079. _this._fallbackTextureUsed = true;
  11080. });
  11081. return this._effect.isReady();
  11082. };
  11083. ProceduralTexture.prototype.resetRefreshCounter = function () {
  11084. this._currentRefreshId = -1;
  11085. };
  11086. ProceduralTexture.prototype.setFragment = function (fragment) {
  11087. this._fragment = fragment;
  11088. };
  11089. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  11090. get: function () {
  11091. return this._refreshRate;
  11092. },
  11093. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  11094. set: function (value) {
  11095. this._refreshRate = value;
  11096. this.resetRefreshCounter();
  11097. },
  11098. enumerable: true,
  11099. configurable: true
  11100. });
  11101. ProceduralTexture.prototype._shouldRender = function () {
  11102. if (!this.isReady() || !this._texture) {
  11103. return false;
  11104. }
  11105. if (this._fallbackTextureUsed) {
  11106. return false;
  11107. }
  11108. if (this._currentRefreshId === -1) {
  11109. this._currentRefreshId = 1;
  11110. return true;
  11111. }
  11112. if (this.refreshRate === this._currentRefreshId) {
  11113. this._currentRefreshId = 1;
  11114. return true;
  11115. }
  11116. this._currentRefreshId++;
  11117. return false;
  11118. };
  11119. ProceduralTexture.prototype.getRenderSize = function () {
  11120. return this._size;
  11121. };
  11122. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  11123. if (this._fallbackTextureUsed) {
  11124. return;
  11125. }
  11126. this.releaseInternalTexture();
  11127. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  11128. };
  11129. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  11130. if (this._uniforms.indexOf(uniformName) === -1) {
  11131. this._uniforms.push(uniformName);
  11132. }
  11133. };
  11134. ProceduralTexture.prototype.setTexture = function (name, texture) {
  11135. if (this._samplers.indexOf(name) === -1) {
  11136. this._samplers.push(name);
  11137. }
  11138. this._textures[name] = texture;
  11139. return this;
  11140. };
  11141. ProceduralTexture.prototype.setFloat = function (name, value) {
  11142. this._checkUniform(name);
  11143. this._floats[name] = value;
  11144. return this;
  11145. };
  11146. ProceduralTexture.prototype.setFloats = function (name, value) {
  11147. this._checkUniform(name);
  11148. this._floatsArrays[name] = value;
  11149. return this;
  11150. };
  11151. ProceduralTexture.prototype.setColor3 = function (name, value) {
  11152. this._checkUniform(name);
  11153. this._colors3[name] = value;
  11154. return this;
  11155. };
  11156. ProceduralTexture.prototype.setColor4 = function (name, value) {
  11157. this._checkUniform(name);
  11158. this._colors4[name] = value;
  11159. return this;
  11160. };
  11161. ProceduralTexture.prototype.setVector2 = function (name, value) {
  11162. this._checkUniform(name);
  11163. this._vectors2[name] = value;
  11164. return this;
  11165. };
  11166. ProceduralTexture.prototype.setVector3 = function (name, value) {
  11167. this._checkUniform(name);
  11168. this._vectors3[name] = value;
  11169. return this;
  11170. };
  11171. ProceduralTexture.prototype.setMatrix = function (name, value) {
  11172. this._checkUniform(name);
  11173. this._matrices[name] = value;
  11174. return this;
  11175. };
  11176. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  11177. var scene = this.getScene();
  11178. var engine = scene.getEngine();
  11179. engine.bindFramebuffer(this._texture);
  11180. // Clear
  11181. engine.clear(scene.clearColor, true, true);
  11182. // Render
  11183. engine.enableEffect(this._effect);
  11184. engine.setState(false);
  11185. for (var name in this._textures) {
  11186. this._effect.setTexture(name, this._textures[name]);
  11187. }
  11188. for (name in this._floats) {
  11189. this._effect.setFloat(name, this._floats[name]);
  11190. }
  11191. for (name in this._floatsArrays) {
  11192. this._effect.setArray(name, this._floatsArrays[name]);
  11193. }
  11194. for (name in this._colors3) {
  11195. this._effect.setColor3(name, this._colors3[name]);
  11196. }
  11197. for (name in this._colors4) {
  11198. var color = this._colors4[name];
  11199. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  11200. }
  11201. for (name in this._vectors2) {
  11202. this._effect.setVector2(name, this._vectors2[name]);
  11203. }
  11204. for (name in this._vectors3) {
  11205. this._effect.setVector3(name, this._vectors3[name]);
  11206. }
  11207. for (name in this._matrices) {
  11208. this._effect.setMatrix(name, this._matrices[name]);
  11209. }
  11210. // VBOs
  11211. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  11212. // Draw order
  11213. engine.draw(true, 0, 6);
  11214. // Unbind
  11215. engine.unBindFramebuffer(this._texture);
  11216. };
  11217. ProceduralTexture.prototype.clone = function () {
  11218. var textureSize = this.getSize();
  11219. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  11220. // Base texture
  11221. newTexture.hasAlpha = this.hasAlpha;
  11222. newTexture.level = this.level;
  11223. // RenderTarget Texture
  11224. newTexture.coordinatesMode = this.coordinatesMode;
  11225. return newTexture;
  11226. };
  11227. ProceduralTexture.prototype.dispose = function () {
  11228. var index = this.getScene()._proceduralTextures.indexOf(this);
  11229. if (index >= 0) {
  11230. this.getScene()._proceduralTextures.splice(index, 1);
  11231. }
  11232. _super.prototype.dispose.call(this);
  11233. };
  11234. return ProceduralTexture;
  11235. })(BABYLON.Texture);
  11236. BABYLON.ProceduralTexture = ProceduralTexture;
  11237. })(BABYLON || (BABYLON = {}));
  11238. //# sourceMappingURL=babylon.proceduralTexture.js.map
  11239. var BABYLON;
  11240. (function (BABYLON) {
  11241. var WoodProceduralTexture = (function (_super) {
  11242. __extends(WoodProceduralTexture, _super);
  11243. function WoodProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  11244. _super.call(this, name, size, "wood", scene, fallbackTexture, generateMipMaps);
  11245. this._ampScale = 100.0;
  11246. this._woodColor = new BABYLON.Color3(0.32, 0.17, 0.09);
  11247. this.updateShaderUniforms();
  11248. this.refreshRate = 0;
  11249. }
  11250. WoodProceduralTexture.prototype.updateShaderUniforms = function () {
  11251. this.setFloat("ampScale", this._ampScale);
  11252. this.setColor3("woodColor", this._woodColor);
  11253. };
  11254. Object.defineProperty(WoodProceduralTexture.prototype, "ampScale", {
  11255. get: function () {
  11256. return this._ampScale;
  11257. },
  11258. set: function (value) {
  11259. this._ampScale = value;
  11260. this.updateShaderUniforms();
  11261. },
  11262. enumerable: true,
  11263. configurable: true
  11264. });
  11265. Object.defineProperty(WoodProceduralTexture.prototype, "woodColor", {
  11266. get: function () {
  11267. return this._woodColor;
  11268. },
  11269. set: function (value) {
  11270. this._woodColor = value;
  11271. this.updateShaderUniforms();
  11272. },
  11273. enumerable: true,
  11274. configurable: true
  11275. });
  11276. return WoodProceduralTexture;
  11277. })(BABYLON.ProceduralTexture);
  11278. BABYLON.WoodProceduralTexture = WoodProceduralTexture;
  11279. var FireProceduralTexture = (function (_super) {
  11280. __extends(FireProceduralTexture, _super);
  11281. function FireProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  11282. _super.call(this, name, size, "fire", scene, fallbackTexture, generateMipMaps);
  11283. this._time = 0.0;
  11284. this._speed = new BABYLON.Vector2(0.5, 0.3);
  11285. this._shift = 1.6;
  11286. this._autoGenerateTime = true;
  11287. this._alphaThreshold = 0.5;
  11288. this._fireColors = FireProceduralTexture.RedFireColors;
  11289. this.updateShaderUniforms();
  11290. this.refreshRate = 1;
  11291. }
  11292. FireProceduralTexture.prototype.updateShaderUniforms = function () {
  11293. this.setFloat("time", this._time);
  11294. this.setVector2("speed", this._speed);
  11295. this.setFloat("shift", this._shift);
  11296. this.setColor3("c1", this._fireColors[0]);
  11297. this.setColor3("c2", this._fireColors[1]);
  11298. this.setColor3("c3", this._fireColors[2]);
  11299. this.setColor3("c4", this._fireColors[3]);
  11300. this.setColor3("c5", this._fireColors[4]);
  11301. this.setColor3("c6", this._fireColors[5]);
  11302. this.setFloat("alphaThreshold", this._alphaThreshold);
  11303. };
  11304. FireProceduralTexture.prototype.render = function (useCameraPostProcess) {
  11305. if (this._autoGenerateTime) {
  11306. this._time += this.getScene().getAnimationRatio() * 0.03;
  11307. this.updateShaderUniforms();
  11308. }
  11309. _super.prototype.render.call(this, useCameraPostProcess);
  11310. };
  11311. Object.defineProperty(FireProceduralTexture, "PurpleFireColors", {
  11312. get: function () {
  11313. return [
  11314. new BABYLON.Color3(0.5, 0.0, 1.0),
  11315. new BABYLON.Color3(0.9, 0.0, 1.0),
  11316. new BABYLON.Color3(0.2, 0.0, 1.0),
  11317. new BABYLON.Color3(1.0, 0.9, 1.0),
  11318. new BABYLON.Color3(0.1, 0.1, 1.0),
  11319. new BABYLON.Color3(0.9, 0.9, 1.0)
  11320. ];
  11321. },
  11322. enumerable: true,
  11323. configurable: true
  11324. });
  11325. Object.defineProperty(FireProceduralTexture, "GreenFireColors", {
  11326. get: function () {
  11327. return [
  11328. new BABYLON.Color3(0.5, 1.0, 0.0),
  11329. new BABYLON.Color3(0.5, 1.0, 0.0),
  11330. new BABYLON.Color3(0.3, 0.4, 0.0),
  11331. new BABYLON.Color3(0.5, 1.0, 0.0),
  11332. new BABYLON.Color3(0.2, 0.0, 0.0),
  11333. new BABYLON.Color3(0.5, 1.0, 0.0)
  11334. ];
  11335. },
  11336. enumerable: true,
  11337. configurable: true
  11338. });
  11339. Object.defineProperty(FireProceduralTexture, "RedFireColors", {
  11340. get: function () {
  11341. return [
  11342. new BABYLON.Color3(0.5, 0.0, 0.1),
  11343. new BABYLON.Color3(0.9, 0.0, 0.0),
  11344. new BABYLON.Color3(0.2, 0.0, 0.0),
  11345. new BABYLON.Color3(1.0, 0.9, 0.0),
  11346. new BABYLON.Color3(0.1, 0.1, 0.1),
  11347. new BABYLON.Color3(0.9, 0.9, 0.9)
  11348. ];
  11349. },
  11350. enumerable: true,
  11351. configurable: true
  11352. });
  11353. Object.defineProperty(FireProceduralTexture, "BlueFireColors", {
  11354. get: function () {
  11355. return [
  11356. new BABYLON.Color3(0.1, 0.0, 0.5),
  11357. new BABYLON.Color3(0.0, 0.0, 0.5),
  11358. new BABYLON.Color3(0.1, 0.0, 0.2),
  11359. new BABYLON.Color3(0.0, 0.0, 1.0),
  11360. new BABYLON.Color3(0.1, 0.2, 0.3),
  11361. new BABYLON.Color3(0.0, 0.2, 0.9)
  11362. ];
  11363. },
  11364. enumerable: true,
  11365. configurable: true
  11366. });
  11367. Object.defineProperty(FireProceduralTexture.prototype, "fireColors", {
  11368. get: function () {
  11369. return this._fireColors;
  11370. },
  11371. set: function (value) {
  11372. this._fireColors = value;
  11373. this.updateShaderUniforms();
  11374. },
  11375. enumerable: true,
  11376. configurable: true
  11377. });
  11378. Object.defineProperty(FireProceduralTexture.prototype, "time", {
  11379. get: function () {
  11380. return this._time;
  11381. },
  11382. set: function (value) {
  11383. this._time = value;
  11384. this.updateShaderUniforms();
  11385. },
  11386. enumerable: true,
  11387. configurable: true
  11388. });
  11389. Object.defineProperty(FireProceduralTexture.prototype, "speed", {
  11390. get: function () {
  11391. return this._speed;
  11392. },
  11393. set: function (value) {
  11394. this._speed = value;
  11395. this.updateShaderUniforms();
  11396. },
  11397. enumerable: true,
  11398. configurable: true
  11399. });
  11400. Object.defineProperty(FireProceduralTexture.prototype, "shift", {
  11401. get: function () {
  11402. return this._shift;
  11403. },
  11404. set: function (value) {
  11405. this._shift = value;
  11406. this.updateShaderUniforms();
  11407. },
  11408. enumerable: true,
  11409. configurable: true
  11410. });
  11411. Object.defineProperty(FireProceduralTexture.prototype, "alphaThreshold", {
  11412. get: function () {
  11413. return this._alphaThreshold;
  11414. },
  11415. set: function (value) {
  11416. this._alphaThreshold = value;
  11417. this.updateShaderUniforms();
  11418. },
  11419. enumerable: true,
  11420. configurable: true
  11421. });
  11422. return FireProceduralTexture;
  11423. })(BABYLON.ProceduralTexture);
  11424. BABYLON.FireProceduralTexture = FireProceduralTexture;
  11425. var CloudProceduralTexture = (function (_super) {
  11426. __extends(CloudProceduralTexture, _super);
  11427. function CloudProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  11428. _super.call(this, name, size, "cloud", scene, fallbackTexture, generateMipMaps);
  11429. this._skyColor = new BABYLON.Color3(0.15, 0.68, 1.0);
  11430. this._cloudColor = new BABYLON.Color3(1, 1, 1);
  11431. this.updateShaderUniforms();
  11432. this.refreshRate = 0;
  11433. }
  11434. CloudProceduralTexture.prototype.updateShaderUniforms = function () {
  11435. this.setColor3("skyColor", this._skyColor);
  11436. this.setColor3("cloudColor", this._cloudColor);
  11437. };
  11438. Object.defineProperty(CloudProceduralTexture.prototype, "skyColor", {
  11439. get: function () {
  11440. return this._skyColor;
  11441. },
  11442. set: function (value) {
  11443. this._skyColor = value;
  11444. this.updateShaderUniforms();
  11445. },
  11446. enumerable: true,
  11447. configurable: true
  11448. });
  11449. Object.defineProperty(CloudProceduralTexture.prototype, "cloudColor", {
  11450. get: function () {
  11451. return this._cloudColor;
  11452. },
  11453. set: function (value) {
  11454. this._cloudColor = value;
  11455. this.updateShaderUniforms();
  11456. },
  11457. enumerable: true,
  11458. configurable: true
  11459. });
  11460. return CloudProceduralTexture;
  11461. })(BABYLON.ProceduralTexture);
  11462. BABYLON.CloudProceduralTexture = CloudProceduralTexture;
  11463. var GrassProceduralTexture = (function (_super) {
  11464. __extends(GrassProceduralTexture, _super);
  11465. function GrassProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  11466. _super.call(this, name, size, "grass", scene, fallbackTexture, generateMipMaps);
  11467. this._herb1 = new BABYLON.Color3(0.29, 0.38, 0.02);
  11468. this._herb2 = new BABYLON.Color3(0.36, 0.49, 0.09);
  11469. this._herb3 = new BABYLON.Color3(0.51, 0.6, 0.28);
  11470. this._groundColor = new BABYLON.Color3(1, 1, 1);
  11471. this._grassColors = [
  11472. new BABYLON.Color3(0.29, 0.38, 0.02),
  11473. new BABYLON.Color3(0.36, 0.49, 0.09),
  11474. new BABYLON.Color3(0.51, 0.6, 0.28)
  11475. ];
  11476. this.updateShaderUniforms();
  11477. this.refreshRate = 0;
  11478. }
  11479. GrassProceduralTexture.prototype.updateShaderUniforms = function () {
  11480. this.setColor3("herb1Color", this._grassColors[0]);
  11481. this.setColor3("herb2Color", this._grassColors[1]);
  11482. this.setColor3("herb3Color", this._grassColors[2]);
  11483. this.setColor3("groundColor", this._groundColor);
  11484. };
  11485. Object.defineProperty(GrassProceduralTexture.prototype, "grassColors", {
  11486. get: function () {
  11487. return this._grassColors;
  11488. },
  11489. set: function (value) {
  11490. this._grassColors = value;
  11491. this.updateShaderUniforms();
  11492. },
  11493. enumerable: true,
  11494. configurable: true
  11495. });
  11496. Object.defineProperty(GrassProceduralTexture.prototype, "groundColor", {
  11497. get: function () {
  11498. return this._groundColor;
  11499. },
  11500. set: function (value) {
  11501. this.groundColor = value;
  11502. this.updateShaderUniforms();
  11503. },
  11504. enumerable: true,
  11505. configurable: true
  11506. });
  11507. return GrassProceduralTexture;
  11508. })(BABYLON.ProceduralTexture);
  11509. BABYLON.GrassProceduralTexture = GrassProceduralTexture;
  11510. var RoadProceduralTexture = (function (_super) {
  11511. __extends(RoadProceduralTexture, _super);
  11512. function RoadProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  11513. _super.call(this, name, size, "road", scene, fallbackTexture, generateMipMaps);
  11514. this._roadColor = new BABYLON.Color3(0.53, 0.53, 0.53);
  11515. this.updateShaderUniforms();
  11516. this.refreshRate = 0;
  11517. }
  11518. RoadProceduralTexture.prototype.updateShaderUniforms = function () {
  11519. this.setColor3("roadColor", this._roadColor);
  11520. };
  11521. Object.defineProperty(RoadProceduralTexture.prototype, "roadColor", {
  11522. get: function () {
  11523. return this._roadColor;
  11524. },
  11525. set: function (value) {
  11526. this._roadColor = value;
  11527. this.updateShaderUniforms();
  11528. },
  11529. enumerable: true,
  11530. configurable: true
  11531. });
  11532. return RoadProceduralTexture;
  11533. })(BABYLON.ProceduralTexture);
  11534. BABYLON.RoadProceduralTexture = RoadProceduralTexture;
  11535. var BrickProceduralTexture = (function (_super) {
  11536. __extends(BrickProceduralTexture, _super);
  11537. function BrickProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  11538. _super.call(this, name, size, "brick", scene, fallbackTexture, generateMipMaps);
  11539. this._numberOfBricksHeight = 15;
  11540. this._numberOfBricksWidth = 5;
  11541. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  11542. this._brickColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  11543. this.updateShaderUniforms();
  11544. this.refreshRate = 0;
  11545. }
  11546. BrickProceduralTexture.prototype.updateShaderUniforms = function () {
  11547. this.setFloat("numberOfBricksHeight", this._numberOfBricksHeight);
  11548. this.setFloat("numberOfBricksWidth", this._numberOfBricksWidth);
  11549. this.setColor3("brickColor", this._brickColor);
  11550. this.setColor3("jointColor", this._jointColor);
  11551. };
  11552. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksHeight", {
  11553. get: function () {
  11554. return this._numberOfBricksHeight;
  11555. },
  11556. enumerable: true,
  11557. configurable: true
  11558. });
  11559. Object.defineProperty(BrickProceduralTexture.prototype, "cloudColor", {
  11560. set: function (value) {
  11561. this._numberOfBricksHeight = value;
  11562. this.updateShaderUniforms();
  11563. },
  11564. enumerable: true,
  11565. configurable: true
  11566. });
  11567. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksWidth", {
  11568. get: function () {
  11569. return this._numberOfBricksWidth;
  11570. },
  11571. set: function (value) {
  11572. this._numberOfBricksHeight = value;
  11573. this.updateShaderUniforms();
  11574. },
  11575. enumerable: true,
  11576. configurable: true
  11577. });
  11578. Object.defineProperty(BrickProceduralTexture.prototype, "jointColor", {
  11579. get: function () {
  11580. return this._jointColor;
  11581. },
  11582. set: function (value) {
  11583. this._jointColor = value;
  11584. this.updateShaderUniforms();
  11585. },
  11586. enumerable: true,
  11587. configurable: true
  11588. });
  11589. Object.defineProperty(BrickProceduralTexture.prototype, "brickColor", {
  11590. get: function () {
  11591. return this._brickColor;
  11592. },
  11593. set: function (value) {
  11594. this._brickColor = value;
  11595. this.updateShaderUniforms();
  11596. },
  11597. enumerable: true,
  11598. configurable: true
  11599. });
  11600. return BrickProceduralTexture;
  11601. })(BABYLON.ProceduralTexture);
  11602. BABYLON.BrickProceduralTexture = BrickProceduralTexture;
  11603. var MarbleProceduralTexture = (function (_super) {
  11604. __extends(MarbleProceduralTexture, _super);
  11605. function MarbleProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  11606. _super.call(this, name, size, "marble", scene, fallbackTexture, generateMipMaps);
  11607. this._numberOfTilesHeight = 3;
  11608. this._numberOfTilesWidth = 3;
  11609. this._amplitude = 9.0;
  11610. this._marbleColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  11611. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  11612. this.updateShaderUniforms();
  11613. this.refreshRate = 0;
  11614. }
  11615. MarbleProceduralTexture.prototype.updateShaderUniforms = function () {
  11616. this.setFloat("numberOfTilesHeight", this._numberOfTilesHeight);
  11617. this.setFloat("numberOfTilesWidth", this._numberOfTilesWidth);
  11618. this.setFloat("amplitude", this._amplitude);
  11619. this.setColor3("marbleColor", this._marbleColor);
  11620. this.setColor3("jointColor", this._jointColor);
  11621. };
  11622. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesHeight", {
  11623. get: function () {
  11624. return this._numberOfTilesHeight;
  11625. },
  11626. set: function (value) {
  11627. this._numberOfTilesHeight = value;
  11628. this.updateShaderUniforms();
  11629. },
  11630. enumerable: true,
  11631. configurable: true
  11632. });
  11633. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesWidth", {
  11634. get: function () {
  11635. return this._numberOfTilesWidth;
  11636. },
  11637. set: function (value) {
  11638. this._numberOfTilesWidth = value;
  11639. this.updateShaderUniforms();
  11640. },
  11641. enumerable: true,
  11642. configurable: true
  11643. });
  11644. Object.defineProperty(MarbleProceduralTexture.prototype, "jointColor", {
  11645. get: function () {
  11646. return this._jointColor;
  11647. },
  11648. set: function (value) {
  11649. this._jointColor = value;
  11650. this.updateShaderUniforms();
  11651. },
  11652. enumerable: true,
  11653. configurable: true
  11654. });
  11655. Object.defineProperty(MarbleProceduralTexture.prototype, "marbleColor", {
  11656. get: function () {
  11657. return this._marbleColor;
  11658. },
  11659. set: function (value) {
  11660. this._marbleColor = value;
  11661. this.updateShaderUniforms();
  11662. },
  11663. enumerable: true,
  11664. configurable: true
  11665. });
  11666. return MarbleProceduralTexture;
  11667. })(BABYLON.ProceduralTexture);
  11668. BABYLON.MarbleProceduralTexture = MarbleProceduralTexture;
  11669. })(BABYLON || (BABYLON = {}));
  11670. //# sourceMappingURL=babylon.standardProceduralTexture.js.map
  11671. var BABYLON;
  11672. (function (BABYLON) {
  11673. var CustomProceduralTexture = (function (_super) {
  11674. __extends(CustomProceduralTexture, _super);
  11675. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  11676. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  11677. this._animate = true;
  11678. this._time = 0;
  11679. this._texturePath = texturePath;
  11680. //Try to load json
  11681. this.loadJson(texturePath);
  11682. this.refreshRate = 1;
  11683. }
  11684. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  11685. var _this = this;
  11686. var that = this;
  11687. function noConfigFile() {
  11688. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShaderStore or DOM element");
  11689. try {
  11690. that.setFragment(that._texturePath);
  11691. } catch (ex) {
  11692. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  11693. }
  11694. }
  11695. var configFileUrl = jsonUrl + "/config.json";
  11696. var xhr = new XMLHttpRequest();
  11697. xhr.open("GET", configFileUrl, true);
  11698. xhr.addEventListener("load", function () {
  11699. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  11700. try {
  11701. _this._config = JSON.parse(xhr.response);
  11702. _this.updateShaderUniforms();
  11703. _this.updateTextures();
  11704. _this.setFragment(_this._texturePath + "/custom");
  11705. _this._animate = _this._config.animate;
  11706. _this.refreshRate = _this._config.refreshrate;
  11707. } catch (ex) {
  11708. noConfigFile();
  11709. }
  11710. } else {
  11711. noConfigFile();
  11712. }
  11713. }, false);
  11714. xhr.addEventListener("error", function (event) {
  11715. noConfigFile();
  11716. }, false);
  11717. try {
  11718. xhr.send();
  11719. } catch (ex) {
  11720. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  11721. }
  11722. };
  11723. CustomProceduralTexture.prototype.isReady = function () {
  11724. if (!_super.prototype.isReady.call(this)) {
  11725. return false;
  11726. }
  11727. for (var name in this._textures) {
  11728. var texture = this._textures[name];
  11729. if (!texture.isReady()) {
  11730. return false;
  11731. }
  11732. }
  11733. return true;
  11734. };
  11735. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  11736. if (this._animate) {
  11737. this._time += this.getScene().getAnimationRatio() * 0.03;
  11738. this.updateShaderUniforms();
  11739. }
  11740. _super.prototype.render.call(this, useCameraPostProcess);
  11741. };
  11742. CustomProceduralTexture.prototype.updateTextures = function () {
  11743. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  11744. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  11745. }
  11746. };
  11747. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  11748. if (this._config) {
  11749. for (var j = 0; j < this._config.uniforms.length; j++) {
  11750. var uniform = this._config.uniforms[j];
  11751. switch (uniform.type) {
  11752. case "float":
  11753. this.setFloat(uniform.name, uniform.value);
  11754. break;
  11755. case "color3":
  11756. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  11757. break;
  11758. case "color4":
  11759. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  11760. break;
  11761. case "vector2":
  11762. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  11763. break;
  11764. case "vector3":
  11765. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  11766. break;
  11767. }
  11768. }
  11769. }
  11770. this.setFloat("time", this._time);
  11771. };
  11772. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  11773. get: function () {
  11774. return this._animate;
  11775. },
  11776. set: function (value) {
  11777. this._animate = value;
  11778. },
  11779. enumerable: true,
  11780. configurable: true
  11781. });
  11782. return CustomProceduralTexture;
  11783. })(BABYLON.ProceduralTexture);
  11784. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  11785. })(BABYLON || (BABYLON = {}));
  11786. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  11787. var BABYLON;
  11788. (function (BABYLON) {
  11789. var MirrorTexture = (function (_super) {
  11790. __extends(MirrorTexture, _super);
  11791. function MirrorTexture(name, size, scene, generateMipMaps) {
  11792. var _this = this;
  11793. _super.call(this, name, size, scene, generateMipMaps, true);
  11794. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  11795. this._transformMatrix = BABYLON.Matrix.Zero();
  11796. this._mirrorMatrix = BABYLON.Matrix.Zero();
  11797. this.onBeforeRender = function () {
  11798. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  11799. _this._savedViewMatrix = scene.getViewMatrix();
  11800. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  11801. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  11802. scene.clipPlane = _this.mirrorPlane;
  11803. scene.getEngine().cullBackFaces = false;
  11804. };
  11805. this.onAfterRender = function () {
  11806. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  11807. scene.getEngine().cullBackFaces = true;
  11808. delete scene.clipPlane;
  11809. };
  11810. }
  11811. MirrorTexture.prototype.clone = function () {
  11812. var textureSize = this.getSize();
  11813. var newTexture = new BABYLON.MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  11814. // Base texture
  11815. newTexture.hasAlpha = this.hasAlpha;
  11816. newTexture.level = this.level;
  11817. // Mirror Texture
  11818. newTexture.mirrorPlane = this.mirrorPlane.clone();
  11819. newTexture.renderList = this.renderList.slice(0);
  11820. return newTexture;
  11821. };
  11822. return MirrorTexture;
  11823. })(BABYLON.RenderTargetTexture);
  11824. BABYLON.MirrorTexture = MirrorTexture;
  11825. })(BABYLON || (BABYLON = {}));
  11826. //# sourceMappingURL=babylon.mirrorTexture.js.map
  11827. var BABYLON;
  11828. (function (BABYLON) {
  11829. var DynamicTexture = (function (_super) {
  11830. __extends(DynamicTexture, _super);
  11831. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  11832. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  11833. _super.call(this, null, scene, !generateMipMaps);
  11834. this.name = name;
  11835. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  11836. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  11837. this._generateMipMaps = generateMipMaps;
  11838. if (options.getContext) {
  11839. this._canvas = options;
  11840. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  11841. } else {
  11842. this._canvas = document.createElement("canvas");
  11843. if (options.width) {
  11844. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  11845. } else {
  11846. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  11847. }
  11848. }
  11849. var textureSize = this.getSize();
  11850. this._canvas.width = textureSize.width;
  11851. this._canvas.height = textureSize.height;
  11852. this._context = this._canvas.getContext("2d");
  11853. }
  11854. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  11855. get: function () {
  11856. return true;
  11857. },
  11858. enumerable: true,
  11859. configurable: true
  11860. });
  11861. DynamicTexture.prototype.scale = function (ratio) {
  11862. var textureSize = this.getSize();
  11863. textureSize.width *= ratio;
  11864. textureSize.height *= ratio;
  11865. this._canvas.width = textureSize.width;
  11866. this._canvas.height = textureSize.height;
  11867. this.releaseInternalTexture();
  11868. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  11869. };
  11870. DynamicTexture.prototype.getContext = function () {
  11871. return this._context;
  11872. };
  11873. DynamicTexture.prototype.update = function (invertY) {
  11874. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  11875. };
  11876. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY) {
  11877. var size = this.getSize();
  11878. if (clearColor) {
  11879. this._context.fillStyle = clearColor;
  11880. this._context.fillRect(0, 0, size.width, size.height);
  11881. }
  11882. this._context.font = font;
  11883. if (x === null) {
  11884. var textSize = this._context.measureText(text);
  11885. x = (size.width - textSize.width) / 2;
  11886. }
  11887. this._context.fillStyle = color;
  11888. this._context.fillText(text, x, y);
  11889. this.update(invertY);
  11890. };
  11891. DynamicTexture.prototype.clone = function () {
  11892. var textureSize = this.getSize();
  11893. var newTexture = new BABYLON.DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  11894. // Base texture
  11895. newTexture.hasAlpha = this.hasAlpha;
  11896. newTexture.level = this.level;
  11897. // Dynamic Texture
  11898. newTexture.wrapU = this.wrapU;
  11899. newTexture.wrapV = this.wrapV;
  11900. return newTexture;
  11901. };
  11902. return DynamicTexture;
  11903. })(BABYLON.Texture);
  11904. BABYLON.DynamicTexture = DynamicTexture;
  11905. })(BABYLON || (BABYLON = {}));
  11906. //# sourceMappingURL=babylon.dynamicTexture.js.map
  11907. var BABYLON;
  11908. (function (BABYLON) {
  11909. var VideoTexture = (function (_super) {
  11910. __extends(VideoTexture, _super);
  11911. function VideoTexture(name, urls, size, scene, generateMipMaps, invertY, samplingMode) {
  11912. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  11913. var _this = this;
  11914. _super.call(this, null, scene, !generateMipMaps, invertY);
  11915. this._autoLaunch = true;
  11916. this.name = name;
  11917. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  11918. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  11919. var requiredWidth = size.width || size;
  11920. var requiredHeight = size.height || size;
  11921. this._texture = scene.getEngine().createDynamicTexture(requiredWidth, requiredHeight, generateMipMaps, samplingMode);
  11922. var textureSize = this.getSize();
  11923. this.video = document.createElement("video");
  11924. this.video.width = textureSize.width;
  11925. this.video.height = textureSize.height;
  11926. this.video.autoplay = false;
  11927. this.video.loop = true;
  11928. this.video.addEventListener("canplaythrough", function () {
  11929. if (_this._texture) {
  11930. _this._texture.isReady = true;
  11931. }
  11932. });
  11933. urls.forEach(function (url) {
  11934. var source = document.createElement("source");
  11935. source.src = url;
  11936. _this.video.appendChild(source);
  11937. });
  11938. this._lastUpdate = BABYLON.Tools.Now;
  11939. }
  11940. VideoTexture.prototype.update = function () {
  11941. if (this._autoLaunch) {
  11942. this._autoLaunch = false;
  11943. this.video.play();
  11944. }
  11945. var now = BABYLON.Tools.Now;
  11946. if (now - this._lastUpdate < 15) {
  11947. return false;
  11948. }
  11949. this._lastUpdate = now;
  11950. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  11951. return true;
  11952. };
  11953. return VideoTexture;
  11954. })(BABYLON.Texture);
  11955. BABYLON.VideoTexture = VideoTexture;
  11956. })(BABYLON || (BABYLON = {}));
  11957. //# sourceMappingURL=babylon.videoTexture.js.map
  11958. var BABYLON;
  11959. (function (BABYLON) {
  11960. var EffectFallbacks = (function () {
  11961. function EffectFallbacks() {
  11962. this._defines = {};
  11963. this._currentRank = 32;
  11964. this._maxRank = -1;
  11965. }
  11966. EffectFallbacks.prototype.addFallback = function (rank, define) {
  11967. if (!this._defines[rank]) {
  11968. if (rank < this._currentRank) {
  11969. this._currentRank = rank;
  11970. }
  11971. if (rank > this._maxRank) {
  11972. this._maxRank = rank;
  11973. }
  11974. this._defines[rank] = new Array();
  11975. }
  11976. this._defines[rank].push(define);
  11977. };
  11978. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  11979. get: function () {
  11980. return this._currentRank <= this._maxRank;
  11981. },
  11982. enumerable: true,
  11983. configurable: true
  11984. });
  11985. EffectFallbacks.prototype.reduce = function (currentDefines) {
  11986. var currentFallbacks = this._defines[this._currentRank];
  11987. for (var index = 0; index < currentFallbacks.length; index++) {
  11988. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  11989. }
  11990. this._currentRank++;
  11991. return currentDefines;
  11992. };
  11993. return EffectFallbacks;
  11994. })();
  11995. BABYLON.EffectFallbacks = EffectFallbacks;
  11996. var Effect = (function () {
  11997. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  11998. var _this = this;
  11999. this._isReady = false;
  12000. this._compilationError = "";
  12001. this._valueCache = [];
  12002. this._engine = engine;
  12003. this.name = baseName;
  12004. this.defines = defines;
  12005. this._uniformsNames = uniformsNames.concat(samplers);
  12006. this._samplers = samplers;
  12007. this._attributesNames = attributesNames;
  12008. this.onError = onError;
  12009. this.onCompiled = onCompiled;
  12010. var vertexSource;
  12011. var fragmentSource;
  12012. if (baseName.vertexElement) {
  12013. vertexSource = document.getElementById(baseName.vertexElement);
  12014. if (!vertexSource) {
  12015. vertexSource = baseName.vertexElement;
  12016. }
  12017. } else {
  12018. vertexSource = baseName.vertex || baseName;
  12019. }
  12020. if (baseName.fragmentElement) {
  12021. fragmentSource = document.getElementById(baseName.fragmentElement);
  12022. if (!fragmentSource) {
  12023. fragmentSource = baseName.fragmentElement;
  12024. }
  12025. } else {
  12026. fragmentSource = baseName.fragment || baseName;
  12027. }
  12028. this._loadVertexShader(vertexSource, function (vertexCode) {
  12029. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  12030. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  12031. });
  12032. });
  12033. }
  12034. // Properties
  12035. Effect.prototype.isReady = function () {
  12036. return this._isReady;
  12037. };
  12038. Effect.prototype.getProgram = function () {
  12039. return this._program;
  12040. };
  12041. Effect.prototype.getAttributesNames = function () {
  12042. return this._attributesNames;
  12043. };
  12044. Effect.prototype.getAttributeLocation = function (index) {
  12045. return this._attributes[index];
  12046. };
  12047. Effect.prototype.getAttributeLocationByName = function (name) {
  12048. var index = this._attributesNames.indexOf(name);
  12049. return this._attributes[index];
  12050. };
  12051. Effect.prototype.getAttributesCount = function () {
  12052. return this._attributes.length;
  12053. };
  12054. Effect.prototype.getUniformIndex = function (uniformName) {
  12055. return this._uniformsNames.indexOf(uniformName);
  12056. };
  12057. Effect.prototype.getUniform = function (uniformName) {
  12058. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  12059. };
  12060. Effect.prototype.getSamplers = function () {
  12061. return this._samplers;
  12062. };
  12063. Effect.prototype.getCompilationError = function () {
  12064. return this._compilationError;
  12065. };
  12066. // Methods
  12067. Effect.prototype._loadVertexShader = function (vertex, callback) {
  12068. // DOM element ?
  12069. if (vertex instanceof HTMLElement) {
  12070. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  12071. callback(vertexCode);
  12072. return;
  12073. }
  12074. // Is in local store ?
  12075. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  12076. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  12077. return;
  12078. }
  12079. var vertexShaderUrl;
  12080. if (vertex[0] === ".") {
  12081. vertexShaderUrl = vertex;
  12082. } else {
  12083. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  12084. }
  12085. // Vertex shader
  12086. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  12087. };
  12088. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  12089. // DOM element ?
  12090. if (fragment instanceof HTMLElement) {
  12091. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  12092. callback(fragmentCode);
  12093. return;
  12094. }
  12095. // Is in local store ?
  12096. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  12097. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  12098. return;
  12099. }
  12100. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  12101. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  12102. return;
  12103. }
  12104. var fragmentShaderUrl;
  12105. if (fragment[0] === ".") {
  12106. fragmentShaderUrl = fragment;
  12107. } else {
  12108. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  12109. }
  12110. // Fragment shader
  12111. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  12112. };
  12113. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  12114. try {
  12115. var engine = this._engine;
  12116. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  12117. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  12118. this._attributes = engine.getAttributes(this._program, attributesNames);
  12119. for (var index = 0; index < this._samplers.length; index++) {
  12120. var sampler = this.getUniform(this._samplers[index]);
  12121. if (sampler == null) {
  12122. this._samplers.splice(index, 1);
  12123. index--;
  12124. }
  12125. }
  12126. engine.bindSamplers(this);
  12127. this._isReady = true;
  12128. if (this.onCompiled) {
  12129. this.onCompiled(this);
  12130. }
  12131. } catch (e) {
  12132. // Is it a problem with precision?
  12133. if (e.message.indexOf("highp") !== -1) {
  12134. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  12135. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  12136. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  12137. return;
  12138. }
  12139. // Let's go through fallbacks then
  12140. if (fallbacks && fallbacks.isMoreFallbacks) {
  12141. defines = fallbacks.reduce(defines);
  12142. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  12143. } else {
  12144. BABYLON.Tools.Error("Unable to compile effect: " + this.name);
  12145. BABYLON.Tools.Error("Defines: " + defines);
  12146. BABYLON.Tools.Error("Error: " + e.message);
  12147. this._compilationError = e.message;
  12148. if (this.onError) {
  12149. this.onError(this, this._compilationError);
  12150. }
  12151. }
  12152. }
  12153. };
  12154. Effect.prototype._bindTexture = function (channel, texture) {
  12155. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  12156. };
  12157. Effect.prototype.setTexture = function (channel, texture) {
  12158. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  12159. };
  12160. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  12161. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  12162. };
  12163. //public _cacheMatrix(uniformName, matrix) {
  12164. // if (!this._valueCache[uniformName]) {
  12165. // this._valueCache[uniformName] = new BABYLON.Matrix();
  12166. // }
  12167. // for (var index = 0; index < 16; index++) {
  12168. // this._valueCache[uniformName].m[index] = matrix.m[index];
  12169. // }
  12170. //};
  12171. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  12172. if (!this._valueCache[uniformName]) {
  12173. this._valueCache[uniformName] = [x, y];
  12174. return;
  12175. }
  12176. this._valueCache[uniformName][0] = x;
  12177. this._valueCache[uniformName][1] = y;
  12178. };
  12179. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  12180. if (!this._valueCache[uniformName]) {
  12181. this._valueCache[uniformName] = [x, y, z];
  12182. return;
  12183. }
  12184. this._valueCache[uniformName][0] = x;
  12185. this._valueCache[uniformName][1] = y;
  12186. this._valueCache[uniformName][2] = z;
  12187. };
  12188. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  12189. if (!this._valueCache[uniformName]) {
  12190. this._valueCache[uniformName] = [x, y, z, w];
  12191. return;
  12192. }
  12193. this._valueCache[uniformName][0] = x;
  12194. this._valueCache[uniformName][1] = y;
  12195. this._valueCache[uniformName][2] = z;
  12196. this._valueCache[uniformName][3] = w;
  12197. };
  12198. Effect.prototype.setArray = function (uniformName, array) {
  12199. this._engine.setArray(this.getUniform(uniformName), array);
  12200. return this;
  12201. };
  12202. Effect.prototype.setMatrices = function (uniformName, matrices) {
  12203. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  12204. return this;
  12205. };
  12206. Effect.prototype.setMatrix = function (uniformName, matrix) {
  12207. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  12208. // return;
  12209. //this._cacheMatrix(uniformName, matrix);
  12210. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  12211. return this;
  12212. };
  12213. Effect.prototype.setFloat = function (uniformName, value) {
  12214. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  12215. return this;
  12216. this._valueCache[uniformName] = value;
  12217. this._engine.setFloat(this.getUniform(uniformName), value);
  12218. return this;
  12219. };
  12220. Effect.prototype.setBool = function (uniformName, bool) {
  12221. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  12222. return this;
  12223. this._valueCache[uniformName] = bool;
  12224. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  12225. return this;
  12226. };
  12227. Effect.prototype.setVector2 = function (uniformName, vector2) {
  12228. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  12229. return this;
  12230. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  12231. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  12232. return this;
  12233. };
  12234. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  12235. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  12236. return this;
  12237. this._cacheFloat2(uniformName, x, y);
  12238. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  12239. return this;
  12240. };
  12241. Effect.prototype.setVector3 = function (uniformName, vector3) {
  12242. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  12243. return this;
  12244. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  12245. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  12246. return this;
  12247. };
  12248. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  12249. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  12250. return this;
  12251. this._cacheFloat3(uniformName, x, y, z);
  12252. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  12253. return this;
  12254. };
  12255. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  12256. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  12257. return this;
  12258. this._cacheFloat4(uniformName, x, y, z, w);
  12259. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  12260. return this;
  12261. };
  12262. Effect.prototype.setColor3 = function (uniformName, color3) {
  12263. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  12264. return this;
  12265. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  12266. this._engine.setColor3(this.getUniform(uniformName), color3);
  12267. return this;
  12268. };
  12269. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  12270. 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)
  12271. return this;
  12272. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  12273. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  12274. return this;
  12275. };
  12276. 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}",
  12277. 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}",
  12278. 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}",
  12279. 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}",
  12280. 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}",
  12281. colorPixelShader:"precision highp float;\n\nuniform vec4 color;\n\nvoid main(void) {\n gl_FragColor = color;\n}",
  12282. 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}",
  12283. 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}",
  12284. 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}",
  12285. 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}",
  12286. 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}",
  12287. 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}",
  12288. 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}",
  12289. 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}",
  12290. 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}",
  12291. 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}",
  12292. 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}",
  12293. 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}",
  12294. 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}",
  12295. 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}",
  12296. 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}",
  12297. 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}",
  12298. 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}",
  12299. 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}",
  12300. 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}",
  12301. 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}",
  12302. 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}",
  12303. 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}",
  12304. 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}",
  12305. 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}",
  12306. 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}",
  12307. 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}",
  12308. 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}",
  12309. 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}",
  12310. 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}",
  12311. 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}",
  12312. 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}",
  12313. };
  12314. return Effect;
  12315. })();
  12316. BABYLON.Effect = Effect;
  12317. })(BABYLON || (BABYLON = {}));
  12318. //# sourceMappingURL=babylon.effect.js.map
  12319. var BABYLON;
  12320. (function (BABYLON) {
  12321. var Material = (function () {
  12322. function Material(name, scene, doNotAdd) {
  12323. this.name = name;
  12324. this.checkReadyOnEveryCall = true;
  12325. this.checkReadyOnlyOnce = false;
  12326. this.state = "";
  12327. this.alpha = 1.0;
  12328. this.backFaceCulling = true;
  12329. this._wasPreviouslyReady = false;
  12330. this._fillMode = Material.TriangleFillMode;
  12331. this.pointSize = 1.0;
  12332. this.id = name;
  12333. this._scene = scene;
  12334. if (!doNotAdd) {
  12335. scene.materials.push(this);
  12336. }
  12337. }
  12338. Object.defineProperty(Material, "TriangleFillMode", {
  12339. get: function () {
  12340. return Material._TriangleFillMode;
  12341. },
  12342. enumerable: true,
  12343. configurable: true
  12344. });
  12345. Object.defineProperty(Material, "WireFrameFillMode", {
  12346. get: function () {
  12347. return Material._WireFrameFillMode;
  12348. },
  12349. enumerable: true,
  12350. configurable: true
  12351. });
  12352. Object.defineProperty(Material, "PointFillMode", {
  12353. get: function () {
  12354. return Material._PointFillMode;
  12355. },
  12356. enumerable: true,
  12357. configurable: true
  12358. });
  12359. Object.defineProperty(Material.prototype, "wireframe", {
  12360. get: function () {
  12361. return this._fillMode === Material.WireFrameFillMode;
  12362. },
  12363. set: function (value) {
  12364. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  12365. },
  12366. enumerable: true,
  12367. configurable: true
  12368. });
  12369. Object.defineProperty(Material.prototype, "pointsCloud", {
  12370. get: function () {
  12371. return this._fillMode === Material.PointFillMode;
  12372. },
  12373. set: function (value) {
  12374. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  12375. },
  12376. enumerable: true,
  12377. configurable: true
  12378. });
  12379. Object.defineProperty(Material.prototype, "fillMode", {
  12380. get: function () {
  12381. return this._fillMode;
  12382. },
  12383. set: function (value) {
  12384. this._fillMode = value;
  12385. },
  12386. enumerable: true,
  12387. configurable: true
  12388. });
  12389. Material.prototype.isReady = function (mesh, useInstances) {
  12390. return true;
  12391. };
  12392. Material.prototype.getEffect = function () {
  12393. return this._effect;
  12394. };
  12395. Material.prototype.getScene = function () {
  12396. return this._scene;
  12397. };
  12398. Material.prototype.needAlphaBlending = function () {
  12399. return (this.alpha < 1.0);
  12400. };
  12401. Material.prototype.needAlphaTesting = function () {
  12402. return false;
  12403. };
  12404. Material.prototype.getAlphaTestTexture = function () {
  12405. return null;
  12406. };
  12407. Material.prototype.trackCreation = function (onCompiled, onError) {
  12408. };
  12409. Material.prototype._preBind = function () {
  12410. var engine = this._scene.getEngine();
  12411. engine.enableEffect(this._effect);
  12412. engine.setState(this.backFaceCulling);
  12413. };
  12414. Material.prototype.bind = function (world, mesh) {
  12415. this._scene._cachedMaterial = this;
  12416. if (this.onBind) {
  12417. this.onBind(this);
  12418. }
  12419. };
  12420. Material.prototype.bindOnlyWorldMatrix = function (world) {
  12421. };
  12422. Material.prototype.unbind = function () {
  12423. };
  12424. Material.prototype.dispose = function (forceDisposeEffect) {
  12425. // Remove from scene
  12426. var index = this._scene.materials.indexOf(this);
  12427. this._scene.materials.splice(index, 1);
  12428. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  12429. if (forceDisposeEffect && this._effect) {
  12430. this._scene.getEngine()._releaseEffect(this._effect);
  12431. this._effect = null;
  12432. }
  12433. // Callback
  12434. if (this.onDispose) {
  12435. this.onDispose();
  12436. }
  12437. };
  12438. Material._TriangleFillMode = 0;
  12439. Material._WireFrameFillMode = 1;
  12440. Material._PointFillMode = 2;
  12441. return Material;
  12442. })();
  12443. BABYLON.Material = Material;
  12444. })(BABYLON || (BABYLON = {}));
  12445. //# sourceMappingURL=babylon.material.js.map
  12446. var BABYLON;
  12447. (function (BABYLON) {
  12448. var maxSimultaneousLights = 4;
  12449. var FresnelParameters = (function () {
  12450. function FresnelParameters() {
  12451. this.isEnabled = true;
  12452. this.leftColor = BABYLON.Color3.White();
  12453. this.rightColor = BABYLON.Color3.Black();
  12454. this.bias = 0;
  12455. this.power = 1;
  12456. }
  12457. return FresnelParameters;
  12458. })();
  12459. BABYLON.FresnelParameters = FresnelParameters;
  12460. var StandardMaterial = (function (_super) {
  12461. __extends(StandardMaterial, _super);
  12462. function StandardMaterial(name, scene) {
  12463. var _this = this;
  12464. _super.call(this, name, scene);
  12465. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  12466. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  12467. this.specularColor = new BABYLON.Color3(1, 1, 1);
  12468. this.specularPower = 64;
  12469. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  12470. this.useAlphaFromDiffuseTexture = false;
  12471. this.useSpecularOverAlpha = true;
  12472. this.fogEnabled = true;
  12473. this._cachedDefines = null;
  12474. this._renderTargets = new BABYLON.SmartArray(16);
  12475. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  12476. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  12477. this._scaledDiffuse = new BABYLON.Color3();
  12478. this._scaledSpecular = new BABYLON.Color3();
  12479. this.getRenderTargetTextures = function () {
  12480. _this._renderTargets.reset();
  12481. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  12482. _this._renderTargets.push(_this.reflectionTexture);
  12483. }
  12484. return _this._renderTargets;
  12485. };
  12486. }
  12487. StandardMaterial.prototype.needAlphaBlending = function () {
  12488. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  12489. };
  12490. StandardMaterial.prototype.needAlphaTesting = function () {
  12491. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && !this.diffuseTexture.getAlphaFromRGB;
  12492. };
  12493. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  12494. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  12495. };
  12496. StandardMaterial.prototype.getAlphaTestTexture = function () {
  12497. return this.diffuseTexture;
  12498. };
  12499. // Methods
  12500. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  12501. if (this.checkReadyOnlyOnce) {
  12502. if (this._wasPreviouslyReady) {
  12503. return true;
  12504. }
  12505. }
  12506. var scene = this.getScene();
  12507. if (!this.checkReadyOnEveryCall) {
  12508. if (this._renderId === scene.getRenderId()) {
  12509. return true;
  12510. }
  12511. }
  12512. var engine = scene.getEngine();
  12513. var defines = [];
  12514. var fallbacks = new BABYLON.EffectFallbacks();
  12515. // Textures
  12516. if (scene.texturesEnabled) {
  12517. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  12518. if (!this.diffuseTexture.isReady()) {
  12519. return false;
  12520. } else {
  12521. defines.push("#define DIFFUSE");
  12522. }
  12523. }
  12524. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  12525. if (!this.ambientTexture.isReady()) {
  12526. return false;
  12527. } else {
  12528. defines.push("#define AMBIENT");
  12529. }
  12530. }
  12531. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  12532. if (!this.opacityTexture.isReady()) {
  12533. return false;
  12534. } else {
  12535. defines.push("#define OPACITY");
  12536. if (this.opacityTexture.getAlphaFromRGB) {
  12537. defines.push("#define OPACITYRGB");
  12538. }
  12539. }
  12540. }
  12541. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  12542. if (!this.reflectionTexture.isReady()) {
  12543. return false;
  12544. } else {
  12545. defines.push("#define REFLECTION");
  12546. fallbacks.addFallback(0, "REFLECTION");
  12547. }
  12548. }
  12549. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  12550. if (!this.emissiveTexture.isReady()) {
  12551. return false;
  12552. } else {
  12553. defines.push("#define EMISSIVE");
  12554. }
  12555. }
  12556. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  12557. if (!this.specularTexture.isReady()) {
  12558. return false;
  12559. } else {
  12560. defines.push("#define SPECULAR");
  12561. fallbacks.addFallback(0, "SPECULAR");
  12562. }
  12563. }
  12564. }
  12565. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  12566. if (!this.bumpTexture.isReady()) {
  12567. return false;
  12568. } else {
  12569. defines.push("#define BUMP");
  12570. fallbacks.addFallback(0, "BUMP");
  12571. }
  12572. }
  12573. // Effect
  12574. if (this.useSpecularOverAlpha) {
  12575. defines.push("#define SPECULAROVERALPHA");
  12576. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  12577. }
  12578. if (scene.clipPlane) {
  12579. defines.push("#define CLIPPLANE");
  12580. }
  12581. if (engine.getAlphaTesting()) {
  12582. defines.push("#define ALPHATEST");
  12583. }
  12584. if (this._shouldUseAlphaFromDiffuseTexture()) {
  12585. defines.push("#define ALPHAFROMDIFFUSE");
  12586. }
  12587. // Point size
  12588. if (this.pointsCloud || scene.forcePointsCloud) {
  12589. defines.push("#define POINTSIZE");
  12590. }
  12591. // Fog
  12592. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  12593. defines.push("#define FOG");
  12594. fallbacks.addFallback(1, "FOG");
  12595. }
  12596. var shadowsActivated = false;
  12597. var lightIndex = 0;
  12598. if (scene.lightsEnabled) {
  12599. for (var index = 0; index < scene.lights.length; index++) {
  12600. var light = scene.lights[index];
  12601. if (!light.isEnabled()) {
  12602. continue;
  12603. }
  12604. // Excluded check
  12605. if (light._excludedMeshesIds.length > 0) {
  12606. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  12607. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  12608. if (excludedMesh) {
  12609. light.excludedMeshes.push(excludedMesh);
  12610. }
  12611. }
  12612. light._excludedMeshesIds = [];
  12613. }
  12614. // Included check
  12615. if (light._includedOnlyMeshesIds.length > 0) {
  12616. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  12617. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  12618. if (includedOnlyMesh) {
  12619. light.includedOnlyMeshes.push(includedOnlyMesh);
  12620. }
  12621. }
  12622. light._includedOnlyMeshesIds = [];
  12623. }
  12624. if (!light.canAffectMesh(mesh)) {
  12625. continue;
  12626. }
  12627. defines.push("#define LIGHT" + lightIndex);
  12628. if (lightIndex > 0) {
  12629. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  12630. }
  12631. var type;
  12632. if (light instanceof BABYLON.SpotLight) {
  12633. type = "#define SPOTLIGHT" + lightIndex;
  12634. } else if (light instanceof BABYLON.HemisphericLight) {
  12635. type = "#define HEMILIGHT" + lightIndex;
  12636. } else {
  12637. type = "#define POINTDIRLIGHT" + lightIndex;
  12638. }
  12639. defines.push(type);
  12640. if (lightIndex > 0) {
  12641. fallbacks.addFallback(lightIndex, type.replace("#define ", ""));
  12642. }
  12643. // Shadows
  12644. if (scene.shadowsEnabled) {
  12645. var shadowGenerator = light.getShadowGenerator();
  12646. if (mesh && mesh.receiveShadows && shadowGenerator) {
  12647. defines.push("#define SHADOW" + lightIndex);
  12648. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  12649. if (!shadowsActivated) {
  12650. defines.push("#define SHADOWS");
  12651. shadowsActivated = true;
  12652. }
  12653. if (shadowGenerator.useVarianceShadowMap) {
  12654. defines.push("#define SHADOWVSM" + lightIndex);
  12655. if (lightIndex > 0) {
  12656. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  12657. }
  12658. }
  12659. if (shadowGenerator.usePoissonSampling) {
  12660. defines.push("#define SHADOWPCF" + lightIndex);
  12661. if (lightIndex > 0) {
  12662. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  12663. }
  12664. }
  12665. }
  12666. }
  12667. lightIndex++;
  12668. if (lightIndex === maxSimultaneousLights)
  12669. break;
  12670. }
  12671. }
  12672. if (StandardMaterial.FresnelEnabled) {
  12673. // Fresnel
  12674. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled || this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled || this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  12675. var fresnelRank = 1;
  12676. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  12677. defines.push("#define DIFFUSEFRESNEL");
  12678. fallbacks.addFallback(fresnelRank, "DIFFUSEFRESNEL");
  12679. fresnelRank++;
  12680. }
  12681. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  12682. defines.push("#define OPACITYFRESNEL");
  12683. fallbacks.addFallback(fresnelRank, "OPACITYFRESNEL");
  12684. fresnelRank++;
  12685. }
  12686. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  12687. defines.push("#define REFLECTIONFRESNEL");
  12688. fallbacks.addFallback(fresnelRank, "REFLECTIONFRESNEL");
  12689. fresnelRank++;
  12690. }
  12691. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  12692. defines.push("#define EMISSIVEFRESNEL");
  12693. fallbacks.addFallback(fresnelRank, "EMISSIVEFRESNEL");
  12694. fresnelRank++;
  12695. }
  12696. defines.push("#define FRESNEL");
  12697. fallbacks.addFallback(fresnelRank - 1, "FRESNEL");
  12698. }
  12699. }
  12700. // Attribs
  12701. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  12702. if (mesh) {
  12703. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  12704. attribs.push(BABYLON.VertexBuffer.UVKind);
  12705. defines.push("#define UV1");
  12706. }
  12707. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  12708. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  12709. defines.push("#define UV2");
  12710. }
  12711. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  12712. attribs.push(BABYLON.VertexBuffer.ColorKind);
  12713. defines.push("#define VERTEXCOLOR");
  12714. if (mesh.hasVertexAlpha) {
  12715. defines.push("#define VERTEXALPHA");
  12716. }
  12717. }
  12718. if (mesh.skeleton && scene.skeletonsEnabled && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  12719. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  12720. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  12721. defines.push("#define BONES");
  12722. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  12723. defines.push("#define BONES4");
  12724. fallbacks.addFallback(0, "BONES4");
  12725. }
  12726. // Instances
  12727. if (useInstances) {
  12728. defines.push("#define INSTANCES");
  12729. attribs.push("world0");
  12730. attribs.push("world1");
  12731. attribs.push("world2");
  12732. attribs.push("world3");
  12733. }
  12734. }
  12735. // Get correct effect
  12736. var join = defines.join("\n");
  12737. if (this._cachedDefines !== join) {
  12738. this._cachedDefines = join;
  12739. scene.resetCachedMaterial();
  12740. // Legacy browser patch
  12741. var shaderName = "default";
  12742. if (!scene.getEngine().getCaps().standardDerivatives) {
  12743. shaderName = "legacydefault";
  12744. }
  12745. this._effect = scene.getEngine().createEffect(shaderName, attribs, [
  12746. "world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  12747. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  12748. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  12749. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  12750. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  12751. "vFogInfos", "vFogColor", "pointSize",
  12752. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos",
  12753. "mBones",
  12754. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix",
  12755. "darkness0", "darkness1", "darkness2", "darkness3",
  12756. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor"
  12757. ], [
  12758. "diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler",
  12759. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  12760. ], join, fallbacks, this.onCompiled, this.onError);
  12761. }
  12762. if (!this._effect.isReady()) {
  12763. return false;
  12764. }
  12765. this._renderId = scene.getRenderId();
  12766. this._wasPreviouslyReady = true;
  12767. return true;
  12768. };
  12769. StandardMaterial.prototype.unbind = function () {
  12770. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  12771. this._effect.setTexture("reflection2DSampler", null);
  12772. }
  12773. };
  12774. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  12775. this._effect.setMatrix("world", world);
  12776. };
  12777. StandardMaterial.prototype.bind = function (world, mesh) {
  12778. var scene = this.getScene();
  12779. // Matrices
  12780. this.bindOnlyWorldMatrix(world);
  12781. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  12782. // Bones
  12783. if (mesh.skeleton && scene.skeletonsEnabled && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  12784. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  12785. }
  12786. if (scene.getCachedMaterial() !== this) {
  12787. if (StandardMaterial.FresnelEnabled) {
  12788. // Fresnel
  12789. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  12790. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  12791. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  12792. }
  12793. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  12794. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  12795. }
  12796. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  12797. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  12798. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  12799. }
  12800. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  12801. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  12802. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  12803. }
  12804. }
  12805. // Textures
  12806. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  12807. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  12808. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  12809. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  12810. }
  12811. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  12812. this._effect.setTexture("ambientSampler", this.ambientTexture);
  12813. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  12814. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  12815. }
  12816. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  12817. this._effect.setTexture("opacitySampler", this.opacityTexture);
  12818. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  12819. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  12820. }
  12821. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  12822. if (this.reflectionTexture.isCube) {
  12823. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  12824. } else {
  12825. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  12826. }
  12827. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  12828. this._effect.setFloat3("vReflectionInfos", this.reflectionTexture.coordinatesMode, this.reflectionTexture.level, this.reflectionTexture.isCube ? 1 : 0);
  12829. }
  12830. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  12831. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  12832. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  12833. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  12834. }
  12835. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  12836. this._effect.setTexture("specularSampler", this.specularTexture);
  12837. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  12838. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  12839. }
  12840. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  12841. this._effect.setTexture("bumpSampler", this.bumpTexture);
  12842. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level);
  12843. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  12844. }
  12845. // Clip plane
  12846. if (scene.clipPlane) {
  12847. var clipPlane = scene.clipPlane;
  12848. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  12849. }
  12850. // Point size
  12851. if (this.pointsCloud) {
  12852. this._effect.setFloat("pointSize", this.pointSize);
  12853. }
  12854. // Colors
  12855. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  12856. // Scaling down color according to emissive
  12857. this._scaledSpecular.r = this.specularColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  12858. this._scaledSpecular.g = this.specularColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  12859. this._scaledSpecular.b = this.specularColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  12860. this._effect.setVector3("vEyePosition", scene.activeCamera.position);
  12861. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  12862. this._effect.setColor4("vSpecularColor", this._scaledSpecular, this.specularPower);
  12863. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  12864. }
  12865. // Scaling down color according to emissive
  12866. this._scaledDiffuse.r = this.diffuseColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  12867. this._scaledDiffuse.g = this.diffuseColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  12868. this._scaledDiffuse.b = this.diffuseColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  12869. this._effect.setColor4("vDiffuseColor", this._scaledDiffuse, this.alpha * mesh.visibility);
  12870. if (scene.lightsEnabled) {
  12871. var lightIndex = 0;
  12872. for (var index = 0; index < scene.lights.length; index++) {
  12873. var light = scene.lights[index];
  12874. if (!light.isEnabled()) {
  12875. continue;
  12876. }
  12877. if (!light.canAffectMesh(mesh)) {
  12878. continue;
  12879. }
  12880. if (light instanceof BABYLON.PointLight) {
  12881. // Point Light
  12882. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  12883. } else if (light instanceof BABYLON.DirectionalLight) {
  12884. // Directional Light
  12885. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  12886. } else if (light instanceof BABYLON.SpotLight) {
  12887. // Spot Light
  12888. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  12889. } else if (light instanceof BABYLON.HemisphericLight) {
  12890. // Hemispheric Light
  12891. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  12892. }
  12893. light.diffuse.scaleToRef(light.intensity, this._scaledDiffuse);
  12894. light.specular.scaleToRef(light.intensity, this._scaledSpecular);
  12895. this._effect.setColor4("vLightDiffuse" + lightIndex, this._scaledDiffuse, light.range);
  12896. this._effect.setColor3("vLightSpecular" + lightIndex, this._scaledSpecular);
  12897. // Shadows
  12898. if (scene.shadowsEnabled) {
  12899. var shadowGenerator = light.getShadowGenerator();
  12900. if (mesh.receiveShadows && shadowGenerator) {
  12901. this._effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  12902. this._effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMap());
  12903. this._effect.setFloat("darkness" + lightIndex, shadowGenerator.getDarkness());
  12904. }
  12905. }
  12906. lightIndex++;
  12907. if (lightIndex === maxSimultaneousLights)
  12908. break;
  12909. }
  12910. }
  12911. // View
  12912. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  12913. this._effect.setMatrix("view", scene.getViewMatrix());
  12914. }
  12915. // Fog
  12916. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  12917. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  12918. this._effect.setColor3("vFogColor", scene.fogColor);
  12919. }
  12920. _super.prototype.bind.call(this, world, mesh);
  12921. };
  12922. StandardMaterial.prototype.getAnimatables = function () {
  12923. var results = [];
  12924. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  12925. results.push(this.diffuseTexture);
  12926. }
  12927. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  12928. results.push(this.ambientTexture);
  12929. }
  12930. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  12931. results.push(this.opacityTexture);
  12932. }
  12933. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  12934. results.push(this.reflectionTexture);
  12935. }
  12936. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  12937. results.push(this.emissiveTexture);
  12938. }
  12939. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  12940. results.push(this.specularTexture);
  12941. }
  12942. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  12943. results.push(this.bumpTexture);
  12944. }
  12945. return results;
  12946. };
  12947. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  12948. if (this.diffuseTexture) {
  12949. this.diffuseTexture.dispose();
  12950. }
  12951. if (this.ambientTexture) {
  12952. this.ambientTexture.dispose();
  12953. }
  12954. if (this.opacityTexture) {
  12955. this.opacityTexture.dispose();
  12956. }
  12957. if (this.reflectionTexture) {
  12958. this.reflectionTexture.dispose();
  12959. }
  12960. if (this.emissiveTexture) {
  12961. this.emissiveTexture.dispose();
  12962. }
  12963. if (this.specularTexture) {
  12964. this.specularTexture.dispose();
  12965. }
  12966. if (this.bumpTexture) {
  12967. this.bumpTexture.dispose();
  12968. }
  12969. _super.prototype.dispose.call(this, forceDisposeEffect);
  12970. };
  12971. StandardMaterial.prototype.clone = function (name) {
  12972. var newStandardMaterial = new StandardMaterial(name, this.getScene());
  12973. // Base material
  12974. newStandardMaterial.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  12975. newStandardMaterial.alpha = this.alpha;
  12976. newStandardMaterial.fillMode = this.fillMode;
  12977. newStandardMaterial.backFaceCulling = this.backFaceCulling;
  12978. // Standard material
  12979. if (this.diffuseTexture && this.diffuseTexture.clone) {
  12980. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  12981. }
  12982. if (this.ambientTexture && this.ambientTexture.clone) {
  12983. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  12984. }
  12985. if (this.opacityTexture && this.opacityTexture.clone) {
  12986. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  12987. }
  12988. if (this.reflectionTexture && this.reflectionTexture.clone) {
  12989. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  12990. }
  12991. if (this.emissiveTexture && this.emissiveTexture.clone) {
  12992. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  12993. }
  12994. if (this.specularTexture && this.specularTexture.clone) {
  12995. newStandardMaterial.specularTexture = this.specularTexture.clone();
  12996. }
  12997. if (this.bumpTexture && this.bumpTexture.clone) {
  12998. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  12999. }
  13000. newStandardMaterial.ambientColor = this.ambientColor.clone();
  13001. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  13002. newStandardMaterial.specularColor = this.specularColor.clone();
  13003. newStandardMaterial.specularPower = this.specularPower;
  13004. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  13005. return newStandardMaterial;
  13006. };
  13007. StandardMaterial.DiffuseTextureEnabled = true;
  13008. StandardMaterial.AmbientTextureEnabled = true;
  13009. StandardMaterial.OpacityTextureEnabled = true;
  13010. StandardMaterial.ReflectionTextureEnabled = true;
  13011. StandardMaterial.EmissiveTextureEnabled = true;
  13012. StandardMaterial.SpecularTextureEnabled = true;
  13013. StandardMaterial.BumpTextureEnabled = true;
  13014. StandardMaterial.FresnelEnabled = true;
  13015. return StandardMaterial;
  13016. })(BABYLON.Material);
  13017. BABYLON.StandardMaterial = StandardMaterial;
  13018. })(BABYLON || (BABYLON = {}));
  13019. //# sourceMappingURL=babylon.standardMaterial.js.map
  13020. var BABYLON;
  13021. (function (BABYLON) {
  13022. var MultiMaterial = (function (_super) {
  13023. __extends(MultiMaterial, _super);
  13024. function MultiMaterial(name, scene) {
  13025. _super.call(this, name, scene, true);
  13026. this.subMaterials = new Array();
  13027. scene.multiMaterials.push(this);
  13028. }
  13029. // Properties
  13030. MultiMaterial.prototype.getSubMaterial = function (index) {
  13031. if (index < 0 || index >= this.subMaterials.length) {
  13032. return this.getScene().defaultMaterial;
  13033. }
  13034. return this.subMaterials[index];
  13035. };
  13036. // Methods
  13037. MultiMaterial.prototype.isReady = function (mesh) {
  13038. for (var index = 0; index < this.subMaterials.length; index++) {
  13039. var subMaterial = this.subMaterials[index];
  13040. if (subMaterial) {
  13041. if (!this.subMaterials[index].isReady(mesh)) {
  13042. return false;
  13043. }
  13044. }
  13045. }
  13046. return true;
  13047. };
  13048. return MultiMaterial;
  13049. })(BABYLON.Material);
  13050. BABYLON.MultiMaterial = MultiMaterial;
  13051. })(BABYLON || (BABYLON = {}));
  13052. //# sourceMappingURL=babylon.multiMaterial.js.map
  13053. var BABYLON;
  13054. (function (BABYLON) {
  13055. var Database = (function () {
  13056. function Database(urlToScene, callbackManifestChecked) {
  13057. // Handling various flavors of prefixed version of IndexedDB
  13058. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  13059. this.callbackManifestChecked = callbackManifestChecked;
  13060. this.currentSceneUrl = BABYLON.Database.ReturnFullUrlLocation(urlToScene);
  13061. this.db = null;
  13062. this.enableSceneOffline = false;
  13063. this.enableTexturesOffline = false;
  13064. this.manifestVersionFound = 0;
  13065. this.mustUpdateRessources = false;
  13066. this.hasReachedQuota = false;
  13067. this.checkManifestFile();
  13068. }
  13069. Database.prototype.checkManifestFile = function () {
  13070. var _this = this;
  13071. function noManifestFile() {
  13072. BABYLON.Tools.Log("Valid manifest file not found. Scene & textures will be loaded directly from the web server.");
  13073. that.enableSceneOffline = false;
  13074. that.enableTexturesOffline = false;
  13075. that.callbackManifestChecked(false);
  13076. }
  13077. var that = this;
  13078. var manifestURL = this.currentSceneUrl + ".manifest";
  13079. var xhr = new XMLHttpRequest();
  13080. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  13081. xhr.open("GET", manifestURLTimeStamped, true);
  13082. xhr.addEventListener("load", function () {
  13083. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  13084. try {
  13085. var manifestFile = JSON.parse(xhr.response);
  13086. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  13087. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  13088. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  13089. _this.manifestVersionFound = manifestFile.version;
  13090. }
  13091. if (_this.callbackManifestChecked) {
  13092. _this.callbackManifestChecked(true);
  13093. }
  13094. } catch (ex) {
  13095. noManifestFile();
  13096. }
  13097. } else {
  13098. noManifestFile();
  13099. }
  13100. }, false);
  13101. xhr.addEventListener("error", function (event) {
  13102. noManifestFile();
  13103. }, false);
  13104. try {
  13105. xhr.send();
  13106. } catch (ex) {
  13107. BABYLON.Tools.Error("Error on XHR send request.");
  13108. that.callbackManifestChecked(false);
  13109. }
  13110. };
  13111. Database.prototype.openAsync = function (successCallback, errorCallback) {
  13112. var _this = this;
  13113. function handleError() {
  13114. that.isSupported = false;
  13115. if (errorCallback)
  13116. errorCallback();
  13117. }
  13118. var that = this;
  13119. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  13120. // Your browser doesn't support IndexedDB
  13121. this.isSupported = false;
  13122. if (errorCallback)
  13123. errorCallback();
  13124. } else {
  13125. // If the DB hasn't been opened or created yet
  13126. if (!this.db) {
  13127. this.hasReachedQuota = false;
  13128. this.isSupported = true;
  13129. var request = this.idbFactory.open("babylonjs", 1);
  13130. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  13131. request.onerror = function (event) {
  13132. handleError();
  13133. };
  13134. // executes when a version change transaction cannot complete due to other active transactions
  13135. request.onblocked = function (event) {
  13136. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  13137. handleError();
  13138. };
  13139. // DB has been opened successfully
  13140. request.onsuccess = function (event) {
  13141. _this.db = request.result;
  13142. successCallback();
  13143. };
  13144. // Initialization of the DB. Creating Scenes & Textures stores
  13145. request.onupgradeneeded = function (event) {
  13146. _this.db = (event.target).result;
  13147. try {
  13148. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  13149. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  13150. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  13151. } catch (ex) {
  13152. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  13153. handleError();
  13154. }
  13155. };
  13156. } else {
  13157. if (successCallback)
  13158. successCallback();
  13159. }
  13160. }
  13161. };
  13162. Database.prototype.loadImageFromDB = function (url, image) {
  13163. var _this = this;
  13164. var completeURL = BABYLON.Database.ReturnFullUrlLocation(url);
  13165. var saveAndLoadImage = function () {
  13166. if (!_this.hasReachedQuota && _this.db !== null) {
  13167. // the texture is not yet in the DB, let's try to save it
  13168. _this._saveImageIntoDBAsync(completeURL, image);
  13169. } else {
  13170. image.src = url;
  13171. }
  13172. };
  13173. if (!this.mustUpdateRessources) {
  13174. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  13175. } else {
  13176. saveAndLoadImage();
  13177. }
  13178. };
  13179. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  13180. if (this.isSupported && this.db !== null) {
  13181. var texture;
  13182. var transaction = this.db.transaction(["textures"]);
  13183. transaction.onabort = function (event) {
  13184. image.src = url;
  13185. };
  13186. transaction.oncomplete = function (event) {
  13187. var blobTextureURL;
  13188. if (texture) {
  13189. var URL = window.URL || window.webkitURL;
  13190. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  13191. image.onerror = function () {
  13192. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  13193. image.src = url;
  13194. };
  13195. image.src = blobTextureURL;
  13196. } else {
  13197. notInDBCallback();
  13198. }
  13199. };
  13200. var getRequest = transaction.objectStore("textures").get(url);
  13201. getRequest.onsuccess = function (event) {
  13202. texture = (event.target).result;
  13203. };
  13204. getRequest.onerror = function (event) {
  13205. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  13206. image.src = url;
  13207. };
  13208. } else {
  13209. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  13210. image.src = url;
  13211. }
  13212. };
  13213. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  13214. var _this = this;
  13215. if (this.isSupported) {
  13216. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  13217. var generateBlobUrl = function () {
  13218. var blobTextureURL;
  13219. if (blob) {
  13220. var URL = window.URL || window.webkitURL;
  13221. try {
  13222. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  13223. } catch (ex) {
  13224. blobTextureURL = URL.createObjectURL(blob);
  13225. }
  13226. }
  13227. image.src = blobTextureURL;
  13228. };
  13229. if (BABYLON.Database.isUASupportingBlobStorage) {
  13230. var xhr = new XMLHttpRequest(), blob;
  13231. xhr.open("GET", url, true);
  13232. xhr.responseType = "blob";
  13233. xhr.addEventListener("load", function () {
  13234. if (xhr.status === 200) {
  13235. // Blob as response (XHR2)
  13236. blob = xhr.response;
  13237. var transaction = _this.db.transaction(["textures"], "readwrite");
  13238. // the transaction could abort because of a QuotaExceededError error
  13239. transaction.onabort = function (event) {
  13240. try {
  13241. if (event.srcElement.error.name === "QuotaExceededError") {
  13242. this.hasReachedQuota = true;
  13243. }
  13244. } catch (ex) {
  13245. }
  13246. generateBlobUrl();
  13247. };
  13248. transaction.oncomplete = function (event) {
  13249. generateBlobUrl();
  13250. };
  13251. var newTexture = { textureUrl: url, data: blob };
  13252. try {
  13253. // Put the blob into the dabase
  13254. var addRequest = transaction.objectStore("textures").put(newTexture);
  13255. addRequest.onsuccess = function (event) {
  13256. };
  13257. addRequest.onerror = function (event) {
  13258. generateBlobUrl();
  13259. };
  13260. } catch (ex) {
  13261. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  13262. if (ex.code === 25) {
  13263. BABYLON.Database.isUASupportingBlobStorage = false;
  13264. }
  13265. image.src = url;
  13266. }
  13267. } else {
  13268. image.src = url;
  13269. }
  13270. }, false);
  13271. xhr.addEventListener("error", function (event) {
  13272. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  13273. image.src = url;
  13274. }, false);
  13275. xhr.send();
  13276. } else {
  13277. image.src = url;
  13278. }
  13279. } else {
  13280. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  13281. image.src = url;
  13282. }
  13283. };
  13284. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  13285. var _this = this;
  13286. var updateVersion = function (event) {
  13287. // the version is not yet in the DB or we need to update it
  13288. _this._saveVersionIntoDBAsync(url, versionLoaded);
  13289. };
  13290. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  13291. };
  13292. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  13293. var _this = this;
  13294. if (this.isSupported) {
  13295. var version;
  13296. try {
  13297. var transaction = this.db.transaction(["versions"]);
  13298. transaction.oncomplete = function (event) {
  13299. if (version) {
  13300. // If the version in the JSON file is > than the version in DB
  13301. if (_this.manifestVersionFound > version.data) {
  13302. _this.mustUpdateRessources = true;
  13303. updateInDBCallback();
  13304. } else {
  13305. callback(version.data);
  13306. }
  13307. } else {
  13308. _this.mustUpdateRessources = true;
  13309. updateInDBCallback();
  13310. }
  13311. };
  13312. transaction.onabort = function (event) {
  13313. callback(-1);
  13314. };
  13315. var getRequest = transaction.objectStore("versions").get(url);
  13316. getRequest.onsuccess = function (event) {
  13317. version = (event.target).result;
  13318. };
  13319. getRequest.onerror = function (event) {
  13320. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  13321. callback(-1);
  13322. };
  13323. } catch (ex) {
  13324. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  13325. callback(-1);
  13326. }
  13327. } else {
  13328. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  13329. callback(-1);
  13330. }
  13331. };
  13332. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  13333. var _this = this;
  13334. if (this.isSupported && !this.hasReachedQuota) {
  13335. try {
  13336. // Open a transaction to the database
  13337. var transaction = this.db.transaction(["versions"], "readwrite");
  13338. // the transaction could abort because of a QuotaExceededError error
  13339. transaction.onabort = function (event) {
  13340. try {
  13341. if (event.srcElement.error.name === "QuotaExceededError") {
  13342. _this.hasReachedQuota = true;
  13343. }
  13344. } catch (ex) {
  13345. }
  13346. callback(-1);
  13347. };
  13348. transaction.oncomplete = function (event) {
  13349. callback(_this.manifestVersionFound);
  13350. };
  13351. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  13352. // Put the scene into the database
  13353. var addRequest = transaction.objectStore("versions").put(newVersion);
  13354. addRequest.onsuccess = function (event) {
  13355. };
  13356. addRequest.onerror = function (event) {
  13357. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  13358. };
  13359. } catch (ex) {
  13360. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  13361. callback(-1);
  13362. }
  13363. } else {
  13364. callback(-1);
  13365. }
  13366. };
  13367. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  13368. var _this = this;
  13369. var completeUrl = BABYLON.Database.ReturnFullUrlLocation(url);
  13370. var saveAndLoadFile = function (event) {
  13371. // the scene is not yet in the DB, let's try to save it
  13372. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  13373. };
  13374. this._checkVersionFromDB(completeUrl, function (version) {
  13375. if (version !== -1) {
  13376. if (!_this.mustUpdateRessources) {
  13377. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  13378. } else {
  13379. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  13380. }
  13381. } else {
  13382. errorCallback();
  13383. }
  13384. });
  13385. };
  13386. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  13387. if (this.isSupported) {
  13388. var targetStore;
  13389. if (url.indexOf(".babylon") !== -1) {
  13390. targetStore = "scenes";
  13391. } else {
  13392. targetStore = "textures";
  13393. }
  13394. var file;
  13395. var transaction = this.db.transaction([targetStore]);
  13396. transaction.oncomplete = function (event) {
  13397. if (file) {
  13398. callback(file.data);
  13399. } else {
  13400. notInDBCallback();
  13401. }
  13402. };
  13403. transaction.onabort = function (event) {
  13404. notInDBCallback();
  13405. };
  13406. var getRequest = transaction.objectStore(targetStore).get(url);
  13407. getRequest.onsuccess = function (event) {
  13408. file = (event.target).result;
  13409. };
  13410. getRequest.onerror = function (event) {
  13411. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  13412. notInDBCallback();
  13413. };
  13414. } else {
  13415. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  13416. callback();
  13417. }
  13418. };
  13419. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  13420. var _this = this;
  13421. if (this.isSupported) {
  13422. var targetStore;
  13423. if (url.indexOf(".babylon") !== -1) {
  13424. targetStore = "scenes";
  13425. } else {
  13426. targetStore = "textures";
  13427. }
  13428. // Create XHR
  13429. var xhr = new XMLHttpRequest(), fileData;
  13430. xhr.open("GET", url, true);
  13431. if (useArrayBuffer) {
  13432. xhr.responseType = "arraybuffer";
  13433. }
  13434. xhr.onprogress = progressCallback;
  13435. xhr.addEventListener("load", function () {
  13436. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  13437. // Blob as response (XHR2)
  13438. //fileData = xhr.responseText;
  13439. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  13440. if (!_this.hasReachedQuota) {
  13441. // Open a transaction to the database
  13442. var transaction = _this.db.transaction([targetStore], "readwrite");
  13443. // the transaction could abort because of a QuotaExceededError error
  13444. transaction.onabort = function (event) {
  13445. try {
  13446. if (event.srcElement.error.name === "QuotaExceededError") {
  13447. this.hasReachedQuota = true;
  13448. }
  13449. } catch (ex) {
  13450. }
  13451. callback(fileData);
  13452. };
  13453. transaction.oncomplete = function (event) {
  13454. callback(fileData);
  13455. };
  13456. var newFile;
  13457. if (targetStore === "scenes") {
  13458. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  13459. } else {
  13460. newFile = { textureUrl: url, data: fileData };
  13461. }
  13462. try {
  13463. // Put the scene into the database
  13464. var addRequest = transaction.objectStore(targetStore).put(newFile);
  13465. addRequest.onsuccess = function (event) {
  13466. };
  13467. addRequest.onerror = function (event) {
  13468. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  13469. };
  13470. } catch (ex) {
  13471. callback(fileData);
  13472. }
  13473. } else {
  13474. callback(fileData);
  13475. }
  13476. } else {
  13477. callback();
  13478. }
  13479. }, false);
  13480. xhr.addEventListener("error", function (event) {
  13481. BABYLON.Tools.Error("error on XHR request.");
  13482. callback();
  13483. }, false);
  13484. xhr.send();
  13485. } else {
  13486. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  13487. callback();
  13488. }
  13489. };
  13490. Database.isUASupportingBlobStorage = true;
  13491. Database.parseURL = function (url) {
  13492. var a = document.createElement('a');
  13493. a.href = url;
  13494. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  13495. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  13496. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  13497. return absLocation;
  13498. };
  13499. Database.ReturnFullUrlLocation = function (url) {
  13500. if (url.indexOf("http:/") === -1) {
  13501. return (BABYLON.Database.parseURL(window.location.href) + url);
  13502. } else {
  13503. return url;
  13504. }
  13505. };
  13506. return Database;
  13507. })();
  13508. BABYLON.Database = Database;
  13509. })(BABYLON || (BABYLON = {}));
  13510. //# sourceMappingURL=babylon.database.js.map
  13511. var BABYLON;
  13512. (function (BABYLON) {
  13513. var SpriteManager = (function () {
  13514. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon) {
  13515. this.name = name;
  13516. this.cellSize = cellSize;
  13517. this.sprites = new Array();
  13518. this.renderingGroupId = 0;
  13519. this.fogEnabled = true;
  13520. this._vertexDeclaration = [3, 4, 4, 4];
  13521. this._vertexStrideSize = 15 * 4;
  13522. this._capacity = capacity;
  13523. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false);
  13524. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  13525. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  13526. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  13527. this._scene = scene;
  13528. this._scene.spriteManagers.push(this);
  13529. // VBO
  13530. this._vertexDeclaration = [3, 4, 4, 4];
  13531. this._vertexStrideSize = 15 * 4;
  13532. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  13533. var indices = [];
  13534. var index = 0;
  13535. for (var count = 0; count < capacity; count++) {
  13536. indices.push(index);
  13537. indices.push(index + 1);
  13538. indices.push(index + 2);
  13539. indices.push(index);
  13540. indices.push(index + 2);
  13541. indices.push(index + 3);
  13542. index += 4;
  13543. }
  13544. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  13545. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  13546. // Effects
  13547. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  13548. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  13549. }
  13550. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  13551. var arrayOffset = index * 15;
  13552. if (offsetX == 0)
  13553. offsetX = this._epsilon;
  13554. else if (offsetX == 1)
  13555. offsetX = 1 - this._epsilon;
  13556. if (offsetY == 0)
  13557. offsetY = this._epsilon;
  13558. else if (offsetY == 1)
  13559. offsetY = 1 - this._epsilon;
  13560. this._vertices[arrayOffset] = sprite.position.x;
  13561. this._vertices[arrayOffset + 1] = sprite.position.y;
  13562. this._vertices[arrayOffset + 2] = sprite.position.z;
  13563. this._vertices[arrayOffset + 3] = sprite.angle;
  13564. this._vertices[arrayOffset + 4] = sprite.size;
  13565. this._vertices[arrayOffset + 5] = offsetX;
  13566. this._vertices[arrayOffset + 6] = offsetY;
  13567. this._vertices[arrayOffset + 7] = sprite.invertU ? 1 : 0;
  13568. this._vertices[arrayOffset + 8] = sprite.invertV ? 1 : 0;
  13569. var offset = (sprite.cellIndex / rowSize) >> 0;
  13570. this._vertices[arrayOffset + 9] = sprite.cellIndex - offset * rowSize;
  13571. this._vertices[arrayOffset + 10] = offset;
  13572. // Color
  13573. this._vertices[arrayOffset + 11] = sprite.color.r;
  13574. this._vertices[arrayOffset + 12] = sprite.color.g;
  13575. this._vertices[arrayOffset + 13] = sprite.color.b;
  13576. this._vertices[arrayOffset + 14] = sprite.color.a;
  13577. };
  13578. SpriteManager.prototype.render = function () {
  13579. // Check
  13580. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  13581. return;
  13582. var engine = this._scene.getEngine();
  13583. var baseSize = this._spriteTexture.getBaseSize();
  13584. // Sprites
  13585. var deltaTime = engine.getDeltaTime();
  13586. var max = Math.min(this._capacity, this.sprites.length);
  13587. var rowSize = baseSize.width / this.cellSize;
  13588. var offset = 0;
  13589. for (var index = 0; index < max; index++) {
  13590. var sprite = this.sprites[index];
  13591. if (!sprite) {
  13592. continue;
  13593. }
  13594. sprite._animate(deltaTime);
  13595. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  13596. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  13597. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  13598. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  13599. }
  13600. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  13601. // Render
  13602. var effect = this._effectBase;
  13603. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  13604. effect = this._effectFog;
  13605. }
  13606. engine.enableEffect(effect);
  13607. var viewMatrix = this._scene.getViewMatrix();
  13608. effect.setTexture("diffuseSampler", this._spriteTexture);
  13609. effect.setMatrix("view", viewMatrix);
  13610. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  13611. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  13612. // Fog
  13613. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  13614. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  13615. effect.setColor3("vFogColor", this._scene.fogColor);
  13616. }
  13617. // VBOs
  13618. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  13619. // Draw order
  13620. effect.setBool("alphaTest", true);
  13621. engine.setColorWrite(false);
  13622. engine.draw(true, 0, max * 6);
  13623. engine.setColorWrite(true);
  13624. effect.setBool("alphaTest", false);
  13625. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  13626. engine.draw(true, 0, max * 6);
  13627. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  13628. };
  13629. SpriteManager.prototype.dispose = function () {
  13630. if (this._vertexBuffer) {
  13631. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  13632. this._vertexBuffer = null;
  13633. }
  13634. if (this._indexBuffer) {
  13635. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  13636. this._indexBuffer = null;
  13637. }
  13638. if (this._spriteTexture) {
  13639. this._spriteTexture.dispose();
  13640. this._spriteTexture = null;
  13641. }
  13642. // Remove from scene
  13643. var index = this._scene.spriteManagers.indexOf(this);
  13644. this._scene.spriteManagers.splice(index, 1);
  13645. // Callback
  13646. if (this.onDispose) {
  13647. this.onDispose();
  13648. }
  13649. };
  13650. return SpriteManager;
  13651. })();
  13652. BABYLON.SpriteManager = SpriteManager;
  13653. })(BABYLON || (BABYLON = {}));
  13654. //# sourceMappingURL=babylon.spriteManager.js.map
  13655. var BABYLON;
  13656. (function (BABYLON) {
  13657. var Sprite = (function () {
  13658. function Sprite(name, manager) {
  13659. this.name = name;
  13660. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  13661. this.size = 1.0;
  13662. this.angle = 0;
  13663. this.cellIndex = 0;
  13664. this.invertU = 0;
  13665. this.invertV = 0;
  13666. this.animations = new Array();
  13667. this._animationStarted = false;
  13668. this._loopAnimation = false;
  13669. this._fromIndex = 0;
  13670. this._toIndex = 0;
  13671. this._delay = 0;
  13672. this._direction = 1;
  13673. this._frameCount = 0;
  13674. this._time = 0;
  13675. this._manager = manager;
  13676. this._manager.sprites.push(this);
  13677. this.position = BABYLON.Vector3.Zero();
  13678. }
  13679. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  13680. this._fromIndex = from;
  13681. this._toIndex = to;
  13682. this._loopAnimation = loop;
  13683. this._delay = delay;
  13684. this._animationStarted = true;
  13685. this._direction = from < to ? 1 : -1;
  13686. this.cellIndex = from;
  13687. this._time = 0;
  13688. };
  13689. Sprite.prototype.stopAnimation = function () {
  13690. this._animationStarted = false;
  13691. };
  13692. Sprite.prototype._animate = function (deltaTime) {
  13693. if (!this._animationStarted)
  13694. return;
  13695. this._time += deltaTime;
  13696. if (this._time > this._delay) {
  13697. this._time = this._time % this._delay;
  13698. this.cellIndex += this._direction;
  13699. if (this.cellIndex == this._toIndex) {
  13700. if (this._loopAnimation) {
  13701. this.cellIndex = this._fromIndex;
  13702. } else {
  13703. this._animationStarted = false;
  13704. if (this.disposeWhenFinishedAnimating) {
  13705. this.dispose();
  13706. }
  13707. }
  13708. }
  13709. }
  13710. };
  13711. Sprite.prototype.dispose = function () {
  13712. for (var i = 0; i < this._manager.sprites.length; i++) {
  13713. if (this._manager.sprites[i] == this) {
  13714. this._manager.sprites.splice(i, 1);
  13715. }
  13716. }
  13717. };
  13718. return Sprite;
  13719. })();
  13720. BABYLON.Sprite = Sprite;
  13721. })(BABYLON || (BABYLON = {}));
  13722. //# sourceMappingURL=babylon.sprite.js.map
  13723. var BABYLON;
  13724. (function (BABYLON) {
  13725. var Layer = (function () {
  13726. function Layer(name, imgUrl, scene, isBackground, color) {
  13727. this.name = name;
  13728. this._vertexDeclaration = [2];
  13729. this._vertexStrideSize = 2 * 4;
  13730. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  13731. this.isBackground = isBackground === undefined ? true : isBackground;
  13732. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  13733. this._scene = scene;
  13734. this._scene.layers.push(this);
  13735. // VBO
  13736. var vertices = [];
  13737. vertices.push(1, 1);
  13738. vertices.push(-1, 1);
  13739. vertices.push(-1, -1);
  13740. vertices.push(1, -1);
  13741. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  13742. // Indices
  13743. var indices = [];
  13744. indices.push(0);
  13745. indices.push(1);
  13746. indices.push(2);
  13747. indices.push(0);
  13748. indices.push(2);
  13749. indices.push(3);
  13750. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  13751. // Effects
  13752. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  13753. }
  13754. Layer.prototype.render = function () {
  13755. // Check
  13756. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  13757. return;
  13758. var engine = this._scene.getEngine();
  13759. // Render
  13760. engine.enableEffect(this._effect);
  13761. engine.setState(false);
  13762. // Texture
  13763. this._effect.setTexture("textureSampler", this.texture);
  13764. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  13765. // Color
  13766. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  13767. // VBOs
  13768. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  13769. // Draw order
  13770. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  13771. engine.draw(true, 0, 6);
  13772. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  13773. };
  13774. Layer.prototype.dispose = function () {
  13775. if (this._vertexBuffer) {
  13776. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  13777. this._vertexBuffer = null;
  13778. }
  13779. if (this._indexBuffer) {
  13780. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  13781. this._indexBuffer = null;
  13782. }
  13783. if (this.texture) {
  13784. this.texture.dispose();
  13785. this.texture = null;
  13786. }
  13787. // Remove from scene
  13788. var index = this._scene.layers.indexOf(this);
  13789. this._scene.layers.splice(index, 1);
  13790. // Callback
  13791. if (this.onDispose) {
  13792. this.onDispose();
  13793. }
  13794. };
  13795. return Layer;
  13796. })();
  13797. BABYLON.Layer = Layer;
  13798. })(BABYLON || (BABYLON = {}));
  13799. //# sourceMappingURL=babylon.layer.js.map
  13800. var BABYLON;
  13801. (function (BABYLON) {
  13802. var Particle = (function () {
  13803. function Particle() {
  13804. this.position = BABYLON.Vector3.Zero();
  13805. this.direction = BABYLON.Vector3.Zero();
  13806. this.color = new BABYLON.Color4(0, 0, 0, 0);
  13807. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  13808. this.lifeTime = 1.0;
  13809. this.age = 0;
  13810. this.size = 0;
  13811. this.angle = 0;
  13812. this.angularSpeed = 0;
  13813. }
  13814. return Particle;
  13815. })();
  13816. BABYLON.Particle = Particle;
  13817. })(BABYLON || (BABYLON = {}));
  13818. //# sourceMappingURL=babylon.particle.js.map
  13819. var BABYLON;
  13820. (function (BABYLON) {
  13821. var randomNumber = function (min, max) {
  13822. if (min === max) {
  13823. return (min);
  13824. }
  13825. var random = Math.random();
  13826. return ((random * (max - min)) + min);
  13827. };
  13828. var ParticleSystem = (function () {
  13829. function ParticleSystem(name, capacity, scene, customEffect) {
  13830. var _this = this;
  13831. this.name = name;
  13832. this.renderingGroupId = 0;
  13833. this.emitter = null;
  13834. this.emitRate = 10;
  13835. this.manualEmitCount = -1;
  13836. this.updateSpeed = 0.01;
  13837. this.targetStopDuration = 0;
  13838. this.disposeOnStop = false;
  13839. this.minEmitPower = 1;
  13840. this.maxEmitPower = 1;
  13841. this.minLifeTime = 1;
  13842. this.maxLifeTime = 1;
  13843. this.minSize = 1;
  13844. this.maxSize = 1;
  13845. this.minAngularSpeed = 0;
  13846. this.maxAngularSpeed = 0;
  13847. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  13848. this.forceDepthWrite = false;
  13849. this.gravity = BABYLON.Vector3.Zero();
  13850. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  13851. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  13852. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  13853. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  13854. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  13855. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  13856. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  13857. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  13858. this.particles = new Array();
  13859. this._vertexDeclaration = [3, 4, 4];
  13860. this._vertexStrideSize = 11 * 4;
  13861. this._stockParticles = new Array();
  13862. this._newPartsExcess = 0;
  13863. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  13864. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  13865. this._scaledDirection = BABYLON.Vector3.Zero();
  13866. this._scaledGravity = BABYLON.Vector3.Zero();
  13867. this._currentRenderId = -1;
  13868. this._started = false;
  13869. this._stopped = false;
  13870. this._actualFrame = 0;
  13871. this.id = name;
  13872. this._capacity = capacity;
  13873. this._scene = scene;
  13874. this._customEffect = customEffect;
  13875. scene.particleSystems.push(this);
  13876. // VBO
  13877. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  13878. var indices = [];
  13879. var index = 0;
  13880. for (var count = 0; count < capacity; count++) {
  13881. indices.push(index);
  13882. indices.push(index + 1);
  13883. indices.push(index + 2);
  13884. indices.push(index);
  13885. indices.push(index + 2);
  13886. indices.push(index + 3);
  13887. index += 4;
  13888. }
  13889. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  13890. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  13891. // Default behaviors
  13892. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate) {
  13893. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  13894. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  13895. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  13896. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  13897. };
  13898. this.startPositionFunction = function (worldMatrix, positionToUpdate) {
  13899. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  13900. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  13901. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  13902. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  13903. };
  13904. this.updateFunction = function (particles) {
  13905. for (var index = 0; index < particles.length; index++) {
  13906. var particle = particles[index];
  13907. particle.age += _this._scaledUpdateSpeed;
  13908. if (particle.age >= particle.lifeTime) {
  13909. particles.splice(index, 1);
  13910. _this._stockParticles.push(particle);
  13911. index--;
  13912. continue;
  13913. } else {
  13914. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  13915. particle.color.addInPlace(_this._scaledColorStep);
  13916. if (particle.color.a < 0)
  13917. particle.color.a = 0;
  13918. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  13919. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  13920. particle.position.addInPlace(_this._scaledDirection);
  13921. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  13922. particle.direction.addInPlace(_this._scaledGravity);
  13923. }
  13924. }
  13925. };
  13926. }
  13927. ParticleSystem.prototype.getCapacity = function () {
  13928. return this._capacity;
  13929. };
  13930. ParticleSystem.prototype.isAlive = function () {
  13931. return this._alive;
  13932. };
  13933. ParticleSystem.prototype.isStarted = function () {
  13934. return this._started;
  13935. };
  13936. ParticleSystem.prototype.start = function () {
  13937. this._started = true;
  13938. this._stopped = false;
  13939. this._actualFrame = 0;
  13940. };
  13941. ParticleSystem.prototype.stop = function () {
  13942. this._stopped = true;
  13943. };
  13944. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  13945. var offset = index * 11;
  13946. this._vertices[offset] = particle.position.x;
  13947. this._vertices[offset + 1] = particle.position.y;
  13948. this._vertices[offset + 2] = particle.position.z;
  13949. this._vertices[offset + 3] = particle.color.r;
  13950. this._vertices[offset + 4] = particle.color.g;
  13951. this._vertices[offset + 5] = particle.color.b;
  13952. this._vertices[offset + 6] = particle.color.a;
  13953. this._vertices[offset + 7] = particle.angle;
  13954. this._vertices[offset + 8] = particle.size;
  13955. this._vertices[offset + 9] = offsetX;
  13956. this._vertices[offset + 10] = offsetY;
  13957. };
  13958. ParticleSystem.prototype._update = function (newParticles) {
  13959. // Update current
  13960. this._alive = this.particles.length > 0;
  13961. this.updateFunction(this.particles);
  13962. // Add new ones
  13963. var worldMatrix;
  13964. if (this.emitter.position) {
  13965. worldMatrix = this.emitter.getWorldMatrix();
  13966. } else {
  13967. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  13968. }
  13969. for (var index = 0; index < newParticles; index++) {
  13970. if (this.particles.length === this._capacity) {
  13971. break;
  13972. }
  13973. if (this._stockParticles.length !== 0) {
  13974. var particle = this._stockParticles.pop();
  13975. particle.age = 0;
  13976. } else {
  13977. particle = new BABYLON.Particle();
  13978. }
  13979. this.particles.push(particle);
  13980. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  13981. this.startDirectionFunction(emitPower, worldMatrix, particle.direction);
  13982. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  13983. particle.size = randomNumber(this.minSize, this.maxSize);
  13984. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  13985. this.startPositionFunction(worldMatrix, particle.position);
  13986. var step = randomNumber(0, 1.0);
  13987. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  13988. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  13989. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  13990. }
  13991. };
  13992. ParticleSystem.prototype._getEffect = function () {
  13993. if (this._customEffect) {
  13994. return this._customEffect;
  13995. }
  13996. ;
  13997. var defines = [];
  13998. if (this._scene.clipPlane) {
  13999. defines.push("#define CLIPPLANE");
  14000. }
  14001. // Effect
  14002. var join = defines.join("\n");
  14003. if (this._cachedDefines !== join) {
  14004. this._cachedDefines = join;
  14005. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  14006. }
  14007. return this._effect;
  14008. };
  14009. ParticleSystem.prototype.animate = function () {
  14010. if (!this._started)
  14011. return;
  14012. var effect = this._getEffect();
  14013. // Check
  14014. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  14015. return;
  14016. if (this._currentRenderId === this._scene.getRenderId()) {
  14017. return;
  14018. }
  14019. this._currentRenderId = this._scene.getRenderId();
  14020. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  14021. // determine the number of particles we need to create
  14022. var emitCout;
  14023. if (this.manualEmitCount > -1) {
  14024. emitCout = this.manualEmitCount;
  14025. this.manualEmitCount = 0;
  14026. } else {
  14027. emitCout = this.emitRate;
  14028. }
  14029. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  14030. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  14031. if (this._newPartsExcess > 1.0) {
  14032. newParticles += this._newPartsExcess >> 0;
  14033. this._newPartsExcess -= this._newPartsExcess >> 0;
  14034. }
  14035. this._alive = false;
  14036. if (!this._stopped) {
  14037. this._actualFrame += this._scaledUpdateSpeed;
  14038. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  14039. this.stop();
  14040. } else {
  14041. newParticles = 0;
  14042. }
  14043. this._update(newParticles);
  14044. // Stopped?
  14045. if (this._stopped) {
  14046. if (!this._alive) {
  14047. this._started = false;
  14048. if (this.disposeOnStop) {
  14049. this._scene._toBeDisposed.push(this);
  14050. }
  14051. }
  14052. }
  14053. // Update VBO
  14054. var offset = 0;
  14055. for (var index = 0; index < this.particles.length; index++) {
  14056. var particle = this.particles[index];
  14057. this._appendParticleVertex(offset++, particle, 0, 0);
  14058. this._appendParticleVertex(offset++, particle, 1, 0);
  14059. this._appendParticleVertex(offset++, particle, 1, 1);
  14060. this._appendParticleVertex(offset++, particle, 0, 1);
  14061. }
  14062. var engine = this._scene.getEngine();
  14063. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  14064. };
  14065. ParticleSystem.prototype.render = function () {
  14066. var effect = this._getEffect();
  14067. // Check
  14068. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  14069. return 0;
  14070. var engine = this._scene.getEngine();
  14071. // Render
  14072. engine.enableEffect(effect);
  14073. engine.setState(false);
  14074. var viewMatrix = this._scene.getViewMatrix();
  14075. effect.setTexture("diffuseSampler", this.particleTexture);
  14076. effect.setMatrix("view", viewMatrix);
  14077. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  14078. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  14079. if (this._scene.clipPlane) {
  14080. var clipPlane = this._scene.clipPlane;
  14081. var invView = viewMatrix.clone();
  14082. invView.invert();
  14083. effect.setMatrix("invView", invView);
  14084. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  14085. }
  14086. // VBOs
  14087. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  14088. // Draw order
  14089. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  14090. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  14091. } else {
  14092. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  14093. }
  14094. if (this.forceDepthWrite) {
  14095. engine.setDepthWrite(true);
  14096. }
  14097. engine.draw(true, 0, this.particles.length * 6);
  14098. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  14099. return this.particles.length;
  14100. };
  14101. ParticleSystem.prototype.dispose = function () {
  14102. if (this._vertexBuffer) {
  14103. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  14104. this._vertexBuffer = null;
  14105. }
  14106. if (this._indexBuffer) {
  14107. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  14108. this._indexBuffer = null;
  14109. }
  14110. if (this.particleTexture) {
  14111. this.particleTexture.dispose();
  14112. this.particleTexture = null;
  14113. }
  14114. // Remove from scene
  14115. var index = this._scene.particleSystems.indexOf(this);
  14116. this._scene.particleSystems.splice(index, 1);
  14117. // Callback
  14118. if (this.onDispose) {
  14119. this.onDispose();
  14120. }
  14121. };
  14122. // Clone
  14123. ParticleSystem.prototype.clone = function (name, newEmitter) {
  14124. var result = new ParticleSystem(name, this._capacity, this._scene);
  14125. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  14126. if (newEmitter === undefined) {
  14127. newEmitter = this.emitter;
  14128. }
  14129. result.emitter = newEmitter;
  14130. if (this.particleTexture) {
  14131. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  14132. }
  14133. result.start();
  14134. return result;
  14135. };
  14136. ParticleSystem.BLENDMODE_ONEONE = 0;
  14137. ParticleSystem.BLENDMODE_STANDARD = 1;
  14138. return ParticleSystem;
  14139. })();
  14140. BABYLON.ParticleSystem = ParticleSystem;
  14141. })(BABYLON || (BABYLON = {}));
  14142. //# sourceMappingURL=babylon.particleSystem.js.map
  14143. var BABYLON;
  14144. (function (BABYLON) {
  14145. var Animation = (function () {
  14146. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  14147. this.name = name;
  14148. this.targetProperty = targetProperty;
  14149. this.framePerSecond = framePerSecond;
  14150. this.dataType = dataType;
  14151. this.loopMode = loopMode;
  14152. this._offsetsCache = {};
  14153. this._highLimitsCache = {};
  14154. this._stopped = false;
  14155. this.targetPropertyPath = targetProperty.split(".");
  14156. this.dataType = dataType;
  14157. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  14158. }
  14159. Animation.CreateAndStartAnimation = function (name, mesh, tartgetProperty, framePerSecond, totalFrame, from, to, loopMode) {
  14160. var dataType = undefined;
  14161. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  14162. dataType = Animation.ANIMATIONTYPE_FLOAT;
  14163. } else if (from instanceof BABYLON.Quaternion) {
  14164. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  14165. } else if (from instanceof BABYLON.Vector3) {
  14166. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  14167. } else if (from instanceof BABYLON.Vector2) {
  14168. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  14169. } else if (from instanceof BABYLON.Color3) {
  14170. dataType = Animation.ANIMATIONTYPE_COLOR3;
  14171. }
  14172. if (dataType == undefined) {
  14173. return;
  14174. }
  14175. var animation = new Animation(name, tartgetProperty, framePerSecond, dataType, loopMode);
  14176. var keys = [];
  14177. keys.push({ frame: 0, value: from });
  14178. keys.push({ frame: totalFrame, value: to });
  14179. animation.setKeys(keys);
  14180. mesh.animations.push(animation);
  14181. mesh.getScene().beginAnimation(mesh, 0, totalFrame, (animation.loopMode == 1));
  14182. };
  14183. // Methods
  14184. Animation.prototype.isStopped = function () {
  14185. return this._stopped;
  14186. };
  14187. Animation.prototype.getKeys = function () {
  14188. return this._keys;
  14189. };
  14190. Animation.prototype.getEasingFunction = function () {
  14191. return this._easingFunction;
  14192. };
  14193. Animation.prototype.setEasingFunction = function (easingFunction) {
  14194. this._easingFunction = easingFunction;
  14195. };
  14196. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  14197. return startValue + (endValue - startValue) * gradient;
  14198. };
  14199. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  14200. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  14201. };
  14202. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  14203. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  14204. };
  14205. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  14206. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  14207. };
  14208. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  14209. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  14210. };
  14211. Animation.prototype.clone = function () {
  14212. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  14213. clone.setKeys(this._keys);
  14214. return clone;
  14215. };
  14216. Animation.prototype.setKeys = function (values) {
  14217. this._keys = values.slice(0);
  14218. this._offsetsCache = {};
  14219. this._highLimitsCache = {};
  14220. };
  14221. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  14222. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  14223. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  14224. }
  14225. this.currentFrame = currentFrame;
  14226. for (var key = 0; key < this._keys.length; key++) {
  14227. // for each frame, we need the key just before the frame superior
  14228. if (this._keys[key + 1].frame >= currentFrame) {
  14229. var startValue = this._keys[key].value;
  14230. var endValue = this._keys[key + 1].value;
  14231. // gradient : percent of currentFrame between the frame inf and the frame sup
  14232. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  14233. // check for easingFunction and correction of gradient
  14234. if (this._easingFunction != null) {
  14235. gradient = this._easingFunction.ease(gradient);
  14236. }
  14237. switch (this.dataType) {
  14238. case Animation.ANIMATIONTYPE_FLOAT:
  14239. switch (loopMode) {
  14240. case Animation.ANIMATIONLOOPMODE_CYCLE:
  14241. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  14242. return this.floatInterpolateFunction(startValue, endValue, gradient);
  14243. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  14244. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  14245. }
  14246. break;
  14247. case Animation.ANIMATIONTYPE_QUATERNION:
  14248. var quaternion = null;
  14249. switch (loopMode) {
  14250. case Animation.ANIMATIONLOOPMODE_CYCLE:
  14251. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  14252. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  14253. break;
  14254. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  14255. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  14256. break;
  14257. }
  14258. return quaternion;
  14259. case Animation.ANIMATIONTYPE_VECTOR3:
  14260. switch (loopMode) {
  14261. case Animation.ANIMATIONLOOPMODE_CYCLE:
  14262. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  14263. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  14264. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  14265. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  14266. }
  14267. case Animation.ANIMATIONTYPE_VECTOR2:
  14268. switch (loopMode) {
  14269. case Animation.ANIMATIONLOOPMODE_CYCLE:
  14270. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  14271. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  14272. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  14273. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  14274. }
  14275. case Animation.ANIMATIONTYPE_COLOR3:
  14276. switch (loopMode) {
  14277. case Animation.ANIMATIONLOOPMODE_CYCLE:
  14278. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  14279. return this.color3InterpolateFunction(startValue, endValue, gradient);
  14280. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  14281. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  14282. }
  14283. case Animation.ANIMATIONTYPE_MATRIX:
  14284. switch (loopMode) {
  14285. case Animation.ANIMATIONLOOPMODE_CYCLE:
  14286. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  14287. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  14288. return startValue;
  14289. }
  14290. default:
  14291. break;
  14292. }
  14293. break;
  14294. }
  14295. }
  14296. return this._keys[this._keys.length - 1].value;
  14297. };
  14298. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  14299. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  14300. this._stopped = true;
  14301. return false;
  14302. }
  14303. var returnValue = true;
  14304. // Adding a start key at frame 0 if missing
  14305. if (this._keys[0].frame != 0) {
  14306. var newKey = { frame: 0, value: this._keys[0].value };
  14307. this._keys.splice(0, 0, newKey);
  14308. }
  14309. // Check limits
  14310. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  14311. from = this._keys[0].frame;
  14312. }
  14313. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  14314. to = this._keys[this._keys.length - 1].frame;
  14315. }
  14316. // Compute ratio
  14317. var range = to - from;
  14318. var offsetValue;
  14319. // ratio represents the frame delta between from and to
  14320. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  14321. if (ratio > range && !loop) {
  14322. returnValue = false;
  14323. highLimitValue = this._keys[this._keys.length - 1].value;
  14324. } else {
  14325. // Get max value if required
  14326. var highLimitValue = 0;
  14327. if (this.loopMode != Animation.ANIMATIONLOOPMODE_CYCLE) {
  14328. var keyOffset = to.toString() + from.toString();
  14329. if (!this._offsetsCache[keyOffset]) {
  14330. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  14331. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  14332. switch (this.dataType) {
  14333. case Animation.ANIMATIONTYPE_FLOAT:
  14334. this._offsetsCache[keyOffset] = toValue - fromValue;
  14335. break;
  14336. case Animation.ANIMATIONTYPE_QUATERNION:
  14337. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  14338. break;
  14339. case Animation.ANIMATIONTYPE_VECTOR3:
  14340. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  14341. case Animation.ANIMATIONTYPE_VECTOR2:
  14342. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  14343. case Animation.ANIMATIONTYPE_COLOR3:
  14344. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  14345. default:
  14346. break;
  14347. }
  14348. this._highLimitsCache[keyOffset] = toValue;
  14349. }
  14350. highLimitValue = this._highLimitsCache[keyOffset];
  14351. offsetValue = this._offsetsCache[keyOffset];
  14352. }
  14353. }
  14354. if (offsetValue === undefined) {
  14355. switch (this.dataType) {
  14356. case Animation.ANIMATIONTYPE_FLOAT:
  14357. offsetValue = 0;
  14358. break;
  14359. case Animation.ANIMATIONTYPE_QUATERNION:
  14360. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  14361. break;
  14362. case Animation.ANIMATIONTYPE_VECTOR3:
  14363. offsetValue = BABYLON.Vector3.Zero();
  14364. break;
  14365. case Animation.ANIMATIONTYPE_VECTOR2:
  14366. offsetValue = BABYLON.Vector2.Zero();
  14367. break;
  14368. case Animation.ANIMATIONTYPE_COLOR3:
  14369. offsetValue = BABYLON.Color3.Black();
  14370. }
  14371. }
  14372. // Compute value
  14373. var repeatCount = (ratio / range) >> 0;
  14374. var currentFrame = returnValue ? from + ratio % range : to;
  14375. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  14376. // Set value
  14377. if (this.targetPropertyPath.length > 1) {
  14378. var property = this._target[this.targetPropertyPath[0]];
  14379. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  14380. property = property[this.targetPropertyPath[index]];
  14381. }
  14382. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  14383. } else {
  14384. this._target[this.targetPropertyPath[0]] = currentValue;
  14385. }
  14386. if (this._target.markAsDirty) {
  14387. this._target.markAsDirty(this.targetProperty);
  14388. }
  14389. if (!returnValue) {
  14390. this._stopped = true;
  14391. }
  14392. return returnValue;
  14393. };
  14394. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  14395. get: function () {
  14396. return Animation._ANIMATIONTYPE_FLOAT;
  14397. },
  14398. enumerable: true,
  14399. configurable: true
  14400. });
  14401. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  14402. get: function () {
  14403. return Animation._ANIMATIONTYPE_VECTOR3;
  14404. },
  14405. enumerable: true,
  14406. configurable: true
  14407. });
  14408. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  14409. get: function () {
  14410. return Animation._ANIMATIONTYPE_VECTOR2;
  14411. },
  14412. enumerable: true,
  14413. configurable: true
  14414. });
  14415. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  14416. get: function () {
  14417. return Animation._ANIMATIONTYPE_QUATERNION;
  14418. },
  14419. enumerable: true,
  14420. configurable: true
  14421. });
  14422. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  14423. get: function () {
  14424. return Animation._ANIMATIONTYPE_MATRIX;
  14425. },
  14426. enumerable: true,
  14427. configurable: true
  14428. });
  14429. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  14430. get: function () {
  14431. return Animation._ANIMATIONTYPE_COLOR3;
  14432. },
  14433. enumerable: true,
  14434. configurable: true
  14435. });
  14436. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  14437. get: function () {
  14438. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  14439. },
  14440. enumerable: true,
  14441. configurable: true
  14442. });
  14443. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  14444. get: function () {
  14445. return Animation._ANIMATIONLOOPMODE_CYCLE;
  14446. },
  14447. enumerable: true,
  14448. configurable: true
  14449. });
  14450. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  14451. get: function () {
  14452. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  14453. },
  14454. enumerable: true,
  14455. configurable: true
  14456. });
  14457. Animation._ANIMATIONTYPE_FLOAT = 0;
  14458. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  14459. Animation._ANIMATIONTYPE_QUATERNION = 2;
  14460. Animation._ANIMATIONTYPE_MATRIX = 3;
  14461. Animation._ANIMATIONTYPE_COLOR3 = 4;
  14462. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  14463. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  14464. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  14465. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  14466. return Animation;
  14467. })();
  14468. BABYLON.Animation = Animation;
  14469. })(BABYLON || (BABYLON = {}));
  14470. //# sourceMappingURL=babylon.animation.js.map
  14471. var BABYLON;
  14472. (function (BABYLON) {
  14473. var Animatable = (function () {
  14474. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  14475. if (typeof fromFrame === "undefined") { fromFrame = 0; }
  14476. if (typeof toFrame === "undefined") { toFrame = 100; }
  14477. if (typeof loopAnimation === "undefined") { loopAnimation = false; }
  14478. if (typeof speedRatio === "undefined") { speedRatio = 1.0; }
  14479. this.target = target;
  14480. this.fromFrame = fromFrame;
  14481. this.toFrame = toFrame;
  14482. this.loopAnimation = loopAnimation;
  14483. this.speedRatio = speedRatio;
  14484. this.onAnimationEnd = onAnimationEnd;
  14485. this._animations = new Array();
  14486. this._paused = false;
  14487. this.animationStarted = false;
  14488. if (animations) {
  14489. this.appendAnimations(target, animations);
  14490. }
  14491. this._scene = scene;
  14492. scene._activeAnimatables.push(this);
  14493. }
  14494. // Methods
  14495. Animatable.prototype.appendAnimations = function (target, animations) {
  14496. for (var index = 0; index < animations.length; index++) {
  14497. var animation = animations[index];
  14498. animation._target = target;
  14499. this._animations.push(animation);
  14500. }
  14501. };
  14502. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  14503. var animations = this._animations;
  14504. for (var index = 0; index < animations.length; index++) {
  14505. if (animations[index].targetProperty === property) {
  14506. return animations[index];
  14507. }
  14508. }
  14509. return null;
  14510. };
  14511. Animatable.prototype.pause = function () {
  14512. if (this._paused) {
  14513. return;
  14514. }
  14515. this._paused = true;
  14516. };
  14517. Animatable.prototype.restart = function () {
  14518. this._paused = false;
  14519. };
  14520. Animatable.prototype.stop = function () {
  14521. var index = this._scene._activeAnimatables.indexOf(this);
  14522. if (index > -1) {
  14523. this._scene._activeAnimatables.splice(index, 1);
  14524. }
  14525. if (this.onAnimationEnd) {
  14526. this.onAnimationEnd();
  14527. }
  14528. };
  14529. Animatable.prototype._animate = function (delay) {
  14530. if (this._paused) {
  14531. if (!this._pausedDelay) {
  14532. this._pausedDelay = delay;
  14533. }
  14534. return true;
  14535. }
  14536. if (!this._localDelayOffset) {
  14537. this._localDelayOffset = delay;
  14538. } else if (this._pausedDelay) {
  14539. this._localDelayOffset += delay - this._pausedDelay;
  14540. this._pausedDelay = null;
  14541. }
  14542. // Animating
  14543. var running = false;
  14544. var animations = this._animations;
  14545. for (var index = 0; index < animations.length; index++) {
  14546. var animation = animations[index];
  14547. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  14548. running = running || isRunning;
  14549. }
  14550. if (!running && this.onAnimationEnd) {
  14551. this.onAnimationEnd();
  14552. }
  14553. return running;
  14554. };
  14555. return Animatable;
  14556. })();
  14557. BABYLON.Animatable = Animatable;
  14558. })(BABYLON || (BABYLON = {}));
  14559. //# sourceMappingURL=babylon.animatable.js.map
  14560. var BABYLON;
  14561. (function (BABYLON) {
  14562. var EasingFunction = (function () {
  14563. function EasingFunction() {
  14564. // Properties
  14565. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  14566. }
  14567. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  14568. get: function () {
  14569. return EasingFunction._EASINGMODE_EASEIN;
  14570. },
  14571. enumerable: true,
  14572. configurable: true
  14573. });
  14574. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  14575. get: function () {
  14576. return EasingFunction._EASINGMODE_EASEOUT;
  14577. },
  14578. enumerable: true,
  14579. configurable: true
  14580. });
  14581. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  14582. get: function () {
  14583. return EasingFunction._EASINGMODE_EASEINOUT;
  14584. },
  14585. enumerable: true,
  14586. configurable: true
  14587. });
  14588. EasingFunction.prototype.setEasingMode = function (easingMode) {
  14589. var n = Math.min(Math.max(easingMode, 0), 2);
  14590. this._easingMode = n;
  14591. };
  14592. EasingFunction.prototype.getEasingMode = function () {
  14593. return this._easingMode;
  14594. };
  14595. EasingFunction.prototype.easeInCore = function (gradient) {
  14596. throw new Error('You must implement this method');
  14597. };
  14598. EasingFunction.prototype.ease = function (gradient) {
  14599. switch (this._easingMode) {
  14600. case EasingFunction.EASINGMODE_EASEIN:
  14601. return this.easeInCore(gradient);
  14602. case EasingFunction.EASINGMODE_EASEOUT:
  14603. return (1 - this.easeInCore(1 - gradient));
  14604. }
  14605. if (gradient >= 0.5) {
  14606. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  14607. }
  14608. return (this.easeInCore(gradient * 2) * 0.5);
  14609. };
  14610. EasingFunction._EASINGMODE_EASEIN = 0;
  14611. EasingFunction._EASINGMODE_EASEOUT = 1;
  14612. EasingFunction._EASINGMODE_EASEINOUT = 2;
  14613. return EasingFunction;
  14614. })();
  14615. BABYLON.EasingFunction = EasingFunction;
  14616. var CircleEase = (function (_super) {
  14617. __extends(CircleEase, _super);
  14618. function CircleEase() {
  14619. _super.apply(this, arguments);
  14620. }
  14621. CircleEase.prototype.easeInCore = function (gradient) {
  14622. gradient = Math.max(0, Math.min(1, gradient));
  14623. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  14624. };
  14625. return CircleEase;
  14626. })(EasingFunction);
  14627. BABYLON.CircleEase = CircleEase;
  14628. var BackEase = (function (_super) {
  14629. __extends(BackEase, _super);
  14630. function BackEase(amplitude) {
  14631. if (typeof amplitude === "undefined") { amplitude = 1; }
  14632. _super.call(this);
  14633. this.amplitude = amplitude;
  14634. }
  14635. BackEase.prototype.easeInCore = function (gradient) {
  14636. var num = Math.max(0, this.amplitude);
  14637. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  14638. };
  14639. return BackEase;
  14640. })(EasingFunction);
  14641. BABYLON.BackEase = BackEase;
  14642. var BounceEase = (function (_super) {
  14643. __extends(BounceEase, _super);
  14644. function BounceEase(bounces, bounciness) {
  14645. if (typeof bounces === "undefined") { bounces = 3; }
  14646. if (typeof bounciness === "undefined") { bounciness = 2; }
  14647. _super.call(this);
  14648. this.bounces = bounces;
  14649. this.bounciness = bounciness;
  14650. }
  14651. BounceEase.prototype.easeInCore = function (gradient) {
  14652. var y = Math.max(0.0, this.bounces);
  14653. var bounciness = this.bounciness;
  14654. if (bounciness <= 1.0) {
  14655. bounciness = 1.001;
  14656. }
  14657. var num9 = Math.pow(bounciness, y);
  14658. var num5 = 1.0 - bounciness;
  14659. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  14660. var num15 = gradient * num4;
  14661. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  14662. var num3 = Math.floor(num65);
  14663. var num13 = num3 + 1.0;
  14664. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  14665. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  14666. var num7 = (num8 + num12) * 0.5;
  14667. var num6 = gradient - num7;
  14668. var num2 = num7 - num8;
  14669. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  14670. };
  14671. return BounceEase;
  14672. })(EasingFunction);
  14673. BABYLON.BounceEase = BounceEase;
  14674. var CubicEase = (function (_super) {
  14675. __extends(CubicEase, _super);
  14676. function CubicEase() {
  14677. _super.apply(this, arguments);
  14678. }
  14679. CubicEase.prototype.easeInCore = function (gradient) {
  14680. return (gradient * gradient * gradient);
  14681. };
  14682. return CubicEase;
  14683. })(EasingFunction);
  14684. BABYLON.CubicEase = CubicEase;
  14685. var ElasticEase = (function (_super) {
  14686. __extends(ElasticEase, _super);
  14687. function ElasticEase(oscillations, springiness) {
  14688. if (typeof oscillations === "undefined") { oscillations = 3; }
  14689. if (typeof springiness === "undefined") { springiness = 3; }
  14690. _super.call(this);
  14691. this.oscillations = oscillations;
  14692. this.springiness = springiness;
  14693. }
  14694. ElasticEase.prototype.easeInCore = function (gradient) {
  14695. var num2;
  14696. var num3 = Math.max(0.0, this.oscillations);
  14697. var num = Math.max(0.0, this.springiness);
  14698. if (num == 0) {
  14699. num2 = gradient;
  14700. } else {
  14701. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  14702. }
  14703. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  14704. };
  14705. return ElasticEase;
  14706. })(EasingFunction);
  14707. BABYLON.ElasticEase = ElasticEase;
  14708. var ExponentialEase = (function (_super) {
  14709. __extends(ExponentialEase, _super);
  14710. function ExponentialEase(exponent) {
  14711. if (typeof exponent === "undefined") { exponent = 2; }
  14712. _super.call(this);
  14713. this.exponent = exponent;
  14714. }
  14715. ExponentialEase.prototype.easeInCore = function (gradient) {
  14716. if (this.exponent <= 0) {
  14717. return gradient;
  14718. }
  14719. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  14720. };
  14721. return ExponentialEase;
  14722. })(EasingFunction);
  14723. BABYLON.ExponentialEase = ExponentialEase;
  14724. var PowerEase = (function (_super) {
  14725. __extends(PowerEase, _super);
  14726. function PowerEase(power) {
  14727. if (typeof power === "undefined") { power = 2; }
  14728. _super.call(this);
  14729. this.power = power;
  14730. }
  14731. PowerEase.prototype.easeInCore = function (gradient) {
  14732. var y = Math.max(0.0, this.power);
  14733. return Math.pow(gradient, y);
  14734. };
  14735. return PowerEase;
  14736. })(EasingFunction);
  14737. BABYLON.PowerEase = PowerEase;
  14738. var QuadraticEase = (function (_super) {
  14739. __extends(QuadraticEase, _super);
  14740. function QuadraticEase() {
  14741. _super.apply(this, arguments);
  14742. }
  14743. QuadraticEase.prototype.easeInCore = function (gradient) {
  14744. return (gradient * gradient);
  14745. };
  14746. return QuadraticEase;
  14747. })(EasingFunction);
  14748. BABYLON.QuadraticEase = QuadraticEase;
  14749. var QuarticEase = (function (_super) {
  14750. __extends(QuarticEase, _super);
  14751. function QuarticEase() {
  14752. _super.apply(this, arguments);
  14753. }
  14754. QuarticEase.prototype.easeInCore = function (gradient) {
  14755. return (gradient * gradient * gradient * gradient);
  14756. };
  14757. return QuarticEase;
  14758. })(EasingFunction);
  14759. BABYLON.QuarticEase = QuarticEase;
  14760. var QuinticEase = (function (_super) {
  14761. __extends(QuinticEase, _super);
  14762. function QuinticEase() {
  14763. _super.apply(this, arguments);
  14764. }
  14765. QuinticEase.prototype.easeInCore = function (gradient) {
  14766. return (gradient * gradient * gradient * gradient * gradient);
  14767. };
  14768. return QuinticEase;
  14769. })(EasingFunction);
  14770. BABYLON.QuinticEase = QuinticEase;
  14771. var SineEase = (function (_super) {
  14772. __extends(SineEase, _super);
  14773. function SineEase() {
  14774. _super.apply(this, arguments);
  14775. }
  14776. SineEase.prototype.easeInCore = function (gradient) {
  14777. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  14778. };
  14779. return SineEase;
  14780. })(EasingFunction);
  14781. BABYLON.SineEase = SineEase;
  14782. var BezierCurveEase = (function (_super) {
  14783. __extends(BezierCurveEase, _super);
  14784. function BezierCurveEase(x1, y1, x2, y2) {
  14785. if (typeof x1 === "undefined") { x1 = 0; }
  14786. if (typeof y1 === "undefined") { y1 = 0; }
  14787. if (typeof x2 === "undefined") { x2 = 1; }
  14788. if (typeof y2 === "undefined") { y2 = 1; }
  14789. _super.call(this);
  14790. this.x1 = x1;
  14791. this.y1 = y1;
  14792. this.x2 = x2;
  14793. this.y2 = y2;
  14794. }
  14795. BezierCurveEase.prototype.easeInCore = function (gradient) {
  14796. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  14797. };
  14798. return BezierCurveEase;
  14799. })(EasingFunction);
  14800. BABYLON.BezierCurveEase = BezierCurveEase;
  14801. })(BABYLON || (BABYLON = {}));
  14802. //# sourceMappingURL=babylon.easing.js.map
  14803. var BABYLON;
  14804. (function (BABYLON) {
  14805. var Octree = (function () {
  14806. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  14807. if (typeof maxDepth === "undefined") { maxDepth = 2; }
  14808. this.maxDepth = maxDepth;
  14809. this.dynamicContent = new Array();
  14810. this._maxBlockCapacity = maxBlockCapacity || 64;
  14811. this._selectionContent = new BABYLON.SmartArray(1024);
  14812. this._creationFunc = creationFunc;
  14813. }
  14814. // Methods
  14815. Octree.prototype.update = function (worldMin, worldMax, entries) {
  14816. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  14817. };
  14818. Octree.prototype.addMesh = function (entry) {
  14819. for (var index = 0; index < this.blocks.length; index++) {
  14820. var block = this.blocks[index];
  14821. block.addEntry(entry);
  14822. }
  14823. };
  14824. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  14825. this._selectionContent.reset();
  14826. for (var index = 0; index < this.blocks.length; index++) {
  14827. var block = this.blocks[index];
  14828. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  14829. }
  14830. if (allowDuplicate) {
  14831. this._selectionContent.concat(this.dynamicContent);
  14832. } else {
  14833. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  14834. }
  14835. return this._selectionContent;
  14836. };
  14837. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  14838. this._selectionContent.reset();
  14839. for (var index = 0; index < this.blocks.length; index++) {
  14840. var block = this.blocks[index];
  14841. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  14842. }
  14843. if (allowDuplicate) {
  14844. this._selectionContent.concat(this.dynamicContent);
  14845. } else {
  14846. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  14847. }
  14848. return this._selectionContent;
  14849. };
  14850. Octree.prototype.intersectsRay = function (ray) {
  14851. this._selectionContent.reset();
  14852. for (var index = 0; index < this.blocks.length; index++) {
  14853. var block = this.blocks[index];
  14854. block.intersectsRay(ray, this._selectionContent);
  14855. }
  14856. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  14857. return this._selectionContent;
  14858. };
  14859. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  14860. target.blocks = new Array();
  14861. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  14862. for (var x = 0; x < 2; x++) {
  14863. for (var y = 0; y < 2; y++) {
  14864. for (var z = 0; z < 2; z++) {
  14865. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  14866. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  14867. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  14868. block.addEntries(entries);
  14869. target.blocks.push(block);
  14870. }
  14871. }
  14872. }
  14873. };
  14874. Octree.CreationFuncForMeshes = function (entry, block) {
  14875. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  14876. block.entries.push(entry);
  14877. }
  14878. };
  14879. Octree.CreationFuncForSubMeshes = function (entry, block) {
  14880. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  14881. block.entries.push(entry);
  14882. }
  14883. };
  14884. return Octree;
  14885. })();
  14886. BABYLON.Octree = Octree;
  14887. })(BABYLON || (BABYLON = {}));
  14888. //# sourceMappingURL=babylon.octree.js.map
  14889. var BABYLON;
  14890. (function (BABYLON) {
  14891. var OctreeBlock = (function () {
  14892. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  14893. this.entries = new Array();
  14894. this._boundingVectors = new Array();
  14895. this._capacity = capacity;
  14896. this._depth = depth;
  14897. this._maxDepth = maxDepth;
  14898. this._creationFunc = creationFunc;
  14899. this._minPoint = minPoint;
  14900. this._maxPoint = maxPoint;
  14901. this._boundingVectors.push(minPoint.clone());
  14902. this._boundingVectors.push(maxPoint.clone());
  14903. this._boundingVectors.push(minPoint.clone());
  14904. this._boundingVectors[2].x = maxPoint.x;
  14905. this._boundingVectors.push(minPoint.clone());
  14906. this._boundingVectors[3].y = maxPoint.y;
  14907. this._boundingVectors.push(minPoint.clone());
  14908. this._boundingVectors[4].z = maxPoint.z;
  14909. this._boundingVectors.push(maxPoint.clone());
  14910. this._boundingVectors[5].z = minPoint.z;
  14911. this._boundingVectors.push(maxPoint.clone());
  14912. this._boundingVectors[6].x = minPoint.x;
  14913. this._boundingVectors.push(maxPoint.clone());
  14914. this._boundingVectors[7].y = minPoint.y;
  14915. }
  14916. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  14917. // Property
  14918. get: function () {
  14919. return this._capacity;
  14920. },
  14921. enumerable: true,
  14922. configurable: true
  14923. });
  14924. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  14925. get: function () {
  14926. return this._minPoint;
  14927. },
  14928. enumerable: true,
  14929. configurable: true
  14930. });
  14931. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  14932. get: function () {
  14933. return this._maxPoint;
  14934. },
  14935. enumerable: true,
  14936. configurable: true
  14937. });
  14938. // Methods
  14939. OctreeBlock.prototype.addEntry = function (entry) {
  14940. if (this.blocks) {
  14941. for (var index = 0; index < this.blocks.length; index++) {
  14942. var block = this.blocks[index];
  14943. block.addEntry(entry);
  14944. }
  14945. return;
  14946. }
  14947. this._creationFunc(entry, this);
  14948. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  14949. this.createInnerBlocks();
  14950. }
  14951. };
  14952. OctreeBlock.prototype.addEntries = function (entries) {
  14953. for (var index = 0; index < entries.length; index++) {
  14954. var mesh = entries[index];
  14955. this.addEntry(mesh);
  14956. }
  14957. };
  14958. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  14959. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  14960. if (this.blocks) {
  14961. for (var index = 0; index < this.blocks.length; index++) {
  14962. var block = this.blocks[index];
  14963. block.select(frustumPlanes, selection, allowDuplicate);
  14964. }
  14965. return;
  14966. }
  14967. if (allowDuplicate) {
  14968. selection.concat(this.entries);
  14969. } else {
  14970. selection.concatWithNoDuplicate(this.entries);
  14971. }
  14972. }
  14973. };
  14974. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  14975. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  14976. if (this.blocks) {
  14977. for (var index = 0; index < this.blocks.length; index++) {
  14978. var block = this.blocks[index];
  14979. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  14980. }
  14981. return;
  14982. }
  14983. if (allowDuplicate) {
  14984. selection.concat(this.entries);
  14985. } else {
  14986. selection.concatWithNoDuplicate(this.entries);
  14987. }
  14988. }
  14989. };
  14990. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  14991. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  14992. if (this.blocks) {
  14993. for (var index = 0; index < this.blocks.length; index++) {
  14994. var block = this.blocks[index];
  14995. block.intersectsRay(ray, selection);
  14996. }
  14997. return;
  14998. }
  14999. selection.concatWithNoDuplicate(this.entries);
  15000. }
  15001. };
  15002. OctreeBlock.prototype.createInnerBlocks = function () {
  15003. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  15004. };
  15005. return OctreeBlock;
  15006. })();
  15007. BABYLON.OctreeBlock = OctreeBlock;
  15008. })(BABYLON || (BABYLON = {}));
  15009. //# sourceMappingURL=babylon.octreeBlock.js.map
  15010. var BABYLON;
  15011. (function (BABYLON) {
  15012. var Bone = (function () {
  15013. function Bone(name, skeleton, parentBone, matrix) {
  15014. this.name = name;
  15015. this.children = new Array();
  15016. this.animations = new Array();
  15017. this._worldTransform = new BABYLON.Matrix();
  15018. this._absoluteTransform = new BABYLON.Matrix();
  15019. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  15020. this._skeleton = skeleton;
  15021. this._matrix = matrix;
  15022. this._baseMatrix = matrix;
  15023. skeleton.bones.push(this);
  15024. if (parentBone) {
  15025. this._parent = parentBone;
  15026. parentBone.children.push(this);
  15027. } else {
  15028. this._parent = null;
  15029. }
  15030. this._updateDifferenceMatrix();
  15031. }
  15032. // Members
  15033. Bone.prototype.getParent = function () {
  15034. return this._parent;
  15035. };
  15036. Bone.prototype.getLocalMatrix = function () {
  15037. return this._matrix;
  15038. };
  15039. Bone.prototype.getBaseMatrix = function () {
  15040. return this._baseMatrix;
  15041. };
  15042. Bone.prototype.getWorldMatrix = function () {
  15043. return this._worldTransform;
  15044. };
  15045. Bone.prototype.getInvertedAbsoluteTransform = function () {
  15046. return this._invertedAbsoluteTransform;
  15047. };
  15048. Bone.prototype.getAbsoluteMatrix = function () {
  15049. var matrix = this._matrix.clone();
  15050. var parent = this._parent;
  15051. while (parent) {
  15052. matrix = matrix.multiply(parent.getLocalMatrix());
  15053. parent = parent.getParent();
  15054. }
  15055. return matrix;
  15056. };
  15057. // Methods
  15058. Bone.prototype.updateMatrix = function (matrix) {
  15059. this._matrix = matrix;
  15060. this._skeleton._markAsDirty();
  15061. this._updateDifferenceMatrix();
  15062. };
  15063. Bone.prototype._updateDifferenceMatrix = function () {
  15064. if (this._parent) {
  15065. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  15066. } else {
  15067. this._absoluteTransform.copyFrom(this._matrix);
  15068. }
  15069. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  15070. for (var index = 0; index < this.children.length; index++) {
  15071. this.children[index]._updateDifferenceMatrix();
  15072. }
  15073. };
  15074. Bone.prototype.markAsDirty = function () {
  15075. this._skeleton._markAsDirty();
  15076. };
  15077. return Bone;
  15078. })();
  15079. BABYLON.Bone = Bone;
  15080. })(BABYLON || (BABYLON = {}));
  15081. //# sourceMappingURL=babylon.bone.js.map
  15082. var BABYLON;
  15083. (function (BABYLON) {
  15084. var Skeleton = (function () {
  15085. function Skeleton(name, id, scene) {
  15086. this.name = name;
  15087. this.id = id;
  15088. this.bones = new Array();
  15089. this._isDirty = true;
  15090. this._identity = BABYLON.Matrix.Identity();
  15091. this.bones = [];
  15092. this._scene = scene;
  15093. scene.skeletons.push(this);
  15094. }
  15095. // Members
  15096. Skeleton.prototype.getTransformMatrices = function () {
  15097. return this._transformMatrices;
  15098. };
  15099. // Methods
  15100. Skeleton.prototype._markAsDirty = function () {
  15101. this._isDirty = true;
  15102. };
  15103. Skeleton.prototype.prepare = function () {
  15104. if (!this._isDirty) {
  15105. return;
  15106. }
  15107. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  15108. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  15109. }
  15110. for (var index = 0; index < this.bones.length; index++) {
  15111. var bone = this.bones[index];
  15112. var parentBone = bone.getParent();
  15113. if (parentBone) {
  15114. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  15115. } else {
  15116. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  15117. }
  15118. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  15119. }
  15120. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  15121. this._isDirty = false;
  15122. };
  15123. Skeleton.prototype.getAnimatables = function () {
  15124. if (!this._animatables || this._animatables.length != this.bones.length) {
  15125. this._animatables = [];
  15126. for (var index = 0; index < this.bones.length; index++) {
  15127. this._animatables.push(this.bones[index]);
  15128. }
  15129. }
  15130. return this._animatables;
  15131. };
  15132. Skeleton.prototype.clone = function (name, id) {
  15133. var result = new BABYLON.Skeleton(name, id || name, this._scene);
  15134. for (var index = 0; index < this.bones.length; index++) {
  15135. var source = this.bones[index];
  15136. var parentBone = null;
  15137. if (source.getParent()) {
  15138. var parentIndex = this.bones.indexOf(source.getParent());
  15139. parentBone = result.bones[parentIndex];
  15140. }
  15141. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  15142. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  15143. }
  15144. return result;
  15145. };
  15146. return Skeleton;
  15147. })();
  15148. BABYLON.Skeleton = Skeleton;
  15149. })(BABYLON || (BABYLON = {}));
  15150. //# sourceMappingURL=babylon.skeleton.js.map
  15151. var BABYLON;
  15152. (function (BABYLON) {
  15153. var PostProcess = (function () {
  15154. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable) {
  15155. this.name = name;
  15156. this.width = -1;
  15157. this.height = -1;
  15158. this._reusable = false;
  15159. this._textures = new BABYLON.SmartArray(2);
  15160. this._currentRenderTextureInd = 0;
  15161. if (camera != null) {
  15162. this._camera = camera;
  15163. this._scene = camera.getScene();
  15164. camera.attachPostProcess(this);
  15165. this._engine = this._scene.getEngine();
  15166. } else {
  15167. this._engine = engine;
  15168. }
  15169. this._renderRatio = ratio;
  15170. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15171. this._reusable = reusable || false;
  15172. samplers = samplers || [];
  15173. samplers.push("textureSampler");
  15174. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: fragmentUrl }, ["position"], parameters || [], samplers, "");
  15175. }
  15176. PostProcess.prototype.isReusable = function () {
  15177. return this._reusable;
  15178. };
  15179. PostProcess.prototype.activate = function (camera, sourceTexture) {
  15180. camera = camera || this._camera;
  15181. var scene = camera.getScene();
  15182. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  15183. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  15184. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  15185. desiredWidth = BABYLON.Tools.GetExponantOfTwo(desiredWidth, maxSize);
  15186. desiredHeight = BABYLON.Tools.GetExponantOfTwo(desiredHeight, maxSize);
  15187. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  15188. if (this._textures.length > 0) {
  15189. for (var i = 0; i < this._textures.length; i++) {
  15190. this._engine._releaseTexture(this._textures.data[i]);
  15191. }
  15192. this._textures.reset();
  15193. }
  15194. this.width = desiredWidth;
  15195. this.height = desiredHeight;
  15196. 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 }));
  15197. if (this._reusable) {
  15198. 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 }));
  15199. }
  15200. if (this.onSizeChanged) {
  15201. this.onSizeChanged();
  15202. }
  15203. }
  15204. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  15205. if (this.onActivate) {
  15206. this.onActivate(camera);
  15207. }
  15208. // Clear
  15209. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  15210. if (this._reusable) {
  15211. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  15212. }
  15213. };
  15214. PostProcess.prototype.apply = function () {
  15215. // Check
  15216. if (!this._effect.isReady())
  15217. return null;
  15218. // States
  15219. this._engine.enableEffect(this._effect);
  15220. this._engine.setState(false);
  15221. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  15222. this._engine.setDepthBuffer(false);
  15223. this._engine.setDepthWrite(false);
  15224. // Texture
  15225. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  15226. // Parameters
  15227. if (this.onApply) {
  15228. this.onApply(this._effect);
  15229. }
  15230. return this._effect;
  15231. };
  15232. PostProcess.prototype.dispose = function (camera) {
  15233. camera = camera || this._camera;
  15234. if (this._textures.length > 0) {
  15235. for (var i = 0; i < this._textures.length; i++) {
  15236. this._engine._releaseTexture(this._textures.data[i]);
  15237. }
  15238. this._textures.reset();
  15239. }
  15240. camera.detachPostProcess(this);
  15241. var index = camera._postProcesses.indexOf(this);
  15242. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  15243. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  15244. }
  15245. };
  15246. return PostProcess;
  15247. })();
  15248. BABYLON.PostProcess = PostProcess;
  15249. })(BABYLON || (BABYLON = {}));
  15250. //# sourceMappingURL=babylon.postProcess.js.map
  15251. var BABYLON;
  15252. (function (BABYLON) {
  15253. var PostProcessManager = (function () {
  15254. function PostProcessManager(scene) {
  15255. this._vertexDeclaration = [2];
  15256. this._vertexStrideSize = 2 * 4;
  15257. this._scene = scene;
  15258. // VBO
  15259. var vertices = [];
  15260. vertices.push(1, 1);
  15261. vertices.push(-1, 1);
  15262. vertices.push(-1, -1);
  15263. vertices.push(1, -1);
  15264. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  15265. // Indices
  15266. var indices = [];
  15267. indices.push(0);
  15268. indices.push(1);
  15269. indices.push(2);
  15270. indices.push(0);
  15271. indices.push(2);
  15272. indices.push(3);
  15273. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  15274. }
  15275. // Methods
  15276. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  15277. var postProcesses = this._scene.activeCamera._postProcesses;
  15278. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  15279. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  15280. return false;
  15281. }
  15282. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  15283. return true;
  15284. };
  15285. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture) {
  15286. var postProcesses = this._scene.activeCamera._postProcesses;
  15287. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  15288. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  15289. return;
  15290. }
  15291. var engine = this._scene.getEngine();
  15292. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  15293. if (index < postProcessesTakenIndices.length - 1) {
  15294. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  15295. } else {
  15296. if (targetTexture) {
  15297. engine.bindFramebuffer(targetTexture);
  15298. } else {
  15299. engine.restoreDefaultFramebuffer();
  15300. }
  15301. }
  15302. if (doNotPresent) {
  15303. break;
  15304. }
  15305. var pp = postProcesses[postProcessesTakenIndices[index]];
  15306. var effect = pp.apply();
  15307. if (effect) {
  15308. if (pp.onBeforeRender) {
  15309. pp.onBeforeRender(effect);
  15310. }
  15311. // VBOs
  15312. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  15313. // Draw order
  15314. engine.draw(true, 0, 6);
  15315. }
  15316. }
  15317. // Restore depth buffer
  15318. engine.setDepthBuffer(true);
  15319. engine.setDepthWrite(true);
  15320. };
  15321. PostProcessManager.prototype.dispose = function () {
  15322. if (this._vertexBuffer) {
  15323. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  15324. this._vertexBuffer = null;
  15325. }
  15326. if (this._indexBuffer) {
  15327. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  15328. this._indexBuffer = null;
  15329. }
  15330. };
  15331. return PostProcessManager;
  15332. })();
  15333. BABYLON.PostProcessManager = PostProcessManager;
  15334. })(BABYLON || (BABYLON = {}));
  15335. //# sourceMappingURL=babylon.postProcessManager.js.map
  15336. var BABYLON;
  15337. (function (BABYLON) {
  15338. var PassPostProcess = (function (_super) {
  15339. __extends(PassPostProcess, _super);
  15340. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  15341. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  15342. }
  15343. return PassPostProcess;
  15344. })(BABYLON.PostProcess);
  15345. BABYLON.PassPostProcess = PassPostProcess;
  15346. })(BABYLON || (BABYLON = {}));
  15347. //# sourceMappingURL=babylon.passPostProcess.js.map
  15348. var BABYLON;
  15349. (function (BABYLON) {
  15350. var BlurPostProcess = (function (_super) {
  15351. __extends(BlurPostProcess, _super);
  15352. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  15353. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  15354. var _this = this;
  15355. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  15356. this.direction = direction;
  15357. this.blurWidth = blurWidth;
  15358. this.onApply = function (effect) {
  15359. effect.setFloat2("screenSize", _this.width, _this.height);
  15360. effect.setVector2("direction", _this.direction);
  15361. effect.setFloat("blurWidth", _this.blurWidth);
  15362. };
  15363. }
  15364. return BlurPostProcess;
  15365. })(BABYLON.PostProcess);
  15366. BABYLON.BlurPostProcess = BlurPostProcess;
  15367. })(BABYLON || (BABYLON = {}));
  15368. //# sourceMappingURL=babylon.blurPostProcess.js.map
  15369. var BABYLON;
  15370. (function (BABYLON) {
  15371. var FilterPostProcess = (function (_super) {
  15372. __extends(FilterPostProcess, _super);
  15373. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  15374. var _this = this;
  15375. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  15376. this.kernelMatrix = kernelMatrix;
  15377. this.onApply = function (effect) {
  15378. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  15379. };
  15380. }
  15381. return FilterPostProcess;
  15382. })(BABYLON.PostProcess);
  15383. BABYLON.FilterPostProcess = FilterPostProcess;
  15384. })(BABYLON || (BABYLON = {}));
  15385. //# sourceMappingURL=babylon.filterPostProcess.js.map
  15386. var BABYLON;
  15387. (function (BABYLON) {
  15388. var RefractionPostProcess = (function (_super) {
  15389. __extends(RefractionPostProcess, _super);
  15390. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  15391. var _this = this;
  15392. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  15393. this.color = color;
  15394. this.depth = depth;
  15395. this.colorLevel = colorLevel;
  15396. this.onActivate = function (cam) {
  15397. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  15398. };
  15399. this.onApply = function (effect) {
  15400. effect.setColor3("baseColor", _this.color);
  15401. effect.setFloat("depth", _this.depth);
  15402. effect.setFloat("colorLevel", _this.colorLevel);
  15403. effect.setTexture("refractionSampler", _this._refRexture);
  15404. };
  15405. }
  15406. // Methods
  15407. RefractionPostProcess.prototype.dispose = function (camera) {
  15408. if (this._refRexture) {
  15409. this._refRexture.dispose();
  15410. }
  15411. _super.prototype.dispose.call(this, camera);
  15412. };
  15413. return RefractionPostProcess;
  15414. })(BABYLON.PostProcess);
  15415. BABYLON.RefractionPostProcess = RefractionPostProcess;
  15416. })(BABYLON || (BABYLON = {}));
  15417. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  15418. var BABYLON;
  15419. (function (BABYLON) {
  15420. var BlackAndWhitePostProcess = (function (_super) {
  15421. __extends(BlackAndWhitePostProcess, _super);
  15422. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  15423. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  15424. }
  15425. return BlackAndWhitePostProcess;
  15426. })(BABYLON.PostProcess);
  15427. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  15428. })(BABYLON || (BABYLON = {}));
  15429. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  15430. var BABYLON;
  15431. (function (BABYLON) {
  15432. var ConvolutionPostProcess = (function (_super) {
  15433. __extends(ConvolutionPostProcess, _super);
  15434. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  15435. var _this = this;
  15436. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  15437. this.kernel = kernel;
  15438. this.onApply = function (effect) {
  15439. effect.setFloat2("screenSize", _this.width, _this.height);
  15440. effect.setArray("kernel", _this.kernel);
  15441. };
  15442. }
  15443. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  15444. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  15445. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  15446. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  15447. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  15448. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  15449. return ConvolutionPostProcess;
  15450. })(BABYLON.PostProcess);
  15451. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  15452. })(BABYLON || (BABYLON = {}));
  15453. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  15454. var BABYLON;
  15455. (function (BABYLON) {
  15456. var FxaaPostProcess = (function (_super) {
  15457. __extends(FxaaPostProcess, _super);
  15458. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  15459. var _this = this;
  15460. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  15461. this.onSizeChanged = function () {
  15462. _this.texelWidth = 1.0 / _this.width;
  15463. _this.texelHeight = 1.0 / _this.height;
  15464. };
  15465. this.onApply = function (effect) {
  15466. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  15467. };
  15468. }
  15469. return FxaaPostProcess;
  15470. })(BABYLON.PostProcess);
  15471. BABYLON.FxaaPostProcess = FxaaPostProcess;
  15472. })(BABYLON || (BABYLON = {}));
  15473. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  15474. var BABYLON;
  15475. (function (BABYLON) {
  15476. var LensFlare = (function () {
  15477. function LensFlare(size, position, color, imgUrl, system) {
  15478. this.size = size;
  15479. this.position = position;
  15480. this.dispose = function () {
  15481. if (this.texture) {
  15482. this.texture.dispose();
  15483. }
  15484. // Remove from scene
  15485. var index = this._system.lensFlares.indexOf(this);
  15486. this._system.lensFlares.splice(index, 1);
  15487. };
  15488. this.color = color || new BABYLON.Color3(1, 1, 1);
  15489. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  15490. this._system = system;
  15491. system.lensFlares.push(this);
  15492. }
  15493. return LensFlare;
  15494. })();
  15495. BABYLON.LensFlare = LensFlare;
  15496. })(BABYLON || (BABYLON = {}));
  15497. //# sourceMappingURL=babylon.lensFlare.js.map
  15498. var BABYLON;
  15499. (function (BABYLON) {
  15500. var LensFlareSystem = (function () {
  15501. function LensFlareSystem(name, emitter, scene) {
  15502. this.name = name;
  15503. this.lensFlares = new Array();
  15504. this.borderLimit = 300;
  15505. this._vertexDeclaration = [2];
  15506. this._vertexStrideSize = 2 * 4;
  15507. this._isEnabled = true;
  15508. this._scene = scene;
  15509. this._emitter = emitter;
  15510. scene.lensFlareSystems.push(this);
  15511. this.meshesSelectionPredicate = function (m) {
  15512. return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0);
  15513. };
  15514. // VBO
  15515. var vertices = [];
  15516. vertices.push(1, 1);
  15517. vertices.push(-1, 1);
  15518. vertices.push(-1, -1);
  15519. vertices.push(1, -1);
  15520. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  15521. // Indices
  15522. var indices = [];
  15523. indices.push(0);
  15524. indices.push(1);
  15525. indices.push(2);
  15526. indices.push(0);
  15527. indices.push(2);
  15528. indices.push(3);
  15529. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  15530. // Effects
  15531. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  15532. }
  15533. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  15534. get: function () {
  15535. return this._isEnabled;
  15536. },
  15537. set: function (value) {
  15538. this._isEnabled = value;
  15539. },
  15540. enumerable: true,
  15541. configurable: true
  15542. });
  15543. LensFlareSystem.prototype.getScene = function () {
  15544. return this._scene;
  15545. };
  15546. LensFlareSystem.prototype.getEmitter = function () {
  15547. return this._emitter;
  15548. };
  15549. LensFlareSystem.prototype.getEmitterPosition = function () {
  15550. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  15551. };
  15552. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  15553. var position = this.getEmitterPosition();
  15554. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  15555. this._positionX = position.x;
  15556. this._positionY = position.y;
  15557. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  15558. if (position.z > 0) {
  15559. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  15560. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  15561. return true;
  15562. }
  15563. }
  15564. return false;
  15565. };
  15566. LensFlareSystem.prototype._isVisible = function () {
  15567. if (!this._isEnabled) {
  15568. return false;
  15569. }
  15570. var emitterPosition = this.getEmitterPosition();
  15571. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  15572. var distance = direction.length();
  15573. direction.normalize();
  15574. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  15575. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  15576. return !pickInfo.hit || pickInfo.distance > distance;
  15577. };
  15578. LensFlareSystem.prototype.render = function () {
  15579. if (!this._effect.isReady())
  15580. return false;
  15581. var engine = this._scene.getEngine();
  15582. var viewport = this._scene.activeCamera.viewport;
  15583. var globalViewport = viewport.toGlobal(engine);
  15584. // Position
  15585. if (!this.computeEffectivePosition(globalViewport)) {
  15586. return false;
  15587. }
  15588. // Visibility
  15589. if (!this._isVisible()) {
  15590. return false;
  15591. }
  15592. // Intensity
  15593. var awayX;
  15594. var awayY;
  15595. if (this._positionX < this.borderLimit + globalViewport.x) {
  15596. awayX = this.borderLimit + globalViewport.x - this._positionX;
  15597. } else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  15598. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  15599. } else {
  15600. awayX = 0;
  15601. }
  15602. if (this._positionY < this.borderLimit + globalViewport.y) {
  15603. awayY = this.borderLimit + globalViewport.y - this._positionY;
  15604. } else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  15605. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  15606. } else {
  15607. awayY = 0;
  15608. }
  15609. var away = (awayX > awayY) ? awayX : awayY;
  15610. if (away > this.borderLimit) {
  15611. away = this.borderLimit;
  15612. }
  15613. var intensity = 1.0 - (away / this.borderLimit);
  15614. if (intensity < 0) {
  15615. return false;
  15616. }
  15617. if (intensity > 1.0) {
  15618. intensity = 1.0;
  15619. }
  15620. // Position
  15621. var centerX = globalViewport.x + globalViewport.width / 2;
  15622. var centerY = globalViewport.y + globalViewport.height / 2;
  15623. var distX = centerX - this._positionX;
  15624. var distY = centerY - this._positionY;
  15625. // Effects
  15626. engine.enableEffect(this._effect);
  15627. engine.setState(false);
  15628. engine.setDepthBuffer(false);
  15629. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  15630. // VBOs
  15631. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  15632. for (var index = 0; index < this.lensFlares.length; index++) {
  15633. var flare = this.lensFlares[index];
  15634. var x = centerX - (distX * flare.position);
  15635. var y = centerY - (distY * flare.position);
  15636. var cw = flare.size;
  15637. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  15638. var cx = 2 * (x / globalViewport.width) - 1.0;
  15639. var cy = 1.0 - 2 * (y / globalViewport.height);
  15640. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  15641. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  15642. // Texture
  15643. this._effect.setTexture("textureSampler", flare.texture);
  15644. // Color
  15645. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  15646. // Draw order
  15647. engine.draw(true, 0, 6);
  15648. }
  15649. engine.setDepthBuffer(true);
  15650. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  15651. return true;
  15652. };
  15653. LensFlareSystem.prototype.dispose = function () {
  15654. if (this._vertexBuffer) {
  15655. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  15656. this._vertexBuffer = null;
  15657. }
  15658. if (this._indexBuffer) {
  15659. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  15660. this._indexBuffer = null;
  15661. }
  15662. while (this.lensFlares.length) {
  15663. this.lensFlares[0].dispose();
  15664. }
  15665. // Remove from scene
  15666. var index = this._scene.lensFlareSystems.indexOf(this);
  15667. this._scene.lensFlareSystems.splice(index, 1);
  15668. };
  15669. return LensFlareSystem;
  15670. })();
  15671. BABYLON.LensFlareSystem = LensFlareSystem;
  15672. })(BABYLON || (BABYLON = {}));
  15673. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  15674. var BABYLON;
  15675. (function (BABYLON) {
  15676. var IntersectionInfo = (function () {
  15677. function IntersectionInfo(bu, bv, distance) {
  15678. this.bu = bu;
  15679. this.bv = bv;
  15680. this.distance = distance;
  15681. this.faceId = 0;
  15682. }
  15683. return IntersectionInfo;
  15684. })();
  15685. BABYLON.IntersectionInfo = IntersectionInfo;
  15686. var PickingInfo = (function () {
  15687. function PickingInfo() {
  15688. this.hit = false;
  15689. this.distance = 0;
  15690. this.pickedPoint = null;
  15691. this.pickedMesh = null;
  15692. this.bu = 0;
  15693. this.bv = 0;
  15694. this.faceId = -1;
  15695. }
  15696. // Methods
  15697. PickingInfo.prototype.getNormal = function () {
  15698. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15699. return null;
  15700. }
  15701. var indices = this.pickedMesh.getIndices();
  15702. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15703. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  15704. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  15705. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  15706. normal0 = normal0.scale(this.bu);
  15707. normal1 = normal1.scale(this.bv);
  15708. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  15709. return new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  15710. };
  15711. PickingInfo.prototype.getTextureCoordinates = function () {
  15712. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  15713. return null;
  15714. }
  15715. var indices = this.pickedMesh.getIndices();
  15716. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  15717. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  15718. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  15719. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  15720. uv0 = uv0.scale(this.bu);
  15721. uv1 = uv1.scale(this.bv);
  15722. uv2 = uv2.scale(1.0 - this.bu - this.bv);
  15723. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  15724. };
  15725. return PickingInfo;
  15726. })();
  15727. BABYLON.PickingInfo = PickingInfo;
  15728. })(BABYLON || (BABYLON = {}));
  15729. //# sourceMappingURL=babylon.pickingInfo.js.map
  15730. var BABYLON;
  15731. (function (BABYLON) {
  15732. var FilesInput = (function () {
  15733. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  15734. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  15735. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  15736. this.engine = p_engine;
  15737. this.canvas = p_canvas;
  15738. this.currentScene = p_scene;
  15739. this.sceneLoadedCallback = p_sceneLoadedCallback;
  15740. this.progressCallback = p_progressCallback;
  15741. this.additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  15742. this.textureLoadingCallback = p_textureLoadingCallback;
  15743. this.startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  15744. }
  15745. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  15746. var _this = this;
  15747. if (p_elementToMonitor) {
  15748. this.elementToMonitor = p_elementToMonitor;
  15749. this.elementToMonitor.addEventListener("dragenter", function (e) {
  15750. _this.drag(e);
  15751. }, false);
  15752. this.elementToMonitor.addEventListener("dragover", function (e) {
  15753. _this.drag(e);
  15754. }, false);
  15755. this.elementToMonitor.addEventListener("drop", function (e) {
  15756. _this.drop(e);
  15757. }, false);
  15758. }
  15759. };
  15760. FilesInput.prototype.renderFunction = function () {
  15761. if (this.additionnalRenderLoopLogicCallback) {
  15762. this.additionnalRenderLoopLogicCallback();
  15763. }
  15764. if (this.currentScene) {
  15765. if (this.textureLoadingCallback) {
  15766. var remaining = this.currentScene.getWaitingItemsCount();
  15767. if (remaining > 0) {
  15768. this.textureLoadingCallback(remaining);
  15769. }
  15770. }
  15771. this.currentScene.render();
  15772. }
  15773. };
  15774. FilesInput.prototype.drag = function (e) {
  15775. e.stopPropagation();
  15776. e.preventDefault();
  15777. };
  15778. FilesInput.prototype.drop = function (eventDrop) {
  15779. eventDrop.stopPropagation();
  15780. eventDrop.preventDefault();
  15781. this.loadFiles(eventDrop);
  15782. };
  15783. FilesInput.prototype.loadFiles = function (event) {
  15784. var _this = this;
  15785. var that = this;
  15786. if (this.startingProcessingFilesCallback)
  15787. this.startingProcessingFilesCallback();
  15788. var sceneFileToLoad;
  15789. var filesToLoad;
  15790. // Handling data transfer via drag'n'drop
  15791. if (event && event.dataTransfer && event.dataTransfer.files) {
  15792. filesToLoad = event.dataTransfer.files;
  15793. }
  15794. // Handling files from input files
  15795. if (event && event.target && event.target.files) {
  15796. filesToLoad = event.target.files;
  15797. }
  15798. if (filesToLoad && filesToLoad.length > 0) {
  15799. for (var i = 0; i < filesToLoad.length; i++) {
  15800. switch (filesToLoad[i].type) {
  15801. case "image/jpeg":
  15802. case "image/png":
  15803. BABYLON.FilesInput.FilesTextures[filesToLoad[i].name] = filesToLoad[i];
  15804. break;
  15805. case "image/targa":
  15806. case "image/vnd.ms-dds":
  15807. BABYLON.FilesInput.FilesToLoad[filesToLoad[i].name] = filesToLoad[i];
  15808. break;
  15809. default:
  15810. 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) {
  15811. sceneFileToLoad = filesToLoad[i];
  15812. }
  15813. break;
  15814. }
  15815. }
  15816. // If a ".babylon" file has been provided
  15817. if (sceneFileToLoad) {
  15818. if (this.currentScene) {
  15819. this.engine.stopRenderLoop();
  15820. this.currentScene.dispose();
  15821. }
  15822. BABYLON.SceneLoader.Load("file:", sceneFileToLoad, this.engine, function (newScene) {
  15823. that.currentScene = newScene;
  15824. // Wait for textures and shaders to be ready
  15825. that.currentScene.executeWhenReady(function () {
  15826. // Attach camera to canvas inputs
  15827. if (that.currentScene.activeCamera) {
  15828. that.currentScene.activeCamera.attachControl(that.canvas);
  15829. }
  15830. if (that.sceneLoadedCallback) {
  15831. that.sceneLoadedCallback(sceneFileToLoad, that.currentScene);
  15832. }
  15833. that.engine.runRenderLoop(function () {
  15834. that.renderFunction();
  15835. });
  15836. });
  15837. }, function (progress) {
  15838. if (_this.progressCallback) {
  15839. _this.progressCallback(progress);
  15840. }
  15841. });
  15842. } else {
  15843. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  15844. }
  15845. }
  15846. };
  15847. FilesInput.FilesTextures = new Array();
  15848. FilesInput.FilesToLoad = new Array();
  15849. return FilesInput;
  15850. })();
  15851. BABYLON.FilesInput = FilesInput;
  15852. })(BABYLON || (BABYLON = {}));
  15853. //# sourceMappingURL=babylon.filesInput.js.map
  15854. var BABYLON;
  15855. (function (BABYLON) {
  15856. var OimoJSPlugin = (function () {
  15857. function OimoJSPlugin() {
  15858. this._registeredMeshes = [];
  15859. /**
  15860. * Update the body position according to the mesh position
  15861. * @param mesh
  15862. */
  15863. this.updateBodyPosition = function (mesh) {
  15864. for (var index = 0; index < this._registeredMeshes.length; index++) {
  15865. var registeredMesh = this._registeredMeshes[index];
  15866. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  15867. var body = registeredMesh.body.body;
  15868. mesh.computeWorldMatrix(true);
  15869. var center = mesh.getBoundingInfo().boundingBox.center;
  15870. body.setPosition(center.x, center.y, center.z);
  15871. body.setOrientation(mesh.rotation.x, mesh.rotation.y, mesh.rotation.z);
  15872. return;
  15873. }
  15874. // Case where the parent has been updated
  15875. if (registeredMesh.mesh.parent === mesh) {
  15876. mesh.computeWorldMatrix(true);
  15877. registeredMesh.mesh.computeWorldMatrix(true);
  15878. var absolutePosition = registeredMesh.mesh.getAbsolutePosition();
  15879. var absoluteRotation = mesh.rotation;
  15880. body = registeredMesh.body.body;
  15881. body.setPosition(absolutePosition.x, absolutePosition.y, absolutePosition.z);
  15882. body.setOrientation(absoluteRotation.x, absoluteRotation.y, absoluteRotation.z);
  15883. return;
  15884. }
  15885. }
  15886. };
  15887. }
  15888. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  15889. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  15890. };
  15891. OimoJSPlugin.prototype.initialize = function (iterations) {
  15892. this._world = new OIMO.World();
  15893. this._world.clear();
  15894. };
  15895. OimoJSPlugin.prototype.setGravity = function (gravity) {
  15896. this._world.gravity = gravity;
  15897. };
  15898. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  15899. var body = null;
  15900. this.unregisterMesh(mesh);
  15901. mesh.computeWorldMatrix(true);
  15902. switch (impostor) {
  15903. case BABYLON.PhysicsEngine.SphereImpostor:
  15904. var bbox = mesh.getBoundingInfo().boundingBox;
  15905. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  15906. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  15907. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  15908. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  15909. // The delta between the mesh position and the mesh bounding box center
  15910. var deltaPosition = mesh.position.subtract(bbox.center);
  15911. body = new OIMO.Body({
  15912. type: 'sphere',
  15913. size: [size],
  15914. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  15915. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  15916. move: options.mass != 0,
  15917. config: [options.mass, options.friction, options.restitution],
  15918. world: this._world
  15919. });
  15920. this._registeredMeshes.push({
  15921. mesh: mesh,
  15922. body: body,
  15923. delta: deltaPosition
  15924. });
  15925. break;
  15926. case BABYLON.PhysicsEngine.PlaneImpostor:
  15927. case BABYLON.PhysicsEngine.BoxImpostor:
  15928. bbox = mesh.getBoundingInfo().boundingBox;
  15929. var min = bbox.minimumWorld;
  15930. var max = bbox.maximumWorld;
  15931. var box = max.subtract(min);
  15932. var sizeX = this._checkWithEpsilon(box.x);
  15933. var sizeY = this._checkWithEpsilon(box.y);
  15934. var sizeZ = this._checkWithEpsilon(box.z);
  15935. // The delta between the mesh position and the mesh boudning box center
  15936. var deltaPosition = mesh.position.subtract(bbox.center);
  15937. body = new OIMO.Body({
  15938. type: 'box',
  15939. size: [sizeX, sizeY, sizeZ],
  15940. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  15941. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  15942. move: options.mass != 0,
  15943. config: [options.mass, options.friction, options.restitution],
  15944. world: this._world
  15945. });
  15946. this._registeredMeshes.push({
  15947. mesh: mesh,
  15948. body: body,
  15949. delta: deltaPosition
  15950. });
  15951. break;
  15952. }
  15953. return body;
  15954. };
  15955. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  15956. var types = [], sizes = [], positions = [], rotations = [];
  15957. var initialMesh = parts[0].mesh;
  15958. for (var index = 0; index < parts.length; index++) {
  15959. var part = parts[index];
  15960. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  15961. types.push(bodyParameters.type);
  15962. sizes.push.apply(sizes, bodyParameters.size);
  15963. positions.push.apply(positions, bodyParameters.pos);
  15964. rotations.push.apply(rotations, bodyParameters.rot);
  15965. }
  15966. var body = new OIMO.Body({
  15967. type: types,
  15968. size: sizes,
  15969. pos: positions,
  15970. rot: rotations,
  15971. move: options.mass != 0,
  15972. config: [options.mass, options.friction, options.restitution],
  15973. world: this._world
  15974. });
  15975. this._registeredMeshes.push({
  15976. mesh: initialMesh,
  15977. body: body
  15978. });
  15979. return body;
  15980. };
  15981. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  15982. var bodyParameters = null;
  15983. var mesh = part.mesh;
  15984. switch (part.impostor) {
  15985. case BABYLON.PhysicsEngine.SphereImpostor:
  15986. var bbox = mesh.getBoundingInfo().boundingBox;
  15987. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  15988. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  15989. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  15990. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  15991. bodyParameters = {
  15992. type: 'sphere',
  15993. /* bug with oimo : sphere needs 3 sizes in this case */
  15994. size: [size, -1, -1],
  15995. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  15996. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  15997. };
  15998. break;
  15999. case BABYLON.PhysicsEngine.PlaneImpostor:
  16000. case BABYLON.PhysicsEngine.BoxImpostor:
  16001. bbox = mesh.getBoundingInfo().boundingBox;
  16002. var min = bbox.minimumWorld;
  16003. var max = bbox.maximumWorld;
  16004. var box = max.subtract(min);
  16005. var sizeX = this._checkWithEpsilon(box.x);
  16006. var sizeY = this._checkWithEpsilon(box.y);
  16007. var sizeZ = this._checkWithEpsilon(box.z);
  16008. var relativePosition = mesh.position;
  16009. bodyParameters = {
  16010. type: 'box',
  16011. size: [sizeX, sizeY, sizeZ],
  16012. pos: [relativePosition.x, relativePosition.y, relativePosition.z],
  16013. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  16014. };
  16015. break;
  16016. }
  16017. return bodyParameters;
  16018. };
  16019. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  16020. for (var index = 0; index < this._registeredMeshes.length; index++) {
  16021. var registeredMesh = this._registeredMeshes[index];
  16022. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  16023. if (registeredMesh.body) {
  16024. this._world.removeRigidBody(registeredMesh.body.body);
  16025. this._unbindBody(registeredMesh.body);
  16026. }
  16027. this._registeredMeshes.splice(index, 1);
  16028. return;
  16029. }
  16030. }
  16031. };
  16032. OimoJSPlugin.prototype._unbindBody = function (body) {
  16033. for (var index = 0; index < this._registeredMeshes.length; index++) {
  16034. var registeredMesh = this._registeredMeshes[index];
  16035. if (registeredMesh.body === body) {
  16036. registeredMesh.body = null;
  16037. }
  16038. }
  16039. };
  16040. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  16041. for (var index = 0; index < this._registeredMeshes.length; index++) {
  16042. var registeredMesh = this._registeredMeshes[index];
  16043. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  16044. // Get object mass to have a behaviour similar to cannon.js
  16045. var mass = registeredMesh.body.body.massInfo.mass;
  16046. // The force is scaled with the mass of object
  16047. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  16048. return;
  16049. }
  16050. }
  16051. };
  16052. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  16053. var body1 = null, body2 = null;
  16054. for (var index = 0; index < this._registeredMeshes.length; index++) {
  16055. var registeredMesh = this._registeredMeshes[index];
  16056. if (registeredMesh.mesh === mesh1) {
  16057. body1 = registeredMesh.body.body;
  16058. } else if (registeredMesh.mesh === mesh2) {
  16059. body2 = registeredMesh.body.body;
  16060. }
  16061. }
  16062. if (!body1 || !body2) {
  16063. return false;
  16064. }
  16065. if (!options) {
  16066. options = {};
  16067. }
  16068. new OIMO.Link({
  16069. type: options.type,
  16070. body1: body1,
  16071. body2: body2,
  16072. min: options.min,
  16073. max: options.max,
  16074. axe1: options.axe1,
  16075. axe2: options.axe2,
  16076. pos1: [pivot1.x, pivot1.y, pivot1.z],
  16077. pos2: [pivot2.x, pivot2.y, pivot2.z],
  16078. collision: options.collision,
  16079. spring: options.spring,
  16080. world: this._world
  16081. });
  16082. return true;
  16083. };
  16084. OimoJSPlugin.prototype.dispose = function () {
  16085. this._world.clear();
  16086. while (this._registeredMeshes.length) {
  16087. this.unregisterMesh(this._registeredMeshes[0].mesh);
  16088. }
  16089. };
  16090. OimoJSPlugin.prototype.isSupported = function () {
  16091. return OIMO !== undefined;
  16092. };
  16093. OimoJSPlugin.prototype._getLastShape = function (body) {
  16094. var lastShape = body.shapes;
  16095. while (lastShape.next) {
  16096. lastShape = lastShape.next;
  16097. }
  16098. return lastShape;
  16099. };
  16100. OimoJSPlugin.prototype.runOneStep = function (time) {
  16101. this._world.step();
  16102. // Update the position of all registered meshes
  16103. var i = this._registeredMeshes.length;
  16104. var m;
  16105. while (i--) {
  16106. var body = this._registeredMeshes[i].body.body;
  16107. var mesh = this._registeredMeshes[i].mesh;
  16108. var delta = this._registeredMeshes[i].delta;
  16109. if (!body.sleeping) {
  16110. if (body.shapes.next) {
  16111. var parentShape = this._getLastShape(body);
  16112. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  16113. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  16114. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  16115. var mtx = BABYLON.Matrix.FromArray(body.getMatrix());
  16116. if (!mesh.rotationQuaternion) {
  16117. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  16118. }
  16119. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  16120. mesh.computeWorldMatrix();
  16121. } else {
  16122. m = body.getMatrix();
  16123. mtx = BABYLON.Matrix.FromArray(m);
  16124. // Body position
  16125. var bodyX = mtx.m[12], bodyY = mtx.m[13], bodyZ = mtx.m[14];
  16126. if (!delta) {
  16127. mesh.position.x = bodyX;
  16128. mesh.position.y = bodyY;
  16129. mesh.position.z = bodyZ;
  16130. } else {
  16131. mesh.position.x = bodyX + delta.x;
  16132. mesh.position.y = bodyY + delta.y;
  16133. mesh.position.z = bodyZ + delta.z;
  16134. }
  16135. if (!mesh.rotationQuaternion) {
  16136. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  16137. }
  16138. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  16139. mesh.computeWorldMatrix();
  16140. }
  16141. }
  16142. }
  16143. };
  16144. return OimoJSPlugin;
  16145. })();
  16146. BABYLON.OimoJSPlugin = OimoJSPlugin;
  16147. })(BABYLON || (BABYLON = {}));
  16148. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  16149. var BABYLON;
  16150. (function (BABYLON) {
  16151. var PhysicsEngine = (function () {
  16152. function PhysicsEngine(plugin) {
  16153. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  16154. }
  16155. PhysicsEngine.prototype._initialize = function (gravity) {
  16156. this._currentPlugin.initialize();
  16157. this._setGravity(gravity);
  16158. };
  16159. PhysicsEngine.prototype._runOneStep = function (delta) {
  16160. if (delta > 0.1) {
  16161. delta = 0.1;
  16162. } else if (delta <= 0) {
  16163. delta = 1.0 / 60.0;
  16164. }
  16165. this._currentPlugin.runOneStep(delta);
  16166. };
  16167. PhysicsEngine.prototype._setGravity = function (gravity) {
  16168. this.gravity = gravity || new BABYLON.Vector3(0, -9.82, 0);
  16169. this._currentPlugin.setGravity(this.gravity);
  16170. };
  16171. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  16172. return this._currentPlugin.registerMesh(mesh, impostor, options);
  16173. };
  16174. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  16175. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  16176. };
  16177. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  16178. this._currentPlugin.unregisterMesh(mesh);
  16179. };
  16180. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  16181. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  16182. };
  16183. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  16184. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  16185. };
  16186. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  16187. this._currentPlugin.updateBodyPosition(mesh);
  16188. };
  16189. PhysicsEngine.prototype.dispose = function () {
  16190. this._currentPlugin.dispose();
  16191. };
  16192. PhysicsEngine.prototype.isSupported = function () {
  16193. return this._currentPlugin.isSupported();
  16194. };
  16195. PhysicsEngine.NoImpostor = 0;
  16196. PhysicsEngine.SphereImpostor = 1;
  16197. PhysicsEngine.BoxImpostor = 2;
  16198. PhysicsEngine.PlaneImpostor = 3;
  16199. PhysicsEngine.MeshImpostor = 4;
  16200. PhysicsEngine.CapsuleImpostor = 5;
  16201. PhysicsEngine.ConeImpostor = 6;
  16202. PhysicsEngine.CylinderImpostor = 7;
  16203. PhysicsEngine.ConvexHullImpostor = 8;
  16204. PhysicsEngine.Epsilon = 0.001;
  16205. return PhysicsEngine;
  16206. })();
  16207. BABYLON.PhysicsEngine = PhysicsEngine;
  16208. })(BABYLON || (BABYLON = {}));
  16209. //# sourceMappingURL=babylon.physicsEngine.js.map
  16210. var BABYLON;
  16211. (function (BABYLON) {
  16212. var serializeLight = function (light) {
  16213. var serializationObject = {};
  16214. serializationObject.name = light.name;
  16215. serializationObject.id = light.id;
  16216. serializationObject.tags = BABYLON.Tags.GetTags(light);
  16217. if (light instanceof BABYLON.PointLight) {
  16218. serializationObject.type = 0;
  16219. serializationObject.position = light.position.asArray();
  16220. } else if (light instanceof BABYLON.DirectionalLight) {
  16221. serializationObject.type = 1;
  16222. var directionalLight = light;
  16223. serializationObject.position = directionalLight.position.asArray();
  16224. serializationObject.direction = directionalLight.direction.asArray();
  16225. } else if (light instanceof BABYLON.SpotLight) {
  16226. serializationObject.type = 2;
  16227. var spotLight = light;
  16228. serializationObject.position = spotLight.position.asArray();
  16229. serializationObject.direction = spotLight.position.asArray();
  16230. serializationObject.angle = spotLight.angle;
  16231. serializationObject.exponent = spotLight.exponent;
  16232. } else if (light instanceof BABYLON.HemisphericLight) {
  16233. serializationObject.type = 3;
  16234. var hemisphericLight = light;
  16235. serializationObject.direction = hemisphericLight.direction.asArray();
  16236. serializationObject.groundColor = hemisphericLight.groundColor.asArray();
  16237. }
  16238. if (light.intensity) {
  16239. serializationObject.intensity = light.intensity;
  16240. }
  16241. serializationObject.range = light.range;
  16242. serializationObject.diffuse = light.diffuse.asArray();
  16243. serializationObject.specular = light.specular.asArray();
  16244. return serializationObject;
  16245. };
  16246. var serializeFresnelParameter = function (fresnelParameter) {
  16247. var serializationObject = {};
  16248. serializationObject.isEnabled = fresnelParameter.isEnabled;
  16249. serializationObject.leftColor = fresnelParameter.leftColor;
  16250. serializationObject.rightColor = fresnelParameter.rightColor;
  16251. serializationObject.bias = fresnelParameter.bias;
  16252. serializationObject.power = fresnelParameter.power;
  16253. return serializationObject;
  16254. };
  16255. var serializeCamera = function (camera) {
  16256. var serializationObject = {};
  16257. serializationObject.name = camera.name;
  16258. serializationObject.tags = BABYLON.Tags.GetTags(camera);
  16259. serializationObject.id = camera.id;
  16260. serializationObject.position = camera.position.asArray();
  16261. // Parent
  16262. if (camera.parent) {
  16263. serializationObject.parentId = camera.parent.id;
  16264. }
  16265. // Target
  16266. serializationObject.rotation = camera.rotation.asArray();
  16267. // Locked target
  16268. if (camera.lockedTarget && camera.lockedTarget.id) {
  16269. serializationObject.lockedTargetId = camera.lockedTarget.id;
  16270. }
  16271. serializationObject.fov = camera.fov;
  16272. serializationObject.minZ = camera.minZ;
  16273. serializationObject.maxZ = camera.maxZ;
  16274. serializationObject.speed = camera.speed;
  16275. serializationObject.inertia = camera.inertia;
  16276. serializationObject.checkCollisions = camera.checkCollisions;
  16277. serializationObject.applyGravity = camera.applyGravity;
  16278. if (camera.ellipsoid) {
  16279. serializationObject.ellipsoid = camera.ellipsoid.asArray();
  16280. }
  16281. // Animations
  16282. appendAnimations(camera, serializationObject);
  16283. // Layer mask
  16284. serializationObject.layerMask = camera.layerMask;
  16285. return serializationObject;
  16286. };
  16287. var appendAnimations = function (source, destination) {
  16288. if (source.animations) {
  16289. destination.animations = [];
  16290. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  16291. var animation = source.animations[animationIndex];
  16292. destination.animations.push(serializeAnimation(animation));
  16293. }
  16294. }
  16295. };
  16296. var serializeAnimation = function (animation) {
  16297. var serializationObject = {};
  16298. serializationObject.name = animation.name;
  16299. serializationObject.property = animation.targetProperty;
  16300. serializationObject.framePerSecond = animation.framePerSecond;
  16301. serializationObject.dataType = animation.dataType;
  16302. serializationObject.loopBehavior = animation.loopMode;
  16303. var dataType = animation.dataType;
  16304. serializationObject.keys = [];
  16305. var keys = animation.getKeys();
  16306. for (var index = 0; index < keys.length; index++) {
  16307. var animationKey = keys[index];
  16308. var key = {};
  16309. key.frame = animationKey.frame;
  16310. switch (dataType) {
  16311. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  16312. key.values = [animationKey.value];
  16313. break;
  16314. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  16315. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  16316. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  16317. key.values = animationKey.value.asArray();
  16318. break;
  16319. }
  16320. serializationObject.keys.push(key);
  16321. }
  16322. return serializationObject;
  16323. };
  16324. var serializeMultiMaterial = function (material) {
  16325. var serializationObject = {};
  16326. serializationObject.name = material.name;
  16327. serializationObject.id = material.id;
  16328. serializationObject.tags = BABYLON.Tags.GetTags(material);
  16329. serializationObject.materials = [];
  16330. for (var matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
  16331. var subMat = material.subMaterials[matIndex];
  16332. if (subMat) {
  16333. serializationObject.materials.push(subMat.id);
  16334. } else {
  16335. serializationObject.materials.push(null);
  16336. }
  16337. }
  16338. return serializationObject;
  16339. };
  16340. var serializeMaterial = function (material) {
  16341. var serializationObject = {};
  16342. serializationObject.name = material.name;
  16343. serializationObject.ambient = material.ambientColor.asArray();
  16344. serializationObject.diffuse = material.diffuseColor.asArray();
  16345. serializationObject.specular = material.specularColor.asArray();
  16346. serializationObject.specularPower = material.specularPower;
  16347. serializationObject.emissive = material.emissiveColor.asArray();
  16348. serializationObject.alpha = material.alpha;
  16349. serializationObject.id = material.id;
  16350. serializationObject.tags = BABYLON.Tags.GetTags(material);
  16351. serializationObject.backFaceCulling = material.backFaceCulling;
  16352. if (material.diffuseTexture) {
  16353. serializationObject.diffuseTexture = serializeTexture(material.diffuseTexture);
  16354. }
  16355. if (material.diffuseFresnelParameters) {
  16356. serializationObject.diffuseFresnelParameters = serializeFresnelParameter(material.diffuseFresnelParameters);
  16357. }
  16358. if (material.ambientTexture) {
  16359. serializationObject.ambientTexture = serializeTexture(material.ambientTexture);
  16360. }
  16361. if (material.opacityTexture) {
  16362. serializationObject.opacityTexture = serializeTexture(material.opacityTexture);
  16363. }
  16364. if (material.opacityFresnelParameters) {
  16365. serializationObject.opacityFresnelParameters = serializeFresnelParameter(material.opacityFresnelParameters);
  16366. }
  16367. if (material.reflectionTexture) {
  16368. serializationObject.reflectionTexture = serializeTexture(material.reflectionTexture);
  16369. }
  16370. if (material.reflectionFresnelParameters) {
  16371. serializationObject.reflectionFresnelParameters = serializeFresnelParameter(material.reflectionFresnelParameters);
  16372. }
  16373. if (material.emissiveTexture) {
  16374. serializationObject.emissiveTexture = serializeTexture(material.emissiveTexture);
  16375. }
  16376. if (material.emissiveFresnelParameters) {
  16377. serializationObject.emissiveFresnelParameters = serializeFresnelParameter(material.emissiveFresnelParameters);
  16378. }
  16379. if (material.specularTexture) {
  16380. serializationObject.specularTexture = serializeTexture(material.specularTexture);
  16381. }
  16382. if (material.bumpTexture) {
  16383. serializationObject.bumpTexture = serializeTexture(material.bumpTexture);
  16384. }
  16385. return serializationObject;
  16386. };
  16387. var serializeTexture = function (texture) {
  16388. var serializationObject = {};
  16389. if (!texture.name) {
  16390. return null;
  16391. }
  16392. if (texture instanceof BABYLON.CubeTexture) {
  16393. serializationObject.name = texture.name;
  16394. serializationObject.hasAlpha = texture.hasAlpha;
  16395. serializationObject.level = texture.level;
  16396. serializationObject.coordinatesMode = texture.coordinatesMode;
  16397. return serializationObject;
  16398. }
  16399. if (texture instanceof BABYLON.MirrorTexture) {
  16400. var mirrorTexture = texture;
  16401. serializationObject.renderTargetSize = mirrorTexture.getRenderSize();
  16402. serializationObject.renderList = [];
  16403. for (var index = 0; index < mirrorTexture.renderList.length; index++) {
  16404. serializationObject.renderList.push(mirrorTexture.renderList[index].id);
  16405. }
  16406. serializationObject.mirrorPlane = mirrorTexture.mirrorPlane.asArray();
  16407. } else if (texture instanceof BABYLON.RenderTargetTexture) {
  16408. var renderTargetTexture = texture;
  16409. serializationObject.renderTargetSize = renderTargetTexture.getRenderSize();
  16410. serializationObject.renderList = [];
  16411. for (index = 0; index < renderTargetTexture.renderList.length; index++) {
  16412. serializationObject.renderList.push(renderTargetTexture.renderList[index].id);
  16413. }
  16414. }
  16415. var regularTexture = texture;
  16416. serializationObject.name = texture.name;
  16417. serializationObject.hasAlpha = texture.hasAlpha;
  16418. serializationObject.level = texture.level;
  16419. serializationObject.coordinatesIndex = texture.coordinatesIndex;
  16420. serializationObject.coordinatesMode = texture.coordinatesMode;
  16421. serializationObject.uOffset = regularTexture.uOffset;
  16422. serializationObject.vOffset = regularTexture.vOffset;
  16423. serializationObject.uScale = regularTexture.uScale;
  16424. serializationObject.vScale = regularTexture.vScale;
  16425. serializationObject.uAng = regularTexture.uAng;
  16426. serializationObject.vAng = regularTexture.vAng;
  16427. serializationObject.wAng = regularTexture.wAng;
  16428. serializationObject.wrapU = texture.wrapU;
  16429. serializationObject.wrapV = texture.wrapV;
  16430. // Animations
  16431. appendAnimations(texture, serializationObject);
  16432. return serializationObject;
  16433. };
  16434. var serializeSkeleton = function (skeleton) {
  16435. var serializationObject = {};
  16436. serializationObject.name = skeleton.name;
  16437. serializationObject.id = skeleton.id;
  16438. serializationObject.bones = [];
  16439. for (var index = 0; index < skeleton.bones.length; index++) {
  16440. var bone = skeleton.bones[index];
  16441. var serializedBone = {
  16442. parentBoneIndex: bone.getParent() ? skeleton.bones.indexOf(bone.getParent()) : -1,
  16443. name: bone.name,
  16444. matrix: bone.getLocalMatrix().toArray()
  16445. };
  16446. serializationObject.bones.push(serializedBone);
  16447. if (bone.animations && bone.animations.length > 0) {
  16448. serializedBone.animation = serializeAnimation(bone.animations[0]);
  16449. }
  16450. }
  16451. return serializationObject;
  16452. };
  16453. var serializeParticleSystem = function (particleSystem) {
  16454. var serializationObject = {};
  16455. serializationObject.emitterId = particleSystem.emitter.id;
  16456. serializationObject.capacity = particleSystem.getCapacity();
  16457. if (particleSystem.particleTexture) {
  16458. serializationObject.textureName = particleSystem.particleTexture.name;
  16459. }
  16460. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  16461. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  16462. serializationObject.minSize = particleSystem.minSize;
  16463. serializationObject.maxSize = particleSystem.maxSize;
  16464. serializationObject.minLifeTime = particleSystem.minLifeTime;
  16465. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  16466. serializationObject.emitRate = particleSystem.emitRate;
  16467. serializationObject.minEmitBox = particleSystem.minEmitBox.asArray();
  16468. serializationObject.maxEmitBox = particleSystem.maxEmitBox.asArray();
  16469. serializationObject.gravity = particleSystem.gravity.asArray();
  16470. serializationObject.direction1 = particleSystem.direction1.asArray();
  16471. serializationObject.direction2 = particleSystem.direction2.asArray();
  16472. serializationObject.color1 = particleSystem.color1.asArray();
  16473. serializationObject.color2 = particleSystem.color2.asArray();
  16474. serializationObject.colorDead = particleSystem.colorDead.asArray();
  16475. serializationObject.updateSpeed = particleSystem.updateSpeed;
  16476. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  16477. serializationObject.textureMask = particleSystem.textureMask.asArray();
  16478. serializationObject.blendMode = particleSystem.blendMode;
  16479. return serializationObject;
  16480. };
  16481. var serializeLensFlareSystem = function (lensFlareSystem) {
  16482. var serializationObject = {};
  16483. serializationObject.emitterId = lensFlareSystem.getEmitter().id;
  16484. serializationObject.borderLimit = lensFlareSystem.borderLimit;
  16485. serializationObject.flares = [];
  16486. for (var index = 0; index < lensFlareSystem.lensFlares.length; index++) {
  16487. var flare = lensFlareSystem.lensFlares[index];
  16488. serializationObject.flares.push({
  16489. size: flare.size,
  16490. position: flare.position,
  16491. color: flare.color.asArray(),
  16492. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  16493. });
  16494. }
  16495. return serializationObject;
  16496. };
  16497. var serializeShadowGenerator = function (light) {
  16498. var serializationObject = {};
  16499. var shadowGenerator = light.getShadowGenerator();
  16500. serializationObject.lightId = light.id;
  16501. serializationObject.mapSize = shadowGenerator.getShadowMap().getRenderSize();
  16502. serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
  16503. serializationObject.usePoissonSampling = shadowGenerator.usePoissonSampling;
  16504. serializationObject.renderList = [];
  16505. for (var meshIndex = 0; meshIndex < shadowGenerator.getShadowMap().renderList.length; meshIndex++) {
  16506. var mesh = shadowGenerator.getShadowMap().renderList[meshIndex];
  16507. serializationObject.renderList.push(mesh.id);
  16508. }
  16509. return serializationObject;
  16510. };
  16511. var serializedGeometries = [];
  16512. var serializeGeometry = function (geometry, serializationGeometries) {
  16513. if (serializedGeometries[geometry.id]) {
  16514. return;
  16515. }
  16516. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  16517. serializationGeometries.boxes.push(serializeBox(geometry));
  16518. } else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  16519. serializationGeometries.spheres.push(serializeSphere(geometry));
  16520. } else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  16521. serializationGeometries.cylinders.push(serializeCylinder(geometry));
  16522. } else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  16523. serializationGeometries.toruses.push(serializeTorus(geometry));
  16524. } else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  16525. serializationGeometries.grounds.push(serializeGround(geometry));
  16526. } else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  16527. serializationGeometries.planes.push(serializePlane(geometry));
  16528. } else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  16529. serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
  16530. } else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  16531. throw new Error("Unknow primitive type");
  16532. } else {
  16533. serializationGeometries.vertexData.push(serializeVertexData(geometry));
  16534. }
  16535. serializedGeometries[geometry.id] = true;
  16536. };
  16537. var serializeGeometryBase = function (geometry) {
  16538. var serializationObject = {};
  16539. serializationObject.id = geometry.id;
  16540. if (BABYLON.Tags.HasTags(geometry)) {
  16541. serializationObject.tags = BABYLON.Tags.GetTags(geometry);
  16542. }
  16543. return serializationObject;
  16544. };
  16545. var serializeVertexData = function (vertexData) {
  16546. var serializationObject = serializeGeometryBase(vertexData);
  16547. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  16548. serializationObject.positions = vertexData.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16549. }
  16550. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  16551. serializationObject.normals = vertexData.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16552. }
  16553. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  16554. serializationObject.uvs = vertexData.getVerticesData(BABYLON.VertexBuffer.UVKind);
  16555. }
  16556. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  16557. serializationObject.uvs2 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  16558. }
  16559. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  16560. serializationObject.colors = vertexData.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  16561. }
  16562. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  16563. serializationObject.matricesIndices = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  16564. serializationObject.matricesIndices._isExpanded = true;
  16565. }
  16566. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  16567. serializationObject.matricesWeights = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  16568. }
  16569. serializationObject.indices = vertexData.getIndices();
  16570. return serializationObject;
  16571. };
  16572. var serializePrimitive = function (primitive) {
  16573. var serializationObject = serializeGeometryBase(primitive);
  16574. serializationObject.canBeRegenerated = primitive.canBeRegenerated();
  16575. return serializationObject;
  16576. };
  16577. var serializeBox = function (box) {
  16578. var serializationObject = serializePrimitive(box);
  16579. serializationObject.size = box.size;
  16580. return serializationObject;
  16581. };
  16582. var serializeSphere = function (sphere) {
  16583. var serializationObject = serializePrimitive(sphere);
  16584. serializationObject.segments = sphere.segments;
  16585. serializationObject.diameter = sphere.diameter;
  16586. return serializationObject;
  16587. };
  16588. var serializeCylinder = function (cylinder) {
  16589. var serializationObject = serializePrimitive(cylinder);
  16590. serializationObject.height = cylinder.height;
  16591. serializationObject.diameterTop = cylinder.diameterTop;
  16592. serializationObject.diameterBottom = cylinder.diameterBottom;
  16593. serializationObject.tessellation = cylinder.tessellation;
  16594. return serializationObject;
  16595. };
  16596. var serializeTorus = function (torus) {
  16597. var serializationObject = serializePrimitive(torus);
  16598. serializationObject.diameter = torus.diameter;
  16599. serializationObject.thickness = torus.thickness;
  16600. serializationObject.tessellation = torus.tessellation;
  16601. return serializationObject;
  16602. };
  16603. var serializeGround = function (ground) {
  16604. var serializationObject = serializePrimitive(ground);
  16605. serializationObject.width = ground.width;
  16606. serializationObject.height = ground.height;
  16607. serializationObject.subdivisions = ground.subdivisions;
  16608. return serializationObject;
  16609. };
  16610. var serializePlane = function (plane) {
  16611. var serializationObject = serializePrimitive(plane);
  16612. serializationObject.size = plane.size;
  16613. return serializationObject;
  16614. };
  16615. var serializeTorusKnot = function (torusKnot) {
  16616. var serializationObject = serializePrimitive(torusKnot);
  16617. serializationObject.radius = torusKnot.radius;
  16618. serializationObject.tube = torusKnot.tube;
  16619. serializationObject.radialSegments = torusKnot.radialSegments;
  16620. serializationObject.tubularSegments = torusKnot.tubularSegments;
  16621. serializationObject.p = torusKnot.p;
  16622. serializationObject.q = torusKnot.q;
  16623. return serializationObject;
  16624. };
  16625. var serializeMesh = function (mesh, serializationScene) {
  16626. var serializationObject = {};
  16627. serializationObject.name = mesh.name;
  16628. serializationObject.id = mesh.id;
  16629. if (BABYLON.Tags.HasTags(mesh)) {
  16630. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  16631. }
  16632. serializationObject.position = mesh.position.asArray();
  16633. if (mesh.rotationQuaternion) {
  16634. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  16635. } else if (mesh.rotation) {
  16636. serializationObject.rotation = mesh.rotation.asArray();
  16637. }
  16638. serializationObject.scaling = mesh.scaling.asArray();
  16639. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  16640. serializationObject.isEnabled = mesh.isEnabled();
  16641. serializationObject.isVisible = mesh.isVisible;
  16642. serializationObject.infiniteDistance = mesh.infiniteDistance;
  16643. serializationObject.pickable = mesh.isPickable;
  16644. serializationObject.receiveShadows = mesh.receiveShadows;
  16645. serializationObject.billboardMode = mesh.billboardMode;
  16646. serializationObject.visibility = mesh.visibility;
  16647. serializationObject.checkCollisions = mesh.checkCollisions;
  16648. // Parent
  16649. if (mesh.parent) {
  16650. serializationObject.parentId = mesh.parent.id;
  16651. }
  16652. // Geometry
  16653. var geometry = mesh._geometry;
  16654. if (geometry) {
  16655. var geometryId = geometry.id;
  16656. serializationObject.geometryId = geometryId;
  16657. if (!mesh.getScene().getGeometryByID(geometryId)) {
  16658. // 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
  16659. serializeGeometry(geometry, serializationScene.geometries);
  16660. }
  16661. // SubMeshes
  16662. serializationObject.subMeshes = [];
  16663. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  16664. var subMesh = mesh.subMeshes[subIndex];
  16665. serializationObject.subMeshes.push({
  16666. materialIndex: subMesh.materialIndex,
  16667. verticesStart: subMesh.verticesStart,
  16668. verticesCount: subMesh.verticesCount,
  16669. indexStart: subMesh.indexStart,
  16670. indexCount: subMesh.indexCount
  16671. });
  16672. }
  16673. }
  16674. // Material
  16675. if (mesh.material) {
  16676. serializationObject.materialId = mesh.material.id;
  16677. } else {
  16678. mesh.material = null;
  16679. }
  16680. // Skeleton
  16681. if (mesh.skeleton) {
  16682. serializationObject.skeletonId = mesh.skeleton.id;
  16683. }
  16684. // Physics
  16685. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  16686. serializationObject.physicsMass = mesh.getPhysicsMass();
  16687. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  16688. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  16689. switch (mesh.getPhysicsImpostor()) {
  16690. case BABYLON.PhysicsEngine.BoxImpostor:
  16691. serializationObject.physicsImpostor = 1;
  16692. break;
  16693. case BABYLON.PhysicsEngine.SphereImpostor:
  16694. serializationObject.physicsImpostor = 2;
  16695. break;
  16696. }
  16697. }
  16698. // Instances
  16699. serializationObject.instances = [];
  16700. for (var index = 0; index < mesh.instances.length; index++) {
  16701. var instance = mesh.instances[index];
  16702. var serializationInstance = {
  16703. name: instance.name,
  16704. position: instance.position,
  16705. rotation: instance.rotation,
  16706. rotationQuaternion: instance.rotationQuaternion,
  16707. scaling: instance.scaling
  16708. };
  16709. serializationObject.instances.push(serializationInstance);
  16710. // Animations
  16711. appendAnimations(instance, serializationInstance);
  16712. }
  16713. // Animations
  16714. appendAnimations(mesh, serializationObject);
  16715. // Layer mask
  16716. serializationObject.layerMask = mesh.layerMask;
  16717. return serializationObject;
  16718. };
  16719. var SceneSerializer = (function () {
  16720. function SceneSerializer() {
  16721. }
  16722. SceneSerializer.Serialize = function (scene) {
  16723. var serializationObject = {};
  16724. // Scene
  16725. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  16726. serializationObject.autoClear = scene.autoClear;
  16727. serializationObject.clearColor = scene.clearColor.asArray();
  16728. serializationObject.ambientColor = scene.ambientColor.asArray();
  16729. serializationObject.gravity = scene.gravity.asArray();
  16730. // Fog
  16731. if (scene.fogMode && scene.fogMode !== 0) {
  16732. serializationObject.fogMode = scene.fogMode;
  16733. serializationObject.fogColor = scene.fogColor.asArray();
  16734. serializationObject.fogStart = scene.fogStart;
  16735. serializationObject.fogEnd = scene.fogEnd;
  16736. serializationObject.fogDensity = scene.fogDensity;
  16737. }
  16738. // Lights
  16739. serializationObject.lights = [];
  16740. for (var index = 0; index < scene.lights.length; index++) {
  16741. var light = scene.lights[index];
  16742. serializationObject.lights.push(serializeLight(light));
  16743. }
  16744. // Cameras
  16745. serializationObject.cameras = [];
  16746. for (index = 0; index < scene.cameras.length; index++) {
  16747. var camera = scene.cameras[index];
  16748. if (camera instanceof BABYLON.FreeCamera) {
  16749. serializationObject.cameras.push(serializeCamera(camera));
  16750. }
  16751. }
  16752. if (scene.activeCamera) {
  16753. serializationObject.activeCameraID = scene.activeCamera.id;
  16754. }
  16755. // Materials
  16756. serializationObject.materials = [];
  16757. serializationObject.multiMaterials = [];
  16758. for (index = 0; index < scene.materials.length; index++) {
  16759. var material = scene.materials[index];
  16760. if (material instanceof BABYLON.StandardMaterial) {
  16761. serializationObject.materials.push(serializeMaterial(material));
  16762. } else if (material instanceof BABYLON.MultiMaterial) {
  16763. serializationObject.multiMaterials.push(serializeMultiMaterial(material));
  16764. }
  16765. }
  16766. // Skeletons
  16767. serializationObject.skeletons = [];
  16768. for (index = 0; index < scene.skeletons.length; index++) {
  16769. serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
  16770. }
  16771. // Geometries
  16772. serializationObject.geometries = {};
  16773. serializationObject.geometries.boxes = [];
  16774. serializationObject.geometries.spheres = [];
  16775. serializationObject.geometries.cylinders = [];
  16776. serializationObject.geometries.toruses = [];
  16777. serializationObject.geometries.grounds = [];
  16778. serializationObject.geometries.planes = [];
  16779. serializationObject.geometries.torusKnots = [];
  16780. serializationObject.geometries.vertexData = [];
  16781. serializedGeometries = [];
  16782. var geometries = scene.getGeometries();
  16783. for (var index = 0; index < geometries.length; index++) {
  16784. var geometry = geometries[index];
  16785. if (geometry.isReady()) {
  16786. serializeGeometry(geometry, serializationObject.geometries);
  16787. }
  16788. }
  16789. // Meshes
  16790. serializationObject.meshes = [];
  16791. for (index = 0; index < scene.meshes.length; index++) {
  16792. var abstractMesh = scene.meshes[index];
  16793. if (abstractMesh instanceof BABYLON.Mesh) {
  16794. var mesh = abstractMesh;
  16795. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  16796. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  16797. }
  16798. }
  16799. }
  16800. // Particles Systems
  16801. serializationObject.particleSystems = [];
  16802. for (index = 0; index < scene.particleSystems.length; index++) {
  16803. serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
  16804. }
  16805. // Lens flares
  16806. serializationObject.lensFlareSystems = [];
  16807. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  16808. serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
  16809. }
  16810. // Shadows
  16811. serializationObject.shadowGenerators = [];
  16812. for (index = 0; index < scene.lights.length; index++) {
  16813. light = scene.lights[index];
  16814. if (light.getShadowGenerator()) {
  16815. serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
  16816. }
  16817. }
  16818. return serializationObject;
  16819. };
  16820. return SceneSerializer;
  16821. })();
  16822. BABYLON.SceneSerializer = SceneSerializer;
  16823. })(BABYLON || (BABYLON = {}));
  16824. //# sourceMappingURL=babylon.sceneSerializer.js.map
  16825. var BABYLON;
  16826. (function (BABYLON) {
  16827. var SceneLoader = (function () {
  16828. function SceneLoader() {
  16829. }
  16830. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  16831. get: function () {
  16832. return SceneLoader._ForceFullSceneLoadingForIncremental;
  16833. },
  16834. set: function (value) {
  16835. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  16836. },
  16837. enumerable: true,
  16838. configurable: true
  16839. });
  16840. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  16841. get: function () {
  16842. return SceneLoader._ShowLoadingScreen;
  16843. },
  16844. set: function (value) {
  16845. SceneLoader._ShowLoadingScreen = value;
  16846. },
  16847. enumerable: true,
  16848. configurable: true
  16849. });
  16850. SceneLoader._getPluginForFilename = function (sceneFilename) {
  16851. var dotPosition = sceneFilename.lastIndexOf(".");
  16852. var queryStringPosition = sceneFilename.indexOf("?");
  16853. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  16854. for (var index = 0; index < this._registeredPlugins.length; index++) {
  16855. var plugin = this._registeredPlugins[index];
  16856. if (plugin.extensions.indexOf(extension) !== -1) {
  16857. return plugin;
  16858. }
  16859. }
  16860. return this._registeredPlugins[this._registeredPlugins.length - 1];
  16861. };
  16862. // Public functions
  16863. SceneLoader.RegisterPlugin = function (plugin) {
  16864. plugin.extensions = plugin.extensions.toLowerCase();
  16865. SceneLoader._registeredPlugins.push(plugin);
  16866. };
  16867. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  16868. var manifestChecked = function (success) {
  16869. scene.database = database;
  16870. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  16871. var importMeshFromData = function (data) {
  16872. var meshes = [];
  16873. var particleSystems = [];
  16874. var skeletons = [];
  16875. try {
  16876. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  16877. if (onerror) {
  16878. onerror(scene, 'unable to load the scene');
  16879. }
  16880. return;
  16881. }
  16882. } catch (e) {
  16883. if (onerror) {
  16884. onerror(scene, e);
  16885. }
  16886. return;
  16887. }
  16888. if (onsuccess) {
  16889. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  16890. onsuccess(meshes, particleSystems, skeletons);
  16891. }
  16892. };
  16893. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  16894. // Direct load
  16895. importMeshFromData(sceneFilename.substr(5));
  16896. return;
  16897. }
  16898. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  16899. importMeshFromData(data);
  16900. }, progressCallBack, database);
  16901. };
  16902. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  16903. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  16904. };
  16905. /**
  16906. * Load a scene
  16907. * @param rootUrl a string that defines the root url for scene and resources
  16908. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  16909. * @param engine is the instance of BABYLON.Engine to use to create the scene
  16910. */
  16911. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  16912. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  16913. };
  16914. /**
  16915. * Append a scene
  16916. * @param rootUrl a string that defines the root url for scene and resources
  16917. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  16918. * @param scene is the instance of BABYLON.Scene to append to
  16919. */
  16920. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  16921. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  16922. var database;
  16923. if (SceneLoader.ShowLoadingScreen) {
  16924. scene.getEngine().displayLoadingUI();
  16925. }
  16926. var loadSceneFromData = function (data) {
  16927. scene.database = database;
  16928. if (!plugin.load(scene, data, rootUrl)) {
  16929. if (onerror) {
  16930. onerror(scene);
  16931. }
  16932. scene.getEngine().hideLoadingUI();
  16933. return;
  16934. }
  16935. if (onsuccess) {
  16936. onsuccess(scene);
  16937. }
  16938. if (SceneLoader.ShowLoadingScreen) {
  16939. scene.executeWhenReady(function () {
  16940. scene.getEngine().hideLoadingUI();
  16941. });
  16942. }
  16943. };
  16944. var manifestChecked = function (success) {
  16945. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  16946. };
  16947. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  16948. // Direct load
  16949. loadSceneFromData(sceneFilename.substr(5));
  16950. return;
  16951. }
  16952. if (rootUrl.indexOf("file:") === -1) {
  16953. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  16954. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  16955. } else {
  16956. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  16957. }
  16958. };
  16959. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  16960. SceneLoader._ShowLoadingScreen = true;
  16961. SceneLoader._registeredPlugins = new Array();
  16962. return SceneLoader;
  16963. })();
  16964. BABYLON.SceneLoader = SceneLoader;
  16965. ;
  16966. })(BABYLON || (BABYLON = {}));
  16967. //# sourceMappingURL=babylon.sceneLoader.js.map
  16968. var BABYLON;
  16969. (function (BABYLON) {
  16970. (function (Internals) {
  16971. var checkColors4 = function (colors, count) {
  16972. // Check if color3 was used
  16973. if (colors.length === count * 3) {
  16974. var colors4 = [];
  16975. for (var index = 0; index < colors.length; index += 3) {
  16976. var newIndex = (index / 3) * 4;
  16977. colors4[newIndex] = colors[index];
  16978. colors4[newIndex + 1] = colors[index + 1];
  16979. colors4[newIndex + 2] = colors[index + 2];
  16980. colors4[newIndex + 3] = 1.0;
  16981. }
  16982. return colors4;
  16983. }
  16984. return colors;
  16985. };
  16986. var loadCubeTexture = function (rootUrl, parsedTexture, scene) {
  16987. var texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene);
  16988. texture.name = parsedTexture.name;
  16989. texture.hasAlpha = parsedTexture.hasAlpha;
  16990. texture.level = parsedTexture.level;
  16991. texture.coordinatesMode = parsedTexture.coordinatesMode;
  16992. return texture;
  16993. };
  16994. var loadTexture = function (rootUrl, parsedTexture, scene) {
  16995. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  16996. return null;
  16997. }
  16998. if (parsedTexture.isCube) {
  16999. return loadCubeTexture(rootUrl, parsedTexture, scene);
  17000. }
  17001. var texture;
  17002. if (parsedTexture.mirrorPlane) {
  17003. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  17004. texture._waitingRenderList = parsedTexture.renderList;
  17005. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  17006. } else if (parsedTexture.isRenderTarget) {
  17007. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  17008. texture._waitingRenderList = parsedTexture.renderList;
  17009. } else {
  17010. texture = new BABYLON.Texture(rootUrl + parsedTexture.name, scene);
  17011. }
  17012. texture.name = parsedTexture.name;
  17013. texture.hasAlpha = parsedTexture.hasAlpha;
  17014. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  17015. texture.level = parsedTexture.level;
  17016. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  17017. texture.coordinatesMode = parsedTexture.coordinatesMode;
  17018. texture.uOffset = parsedTexture.uOffset;
  17019. texture.vOffset = parsedTexture.vOffset;
  17020. texture.uScale = parsedTexture.uScale;
  17021. texture.vScale = parsedTexture.vScale;
  17022. texture.uAng = parsedTexture.uAng;
  17023. texture.vAng = parsedTexture.vAng;
  17024. texture.wAng = parsedTexture.wAng;
  17025. texture.wrapU = parsedTexture.wrapU;
  17026. texture.wrapV = parsedTexture.wrapV;
  17027. // Animations
  17028. if (parsedTexture.animations) {
  17029. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  17030. var parsedAnimation = parsedTexture.animations[animationIndex];
  17031. texture.animations.push(parseAnimation(parsedAnimation));
  17032. }
  17033. }
  17034. return texture;
  17035. };
  17036. var parseSkeleton = function (parsedSkeleton, scene) {
  17037. var skeleton = new BABYLON.Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  17038. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  17039. var parsedBone = parsedSkeleton.bones[index];
  17040. var parentBone = null;
  17041. if (parsedBone.parentBoneIndex > -1) {
  17042. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  17043. }
  17044. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  17045. if (parsedBone.animation) {
  17046. bone.animations.push(parseAnimation(parsedBone.animation));
  17047. }
  17048. }
  17049. return skeleton;
  17050. };
  17051. var parseFresnelParameters = function (parsedFresnelParameters) {
  17052. var fresnelParameters = new BABYLON.FresnelParameters();
  17053. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  17054. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  17055. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  17056. fresnelParameters.bias = parsedFresnelParameters.bias;
  17057. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  17058. return fresnelParameters;
  17059. };
  17060. var parseMaterial = function (parsedMaterial, scene, rootUrl) {
  17061. var material;
  17062. material = new BABYLON.StandardMaterial(parsedMaterial.name, scene);
  17063. material.ambientColor = BABYLON.Color3.FromArray(parsedMaterial.ambient);
  17064. material.diffuseColor = BABYLON.Color3.FromArray(parsedMaterial.diffuse);
  17065. material.specularColor = BABYLON.Color3.FromArray(parsedMaterial.specular);
  17066. material.specularPower = parsedMaterial.specularPower;
  17067. material.emissiveColor = BABYLON.Color3.FromArray(parsedMaterial.emissive);
  17068. material.alpha = parsedMaterial.alpha;
  17069. material.id = parsedMaterial.id;
  17070. BABYLON.Tags.AddTagsTo(material, parsedMaterial.tags);
  17071. material.backFaceCulling = parsedMaterial.backFaceCulling;
  17072. material.wireframe = parsedMaterial.wireframe;
  17073. if (parsedMaterial.diffuseTexture) {
  17074. material.diffuseTexture = loadTexture(rootUrl, parsedMaterial.diffuseTexture, scene);
  17075. }
  17076. if (parsedMaterial.diffuseFresnelParameters) {
  17077. material.diffuseFresnelParameters = parseFresnelParameters(parsedMaterial.diffuseFresnelParameters);
  17078. }
  17079. if (parsedMaterial.ambientTexture) {
  17080. material.ambientTexture = loadTexture(rootUrl, parsedMaterial.ambientTexture, scene);
  17081. }
  17082. if (parsedMaterial.opacityTexture) {
  17083. material.opacityTexture = loadTexture(rootUrl, parsedMaterial.opacityTexture, scene);
  17084. }
  17085. if (parsedMaterial.opacityFresnelParameters) {
  17086. material.opacityFresnelParameters = parseFresnelParameters(parsedMaterial.opacityFresnelParameters);
  17087. }
  17088. if (parsedMaterial.reflectionTexture) {
  17089. material.reflectionTexture = loadTexture(rootUrl, parsedMaterial.reflectionTexture, scene);
  17090. }
  17091. if (parsedMaterial.reflectionFresnelParameters) {
  17092. material.reflectionFresnelParameters = parseFresnelParameters(parsedMaterial.reflectionFresnelParameters);
  17093. }
  17094. if (parsedMaterial.emissiveTexture) {
  17095. material.emissiveTexture = loadTexture(rootUrl, parsedMaterial.emissiveTexture, scene);
  17096. }
  17097. if (parsedMaterial.emissiveFresnelParameters) {
  17098. material.emissiveFresnelParameters = parseFresnelParameters(parsedMaterial.emissiveFresnelParameters);
  17099. }
  17100. if (parsedMaterial.specularTexture) {
  17101. material.specularTexture = loadTexture(rootUrl, parsedMaterial.specularTexture, scene);
  17102. }
  17103. if (parsedMaterial.bumpTexture) {
  17104. material.bumpTexture = loadTexture(rootUrl, parsedMaterial.bumpTexture, scene);
  17105. }
  17106. return material;
  17107. };
  17108. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  17109. for (var index = 0; index < parsedData.materials.length; index++) {
  17110. var parsedMaterial = parsedData.materials[index];
  17111. if (parsedMaterial.id === id) {
  17112. return parseMaterial(parsedMaterial, scene, rootUrl);
  17113. }
  17114. }
  17115. return null;
  17116. };
  17117. var parseMultiMaterial = function (parsedMultiMaterial, scene) {
  17118. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  17119. multiMaterial.id = parsedMultiMaterial.id;
  17120. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  17121. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  17122. var subMatId = parsedMultiMaterial.materials[matIndex];
  17123. if (subMatId) {
  17124. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  17125. } else {
  17126. multiMaterial.subMaterials.push(null);
  17127. }
  17128. }
  17129. return multiMaterial;
  17130. };
  17131. var parseLensFlareSystem = function (parsedLensFlareSystem, scene, rootUrl) {
  17132. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  17133. var lensFlareSystem = new BABYLON.LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  17134. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  17135. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  17136. var parsedFlare = parsedLensFlareSystem.flares[index];
  17137. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  17138. }
  17139. return lensFlareSystem;
  17140. };
  17141. var parseParticleSystem = function (parsedParticleSystem, scene, rootUrl) {
  17142. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  17143. var particleSystem = new BABYLON.ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  17144. if (parsedParticleSystem.textureName) {
  17145. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  17146. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  17147. }
  17148. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  17149. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  17150. particleSystem.minSize = parsedParticleSystem.minSize;
  17151. particleSystem.maxSize = parsedParticleSystem.maxSize;
  17152. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  17153. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  17154. particleSystem.emitter = emitter;
  17155. particleSystem.emitRate = parsedParticleSystem.emitRate;
  17156. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  17157. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  17158. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  17159. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  17160. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  17161. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  17162. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  17163. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  17164. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  17165. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  17166. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  17167. particleSystem.blendMode = parsedParticleSystem.blendMode;
  17168. particleSystem.start();
  17169. return particleSystem;
  17170. };
  17171. var parseShadowGenerator = function (parsedShadowGenerator, scene) {
  17172. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  17173. var shadowGenerator = new BABYLON.ShadowGenerator(parsedShadowGenerator.mapSize, light);
  17174. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  17175. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  17176. shadowGenerator.getShadowMap().renderList.push(mesh);
  17177. }
  17178. if (parsedShadowGenerator.usePoissonSampling) {
  17179. shadowGenerator.usePoissonSampling = true;
  17180. } else {
  17181. shadowGenerator.useVarianceShadowMap = parsedShadowGenerator.useVarianceShadowMap;
  17182. }
  17183. return shadowGenerator;
  17184. };
  17185. var parseAnimation = function (parsedAnimation) {
  17186. var animation = new BABYLON.Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  17187. var dataType = parsedAnimation.dataType;
  17188. var keys = [];
  17189. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  17190. var key = parsedAnimation.keys[index];
  17191. var data;
  17192. switch (dataType) {
  17193. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  17194. data = key.values[0];
  17195. break;
  17196. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  17197. data = BABYLON.Quaternion.FromArray(key.values);
  17198. break;
  17199. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  17200. data = BABYLON.Matrix.FromArray(key.values);
  17201. break;
  17202. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  17203. default:
  17204. data = BABYLON.Vector3.FromArray(key.values);
  17205. break;
  17206. }
  17207. keys.push({
  17208. frame: key.frame,
  17209. value: data
  17210. });
  17211. }
  17212. animation.setKeys(keys);
  17213. return animation;
  17214. };
  17215. var parseLight = function (parsedLight, scene) {
  17216. var light;
  17217. switch (parsedLight.type) {
  17218. case 0:
  17219. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  17220. break;
  17221. case 1:
  17222. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  17223. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  17224. break;
  17225. case 2:
  17226. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  17227. break;
  17228. case 3:
  17229. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  17230. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  17231. break;
  17232. }
  17233. light.id = parsedLight.id;
  17234. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  17235. if (parsedLight.intensity !== undefined) {
  17236. light.intensity = parsedLight.intensity;
  17237. }
  17238. if (parsedLight.range) {
  17239. light.range = parsedLight.range;
  17240. }
  17241. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  17242. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  17243. if (parsedLight.excludedMeshesIds) {
  17244. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  17245. }
  17246. // Parent
  17247. if (parsedLight.parentId) {
  17248. light._waitingParentId = parsedLight.parentId;
  17249. }
  17250. if (parsedLight.includedOnlyMeshesIds) {
  17251. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  17252. }
  17253. // Animations
  17254. if (parsedLight.animations) {
  17255. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  17256. var parsedAnimation = parsedLight.animations[animationIndex];
  17257. light.animations.push(parseAnimation(parsedAnimation));
  17258. }
  17259. }
  17260. if (parsedLight.autoAnimate) {
  17261. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  17262. }
  17263. };
  17264. var parseCamera = function (parsedCamera, scene) {
  17265. var camera;
  17266. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  17267. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  17268. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  17269. var alpha = parsedCamera.alpha;
  17270. var beta = parsedCamera.beta;
  17271. var radius = parsedCamera.radius;
  17272. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  17273. var eye_space = parsedCamera.eye_space;
  17274. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, eye_space, scene);
  17275. } else {
  17276. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  17277. }
  17278. } else if (parsedCamera.type === "AnaglyphFreeCamera") {
  17279. var eye_space = parsedCamera.eye_space;
  17280. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, eye_space, scene);
  17281. } else if (parsedCamera.type === "DeviceOrientationCamera") {
  17282. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  17283. } else if (parsedCamera.type === "FollowCamera") {
  17284. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  17285. camera.heightOffset = parsedCamera.heightOffset;
  17286. camera.radius = parsedCamera.radius;
  17287. camera.rotationOffset = parsedCamera.rotationOffset;
  17288. if (lockedTargetMesh)
  17289. camera.target = lockedTargetMesh;
  17290. } else if (parsedCamera.type === "GamepadCamera") {
  17291. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  17292. } else if (parsedCamera.type === "OculusCamera") {
  17293. camera = new BABYLON.OculusCamera(parsedCamera.name, position, scene);
  17294. } else if (parsedCamera.type === "OculusGamepadCamera") {
  17295. camera = new BABYLON.OculusGamepadCamera(parsedCamera.name, position, scene);
  17296. } else if (parsedCamera.type === "TouchCamera") {
  17297. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  17298. } else if (parsedCamera.type === "VirtualJoysticksCamera") {
  17299. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  17300. } else if (parsedCamera.type === "WebVRCamera") {
  17301. camera = new BABYLON.WebVRCamera(parsedCamera.name, position, scene);
  17302. } else if (parsedCamera.type === "VRDeviceOrientationCamera") {
  17303. camera = new BABYLON.VRDeviceOrientationCamera(parsedCamera.name, position, scene);
  17304. } else {
  17305. // Free Camera is the default value
  17306. camera = new BABYLON.FreeCamera(parsedCamera.name, position, scene);
  17307. }
  17308. // Test for lockedTargetMesh & FreeCamera outside of if-else-if nest, since things like GamepadCamera extend FreeCamera
  17309. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  17310. camera.lockedTarget = lockedTargetMesh;
  17311. }
  17312. camera.id = parsedCamera.id;
  17313. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  17314. // Parent
  17315. if (parsedCamera.parentId) {
  17316. camera._waitingParentId = parsedCamera.parentId;
  17317. }
  17318. // Target
  17319. if (parsedCamera.target) {
  17320. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  17321. } else {
  17322. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  17323. }
  17324. camera.fov = parsedCamera.fov;
  17325. camera.minZ = parsedCamera.minZ;
  17326. camera.maxZ = parsedCamera.maxZ;
  17327. camera.speed = parsedCamera.speed;
  17328. camera.inertia = parsedCamera.inertia;
  17329. camera.checkCollisions = parsedCamera.checkCollisions;
  17330. camera.applyGravity = parsedCamera.applyGravity;
  17331. if (parsedCamera.ellipsoid) {
  17332. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  17333. }
  17334. // Animations
  17335. if (parsedCamera.animations) {
  17336. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  17337. var parsedAnimation = parsedCamera.animations[animationIndex];
  17338. camera.animations.push(parseAnimation(parsedAnimation));
  17339. }
  17340. }
  17341. if (parsedCamera.autoAnimate) {
  17342. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  17343. }
  17344. // Layer Mask
  17345. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  17346. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  17347. } else {
  17348. camera.layerMask = 0xFFFFFFFF;
  17349. }
  17350. return camera;
  17351. };
  17352. var parseGeometry = function (parsedGeometry, scene) {
  17353. var id = parsedGeometry.id;
  17354. return scene.getGeometryByID(id);
  17355. };
  17356. var parseBox = function (parsedBox, scene) {
  17357. if (parseGeometry(parsedBox, scene)) {
  17358. return null;
  17359. }
  17360. var box = new BABYLON.Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  17361. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  17362. scene.pushGeometry(box, true);
  17363. return box;
  17364. };
  17365. var parseSphere = function (parsedSphere, scene) {
  17366. if (parseGeometry(parsedSphere, scene)) {
  17367. return null;
  17368. }
  17369. var sphere = new BABYLON.Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  17370. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  17371. scene.pushGeometry(sphere, true);
  17372. return sphere;
  17373. };
  17374. var parseCylinder = function (parsedCylinder, scene) {
  17375. if (parseGeometry(parsedCylinder, scene)) {
  17376. return null;
  17377. }
  17378. var cylinder = new BABYLON.Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  17379. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  17380. scene.pushGeometry(cylinder, true);
  17381. return cylinder;
  17382. };
  17383. var parseTorus = function (parsedTorus, scene) {
  17384. if (parseGeometry(parsedTorus, scene)) {
  17385. return null;
  17386. }
  17387. var torus = new BABYLON.Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  17388. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  17389. scene.pushGeometry(torus, true);
  17390. return torus;
  17391. };
  17392. var parseGround = function (parsedGround, scene) {
  17393. if (parseGeometry(parsedGround, scene)) {
  17394. return null;
  17395. }
  17396. var ground = new BABYLON.Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  17397. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  17398. scene.pushGeometry(ground, true);
  17399. return ground;
  17400. };
  17401. var parsePlane = function (parsedPlane, scene) {
  17402. if (parseGeometry(parsedPlane, scene)) {
  17403. return null;
  17404. }
  17405. var plane = new BABYLON.Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  17406. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  17407. scene.pushGeometry(plane, true);
  17408. return plane;
  17409. };
  17410. var parseTorusKnot = function (parsedTorusKnot, scene) {
  17411. if (parseGeometry(parsedTorusKnot, scene)) {
  17412. return null;
  17413. }
  17414. 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);
  17415. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  17416. scene.pushGeometry(torusKnot, true);
  17417. return torusKnot;
  17418. };
  17419. var parseVertexData = function (parsedVertexData, scene, rootUrl) {
  17420. if (parseGeometry(parsedVertexData, scene)) {
  17421. return null;
  17422. }
  17423. var geometry = new BABYLON.Geometry(parsedVertexData.id, scene);
  17424. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  17425. if (parsedVertexData.delayLoadingFile) {
  17426. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  17427. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  17428. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  17429. geometry._delayInfo = [];
  17430. if (parsedVertexData.hasUVs) {
  17431. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  17432. }
  17433. if (parsedVertexData.hasUVs2) {
  17434. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  17435. }
  17436. if (parsedVertexData.hasColors) {
  17437. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  17438. }
  17439. if (parsedVertexData.hasMatricesIndices) {
  17440. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  17441. }
  17442. if (parsedVertexData.hasMatricesWeights) {
  17443. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  17444. }
  17445. geometry._delayLoadingFunction = importVertexData;
  17446. } else {
  17447. importVertexData(parsedVertexData, geometry);
  17448. }
  17449. scene.pushGeometry(geometry, true);
  17450. return geometry;
  17451. };
  17452. var parseMesh = function (parsedMesh, scene, rootUrl) {
  17453. var mesh = new BABYLON.Mesh(parsedMesh.name, scene);
  17454. mesh.id = parsedMesh.id;
  17455. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  17456. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  17457. if (parsedMesh.rotationQuaternion) {
  17458. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  17459. } else if (parsedMesh.rotation) {
  17460. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  17461. }
  17462. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  17463. if (parsedMesh.localMatrix) {
  17464. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  17465. } else if (parsedMesh.pivotMatrix) {
  17466. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  17467. }
  17468. mesh.setEnabled(parsedMesh.isEnabled);
  17469. mesh.isVisible = parsedMesh.isVisible;
  17470. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  17471. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  17472. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  17473. if (parsedMesh.applyFog !== undefined) {
  17474. mesh.applyFog = parsedMesh.applyFog;
  17475. }
  17476. if (parsedMesh.pickable !== undefined) {
  17477. mesh.isPickable = parsedMesh.pickable;
  17478. }
  17479. if (parsedMesh.alphaIndex !== undefined) {
  17480. mesh.alphaIndex = parsedMesh.alphaIndex;
  17481. }
  17482. mesh.receiveShadows = parsedMesh.receiveShadows;
  17483. mesh.billboardMode = parsedMesh.billboardMode;
  17484. if (parsedMesh.visibility !== undefined) {
  17485. mesh.visibility = parsedMesh.visibility;
  17486. }
  17487. mesh.checkCollisions = parsedMesh.checkCollisions;
  17488. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  17489. // Parent
  17490. if (parsedMesh.parentId) {
  17491. mesh._waitingParentId = parsedMesh.parentId;
  17492. }
  17493. // Geometry
  17494. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  17495. if (parsedMesh.delayLoadingFile) {
  17496. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  17497. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  17498. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  17499. if (parsedMesh._binaryInfo) {
  17500. mesh._binaryInfo = parsedMesh._binaryInfo;
  17501. }
  17502. mesh._delayInfo = [];
  17503. if (parsedMesh.hasUVs) {
  17504. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  17505. }
  17506. if (parsedMesh.hasUVs2) {
  17507. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  17508. }
  17509. if (parsedMesh.hasColors) {
  17510. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  17511. }
  17512. if (parsedMesh.hasMatricesIndices) {
  17513. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  17514. }
  17515. if (parsedMesh.hasMatricesWeights) {
  17516. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  17517. }
  17518. mesh._delayLoadingFunction = importGeometry;
  17519. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  17520. mesh._checkDelayState();
  17521. }
  17522. } else {
  17523. importGeometry(parsedMesh, mesh);
  17524. }
  17525. // Material
  17526. if (parsedMesh.materialId) {
  17527. mesh.setMaterialByID(parsedMesh.materialId);
  17528. } else {
  17529. mesh.material = null;
  17530. }
  17531. // Skeleton
  17532. if (parsedMesh.skeletonId > -1) {
  17533. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  17534. }
  17535. // Physics
  17536. if (parsedMesh.physicsImpostor) {
  17537. if (!scene.isPhysicsEnabled()) {
  17538. scene.enablePhysics();
  17539. }
  17540. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  17541. }
  17542. // Animations
  17543. if (parsedMesh.animations) {
  17544. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  17545. var parsedAnimation = parsedMesh.animations[animationIndex];
  17546. mesh.animations.push(parseAnimation(parsedAnimation));
  17547. }
  17548. }
  17549. if (parsedMesh.autoAnimate) {
  17550. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  17551. }
  17552. // Layer Mask
  17553. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  17554. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  17555. } else {
  17556. mesh.layerMask = 0xFFFFFFFF;
  17557. }
  17558. // Instances
  17559. if (parsedMesh.instances) {
  17560. for (var index = 0; index < parsedMesh.instances.length; index++) {
  17561. var parsedInstance = parsedMesh.instances[index];
  17562. var instance = mesh.createInstance(parsedInstance.name);
  17563. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  17564. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  17565. if (parsedInstance.rotationQuaternion) {
  17566. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  17567. } else if (parsedInstance.rotation) {
  17568. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  17569. }
  17570. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  17571. instance.checkCollisions = mesh.checkCollisions;
  17572. if (parsedMesh.animations) {
  17573. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  17574. parsedAnimation = parsedMesh.animations[animationIndex];
  17575. instance.animations.push(parseAnimation(parsedAnimation));
  17576. }
  17577. }
  17578. }
  17579. }
  17580. return mesh;
  17581. };
  17582. var isDescendantOf = function (mesh, names, hierarchyIds) {
  17583. names = (names instanceof Array) ? names : [names];
  17584. for (var i in names) {
  17585. if (mesh.name === names[i]) {
  17586. hierarchyIds.push(mesh.id);
  17587. return true;
  17588. }
  17589. }
  17590. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  17591. hierarchyIds.push(mesh.id);
  17592. return true;
  17593. }
  17594. return false;
  17595. };
  17596. var importVertexData = function (parsedVertexData, geometry) {
  17597. var vertexData = new BABYLON.VertexData();
  17598. // positions
  17599. var positions = parsedVertexData.positions;
  17600. if (positions) {
  17601. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  17602. }
  17603. // normals
  17604. var normals = parsedVertexData.normals;
  17605. if (normals) {
  17606. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  17607. }
  17608. // uvs
  17609. var uvs = parsedVertexData.uvs;
  17610. if (uvs) {
  17611. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  17612. }
  17613. // uv2s
  17614. var uv2s = parsedVertexData.uv2s;
  17615. if (uv2s) {
  17616. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  17617. }
  17618. // colors
  17619. var colors = parsedVertexData.colors;
  17620. if (colors) {
  17621. vertexData.set(checkColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  17622. }
  17623. // matricesIndices
  17624. var matricesIndices = parsedVertexData.matricesIndices;
  17625. if (matricesIndices) {
  17626. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  17627. }
  17628. // matricesWeights
  17629. var matricesWeights = parsedVertexData.matricesWeights;
  17630. if (matricesWeights) {
  17631. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  17632. }
  17633. // indices
  17634. var indices = parsedVertexData.indices;
  17635. if (indices) {
  17636. vertexData.indices = indices;
  17637. }
  17638. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  17639. };
  17640. var importGeometry = function (parsedGeometry, mesh) {
  17641. var scene = mesh.getScene();
  17642. // Geometry
  17643. var geometryId = parsedGeometry.geometryId;
  17644. if (geometryId) {
  17645. var geometry = scene.getGeometryByID(geometryId);
  17646. if (geometry) {
  17647. geometry.applyToMesh(mesh);
  17648. }
  17649. } else if (parsedGeometry instanceof ArrayBuffer) {
  17650. var binaryInfo = mesh._binaryInfo;
  17651. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  17652. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  17653. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  17654. }
  17655. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  17656. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  17657. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  17658. }
  17659. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  17660. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  17661. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  17662. }
  17663. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  17664. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  17665. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  17666. }
  17667. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  17668. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  17669. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false);
  17670. }
  17671. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  17672. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  17673. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  17674. }
  17675. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  17676. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  17677. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  17678. }
  17679. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  17680. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  17681. mesh.setIndices(indicesData);
  17682. }
  17683. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  17684. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  17685. mesh.subMeshes = [];
  17686. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  17687. var materialIndex = subMeshesData[(i * 5) + 0];
  17688. var verticesStart = subMeshesData[(i * 5) + 1];
  17689. var verticesCount = subMeshesData[(i * 5) + 2];
  17690. var indexStart = subMeshesData[(i * 5) + 3];
  17691. var indexCount = subMeshesData[(i * 5) + 4];
  17692. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  17693. }
  17694. }
  17695. } else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  17696. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  17697. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  17698. if (parsedGeometry.uvs) {
  17699. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  17700. }
  17701. if (parsedGeometry.uvs2) {
  17702. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  17703. }
  17704. if (parsedGeometry.colors) {
  17705. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, checkColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  17706. }
  17707. if (parsedGeometry.matricesIndices) {
  17708. if (!parsedGeometry.matricesIndices._isExpanded) {
  17709. var floatIndices = [];
  17710. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  17711. var matricesIndex = parsedGeometry.matricesIndices[i];
  17712. floatIndices.push(matricesIndex & 0x000000FF);
  17713. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  17714. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  17715. floatIndices.push(matricesIndex >> 24);
  17716. }
  17717. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  17718. } else {
  17719. delete parsedGeometry.matricesIndices._isExpanded;
  17720. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  17721. }
  17722. }
  17723. if (parsedGeometry.matricesWeights) {
  17724. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  17725. }
  17726. mesh.setIndices(parsedGeometry.indices);
  17727. // SubMeshes
  17728. if (parsedGeometry.subMeshes) {
  17729. mesh.subMeshes = [];
  17730. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  17731. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  17732. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  17733. }
  17734. }
  17735. }
  17736. // Flat shading
  17737. if (mesh._shouldGenerateFlatShading) {
  17738. mesh.convertToFlatShadedMesh();
  17739. delete mesh._shouldGenerateFlatShading;
  17740. }
  17741. // Update
  17742. mesh.computeWorldMatrix(true);
  17743. // Octree
  17744. if (scene._selectionOctree) {
  17745. scene._selectionOctree.addMesh(mesh);
  17746. }
  17747. };
  17748. BABYLON.SceneLoader.RegisterPlugin({
  17749. extensions: ".babylon",
  17750. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  17751. var parsedData = JSON.parse(data);
  17752. var loadedSkeletonsIds = [];
  17753. var loadedMaterialsIds = [];
  17754. var hierarchyIds = [];
  17755. for (var index = 0; index < parsedData.meshes.length; index++) {
  17756. var parsedMesh = parsedData.meshes[index];
  17757. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  17758. if (meshesNames instanceof Array) {
  17759. // Remove found mesh name from list.
  17760. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  17761. }
  17762. // Material ?
  17763. if (parsedMesh.materialId) {
  17764. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  17765. if (!materialFound) {
  17766. for (var multimatIndex = 0; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
  17767. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  17768. if (parsedMultiMaterial.id == parsedMesh.materialId) {
  17769. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  17770. var subMatId = parsedMultiMaterial.materials[matIndex];
  17771. loadedMaterialsIds.push(subMatId);
  17772. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  17773. }
  17774. loadedMaterialsIds.push(parsedMultiMaterial.id);
  17775. parseMultiMaterial(parsedMultiMaterial, scene);
  17776. materialFound = true;
  17777. break;
  17778. }
  17779. }
  17780. }
  17781. if (!materialFound) {
  17782. loadedMaterialsIds.push(parsedMesh.materialId);
  17783. parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  17784. }
  17785. }
  17786. // Skeleton ?
  17787. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  17788. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  17789. if (!skeletonAlreadyLoaded) {
  17790. for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
  17791. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  17792. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  17793. skeletons.push(parseSkeleton(parsedSkeleton, scene));
  17794. loadedSkeletonsIds.push(parsedSkeleton.id);
  17795. }
  17796. }
  17797. }
  17798. }
  17799. var mesh = parseMesh(parsedMesh, scene, rootUrl);
  17800. meshes.push(mesh);
  17801. }
  17802. }
  17803. for (index = 0; index < scene.meshes.length; index++) {
  17804. var currentMesh = scene.meshes[index];
  17805. if (currentMesh._waitingParentId) {
  17806. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  17807. currentMesh._waitingParentId = undefined;
  17808. }
  17809. }
  17810. // Particles
  17811. if (parsedData.particleSystems) {
  17812. for (index = 0; index < parsedData.particleSystems.length; index++) {
  17813. var parsedParticleSystem = parsedData.particleSystems[index];
  17814. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  17815. particleSystems.push(parseParticleSystem(parsedParticleSystem, scene, rootUrl));
  17816. }
  17817. }
  17818. }
  17819. return true;
  17820. },
  17821. load: function (scene, data, rootUrl) {
  17822. var parsedData = JSON.parse(data);
  17823. // Scene
  17824. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  17825. scene.autoClear = parsedData.autoClear;
  17826. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  17827. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  17828. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  17829. // Fog
  17830. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  17831. scene.fogMode = parsedData.fogMode;
  17832. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  17833. scene.fogStart = parsedData.fogStart;
  17834. scene.fogEnd = parsedData.fogEnd;
  17835. scene.fogDensity = parsedData.fogDensity;
  17836. }
  17837. for (var index = 0; index < parsedData.lights.length; index++) {
  17838. var parsedLight = parsedData.lights[index];
  17839. parseLight(parsedLight, scene);
  17840. }
  17841. // Materials
  17842. if (parsedData.materials) {
  17843. for (index = 0; index < parsedData.materials.length; index++) {
  17844. var parsedMaterial = parsedData.materials[index];
  17845. parseMaterial(parsedMaterial, scene, rootUrl);
  17846. }
  17847. }
  17848. if (parsedData.multiMaterials) {
  17849. for (index = 0; index < parsedData.multiMaterials.length; index++) {
  17850. var parsedMultiMaterial = parsedData.multiMaterials[index];
  17851. parseMultiMaterial(parsedMultiMaterial, scene);
  17852. }
  17853. }
  17854. // Skeletons
  17855. if (parsedData.skeletons) {
  17856. for (index = 0; index < parsedData.skeletons.length; index++) {
  17857. var parsedSkeleton = parsedData.skeletons[index];
  17858. parseSkeleton(parsedSkeleton, scene);
  17859. }
  17860. }
  17861. // Geometries
  17862. var geometries = parsedData.geometries;
  17863. if (geometries) {
  17864. // Boxes
  17865. var boxes = geometries.boxes;
  17866. if (boxes) {
  17867. for (index = 0; index < boxes.length; index++) {
  17868. var parsedBox = boxes[index];
  17869. parseBox(parsedBox, scene);
  17870. }
  17871. }
  17872. // Spheres
  17873. var spheres = geometries.spheres;
  17874. if (spheres) {
  17875. for (index = 0; index < spheres.length; index++) {
  17876. var parsedSphere = spheres[index];
  17877. parseSphere(parsedSphere, scene);
  17878. }
  17879. }
  17880. // Cylinders
  17881. var cylinders = geometries.cylinders;
  17882. if (cylinders) {
  17883. for (index = 0; index < cylinders.length; index++) {
  17884. var parsedCylinder = cylinders[index];
  17885. parseCylinder(parsedCylinder, scene);
  17886. }
  17887. }
  17888. // Toruses
  17889. var toruses = geometries.toruses;
  17890. if (toruses) {
  17891. for (index = 0; index < toruses.length; index++) {
  17892. var parsedTorus = toruses[index];
  17893. parseTorus(parsedTorus, scene);
  17894. }
  17895. }
  17896. // Grounds
  17897. var grounds = geometries.grounds;
  17898. if (grounds) {
  17899. for (index = 0; index < grounds.length; index++) {
  17900. var parsedGround = grounds[index];
  17901. parseGround(parsedGround, scene);
  17902. }
  17903. }
  17904. // Planes
  17905. var planes = geometries.planes;
  17906. if (planes) {
  17907. for (index = 0; index < planes.length; index++) {
  17908. var parsedPlane = planes[index];
  17909. parsePlane(parsedPlane, scene);
  17910. }
  17911. }
  17912. // TorusKnots
  17913. var torusKnots = geometries.torusKnots;
  17914. if (torusKnots) {
  17915. for (index = 0; index < torusKnots.length; index++) {
  17916. var parsedTorusKnot = torusKnots[index];
  17917. parseTorusKnot(parsedTorusKnot, scene);
  17918. }
  17919. }
  17920. // VertexData
  17921. var vertexData = geometries.vertexData;
  17922. if (vertexData) {
  17923. for (index = 0; index < vertexData.length; index++) {
  17924. var parsedVertexData = vertexData[index];
  17925. parseVertexData(parsedVertexData, scene, rootUrl);
  17926. }
  17927. }
  17928. }
  17929. for (index = 0; index < parsedData.meshes.length; index++) {
  17930. var parsedMesh = parsedData.meshes[index];
  17931. parseMesh(parsedMesh, scene, rootUrl);
  17932. }
  17933. for (index = 0; index < parsedData.cameras.length; index++) {
  17934. var parsedCamera = parsedData.cameras[index];
  17935. parseCamera(parsedCamera, scene);
  17936. }
  17937. if (parsedData.activeCameraID) {
  17938. scene.setActiveCameraByID(parsedData.activeCameraID);
  17939. }
  17940. for (index = 0; index < scene.cameras.length; index++) {
  17941. var camera = scene.cameras[index];
  17942. if (camera._waitingParentId) {
  17943. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  17944. camera._waitingParentId = undefined;
  17945. }
  17946. }
  17947. for (index = 0; index < scene.lights.length; index++) {
  17948. var light = scene.lights[index];
  17949. if (light._waitingParentId) {
  17950. light.parent = scene.getLastEntryByID(light._waitingParentId);
  17951. light._waitingParentId = undefined;
  17952. }
  17953. }
  17954. for (index = 0; index < scene.meshes.length; index++) {
  17955. var mesh = scene.meshes[index];
  17956. if (mesh._waitingParentId) {
  17957. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  17958. mesh._waitingParentId = undefined;
  17959. }
  17960. }
  17961. // Particles Systems
  17962. if (parsedData.particleSystems) {
  17963. for (index = 0; index < parsedData.particleSystems.length; index++) {
  17964. var parsedParticleSystem = parsedData.particleSystems[index];
  17965. parseParticleSystem(parsedParticleSystem, scene, rootUrl);
  17966. }
  17967. }
  17968. // Lens flares
  17969. if (parsedData.lensFlareSystems) {
  17970. for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
  17971. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  17972. parseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
  17973. }
  17974. }
  17975. // Shadows
  17976. if (parsedData.shadowGenerators) {
  17977. for (index = 0; index < parsedData.shadowGenerators.length; index++) {
  17978. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  17979. parseShadowGenerator(parsedShadowGenerator, scene);
  17980. }
  17981. }
  17982. // Finish
  17983. return true;
  17984. }
  17985. });
  17986. })(BABYLON.Internals || (BABYLON.Internals = {}));
  17987. var Internals = BABYLON.Internals;
  17988. })(BABYLON || (BABYLON = {}));
  17989. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  17990. var BABYLON;
  17991. (function (BABYLON) {
  17992. // Unique ID when we import meshes from Babylon to CSG
  17993. var currentCSGMeshId = 0;
  17994. // # class Vertex
  17995. // Represents a vertex of a polygon. Use your own vertex class instead of this
  17996. // one to provide additional features like texture coordinates and vertex
  17997. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  17998. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  17999. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  18000. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  18001. // is not used anywhere else.
  18002. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  18003. var Vertex = (function () {
  18004. function Vertex(pos, normal, uv) {
  18005. this.pos = pos;
  18006. this.normal = normal;
  18007. this.uv = uv;
  18008. }
  18009. Vertex.prototype.clone = function () {
  18010. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  18011. };
  18012. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  18013. // orientation of a polygon is flipped.
  18014. Vertex.prototype.flip = function () {
  18015. this.normal = this.normal.scale(-1);
  18016. };
  18017. // Create a new vertex between this vertex and `other` by linearly
  18018. // interpolating all properties using a parameter of `t`. Subclasses should
  18019. // override this to interpolate additional properties.
  18020. Vertex.prototype.interpolate = function (other, t) {
  18021. 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));
  18022. };
  18023. return Vertex;
  18024. })();
  18025. // # class Plane
  18026. // Represents a plane in 3D space.
  18027. var Plane = (function () {
  18028. function Plane(normal, w) {
  18029. this.normal = normal;
  18030. this.w = w;
  18031. }
  18032. Plane.FromPoints = function (a, b, c) {
  18033. var v0 = c.subtract(a);
  18034. var v1 = b.subtract(a);
  18035. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  18036. return null;
  18037. }
  18038. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  18039. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  18040. };
  18041. Plane.prototype.clone = function () {
  18042. return new Plane(this.normal.clone(), this.w);
  18043. };
  18044. Plane.prototype.flip = function () {
  18045. this.normal.scaleInPlace(-1);
  18046. this.w = -this.w;
  18047. };
  18048. // Split `polygon` by this plane if needed, then put the polygon or polygon
  18049. // fragments in the appropriate lists. Coplanar polygons go into either
  18050. // `coplanarFront` or `coplanarBack` depending on their orientation with
  18051. // respect to this plane. Polygons in front or in back of this plane go into
  18052. // either `front` or `back`.
  18053. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  18054. var COPLANAR = 0;
  18055. var FRONT = 1;
  18056. var BACK = 2;
  18057. var SPANNING = 3;
  18058. // Classify each point as well as the entire polygon into one of the above
  18059. // four classes.
  18060. var polygonType = 0;
  18061. var types = [];
  18062. for (var i = 0; i < polygon.vertices.length; i++) {
  18063. var t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  18064. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  18065. polygonType |= type;
  18066. types.push(type);
  18067. }
  18068. switch (polygonType) {
  18069. case COPLANAR:
  18070. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  18071. break;
  18072. case FRONT:
  18073. front.push(polygon);
  18074. break;
  18075. case BACK:
  18076. back.push(polygon);
  18077. break;
  18078. case SPANNING:
  18079. var f = [], b = [];
  18080. for (i = 0; i < polygon.vertices.length; i++) {
  18081. var j = (i + 1) % polygon.vertices.length;
  18082. var ti = types[i], tj = types[j];
  18083. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  18084. if (ti != BACK)
  18085. f.push(vi);
  18086. if (ti != FRONT)
  18087. b.push(ti != BACK ? vi.clone() : vi);
  18088. if ((ti | tj) == SPANNING) {
  18089. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  18090. var v = vi.interpolate(vj, t);
  18091. f.push(v);
  18092. b.push(v.clone());
  18093. }
  18094. }
  18095. if (f.length >= 3) {
  18096. var poly = new Polygon(f, polygon.shared);
  18097. if (poly.plane)
  18098. front.push(poly);
  18099. }
  18100. if (b.length >= 3) {
  18101. poly = new Polygon(b, polygon.shared);
  18102. if (poly.plane)
  18103. back.push(poly);
  18104. }
  18105. break;
  18106. }
  18107. };
  18108. Plane.EPSILON = 1e-5;
  18109. return Plane;
  18110. })();
  18111. // # class Polygon
  18112. // Represents a convex polygon. The vertices used to initialize a polygon must
  18113. // be coplanar and form a convex loop.
  18114. //
  18115. // Each convex polygon has a `shared` property, which is shared between all
  18116. // polygons that are clones of each other or were split from the same polygon.
  18117. // This can be used to define per-polygon properties (such as surface color).
  18118. var Polygon = (function () {
  18119. function Polygon(vertices, shared) {
  18120. this.vertices = vertices;
  18121. this.shared = shared;
  18122. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  18123. }
  18124. Polygon.prototype.clone = function () {
  18125. var vertices = this.vertices.map(function (v) {
  18126. return v.clone();
  18127. });
  18128. return new Polygon(vertices, this.shared);
  18129. };
  18130. Polygon.prototype.flip = function () {
  18131. this.vertices.reverse().map(function (v) {
  18132. v.flip();
  18133. });
  18134. this.plane.flip();
  18135. };
  18136. return Polygon;
  18137. })();
  18138. // # class Node
  18139. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  18140. // by picking a polygon to split along. That polygon (and all other coplanar
  18141. // polygons) are added directly to that node and the other polygons are added to
  18142. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  18143. // no distinction between internal and leaf nodes.
  18144. var Node = (function () {
  18145. function Node(polygons) {
  18146. this.plane = null;
  18147. this.front = null;
  18148. this.back = null;
  18149. this.polygons = [];
  18150. if (polygons) {
  18151. this.build(polygons);
  18152. }
  18153. }
  18154. Node.prototype.clone = function () {
  18155. var node = new Node();
  18156. node.plane = this.plane && this.plane.clone();
  18157. node.front = this.front && this.front.clone();
  18158. node.back = this.back && this.back.clone();
  18159. node.polygons = this.polygons.map(function (p) {
  18160. return p.clone();
  18161. });
  18162. return node;
  18163. };
  18164. // Convert solid space to empty space and empty space to solid space.
  18165. Node.prototype.invert = function () {
  18166. for (var i = 0; i < this.polygons.length; i++) {
  18167. this.polygons[i].flip();
  18168. }
  18169. if (this.plane) {
  18170. this.plane.flip();
  18171. }
  18172. if (this.front) {
  18173. this.front.invert();
  18174. }
  18175. if (this.back) {
  18176. this.back.invert();
  18177. }
  18178. var temp = this.front;
  18179. this.front = this.back;
  18180. this.back = temp;
  18181. };
  18182. // Recursively remove all polygons in `polygons` that are inside this BSP
  18183. // tree.
  18184. Node.prototype.clipPolygons = function (polygons) {
  18185. if (!this.plane)
  18186. return polygons.slice();
  18187. var front = [], back = [];
  18188. for (var i = 0; i < polygons.length; i++) {
  18189. this.plane.splitPolygon(polygons[i], front, back, front, back);
  18190. }
  18191. if (this.front) {
  18192. front = this.front.clipPolygons(front);
  18193. }
  18194. if (this.back) {
  18195. back = this.back.clipPolygons(back);
  18196. } else {
  18197. back = [];
  18198. }
  18199. return front.concat(back);
  18200. };
  18201. // Remove all polygons in this BSP tree that are inside the other BSP tree
  18202. // `bsp`.
  18203. Node.prototype.clipTo = function (bsp) {
  18204. this.polygons = bsp.clipPolygons(this.polygons);
  18205. if (this.front)
  18206. this.front.clipTo(bsp);
  18207. if (this.back)
  18208. this.back.clipTo(bsp);
  18209. };
  18210. // Return a list of all polygons in this BSP tree.
  18211. Node.prototype.allPolygons = function () {
  18212. var polygons = this.polygons.slice();
  18213. if (this.front)
  18214. polygons = polygons.concat(this.front.allPolygons());
  18215. if (this.back)
  18216. polygons = polygons.concat(this.back.allPolygons());
  18217. return polygons;
  18218. };
  18219. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  18220. // new polygons are filtered down to the bottom of the tree and become new
  18221. // nodes there. Each set of polygons is partitioned using the first polygon
  18222. // (no heuristic is used to pick a good split).
  18223. Node.prototype.build = function (polygons) {
  18224. if (!polygons.length)
  18225. return;
  18226. if (!this.plane)
  18227. this.plane = polygons[0].plane.clone();
  18228. var front = [], back = [];
  18229. for (var i = 0; i < polygons.length; i++) {
  18230. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  18231. }
  18232. if (front.length) {
  18233. if (!this.front)
  18234. this.front = new Node();
  18235. this.front.build(front);
  18236. }
  18237. if (back.length) {
  18238. if (!this.back)
  18239. this.back = new Node();
  18240. this.back.build(back);
  18241. }
  18242. };
  18243. return Node;
  18244. })();
  18245. var CSG = (function () {
  18246. function CSG() {
  18247. this.polygons = new Array();
  18248. }
  18249. // Convert BABYLON.Mesh to BABYLON.CSG
  18250. CSG.FromMesh = function (mesh) {
  18251. var vertex, normal, uv, position, polygon, polygons = [], vertices;
  18252. if (mesh instanceof BABYLON.Mesh) {
  18253. mesh.computeWorldMatrix(true);
  18254. var matrix = mesh.getWorldMatrix();
  18255. var meshPosition = mesh.position.clone();
  18256. var meshRotation = mesh.rotation.clone();
  18257. var meshScaling = mesh.scaling.clone();
  18258. } else {
  18259. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  18260. }
  18261. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  18262. var subMeshes = mesh.subMeshes;
  18263. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  18264. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  18265. vertices = [];
  18266. for (var j = 0; j < 3; j++) {
  18267. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  18268. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  18269. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  18270. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  18271. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  18272. vertex = new Vertex(position, normal, uv);
  18273. vertices.push(vertex);
  18274. }
  18275. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  18276. // To handle the case of degenerated triangle
  18277. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  18278. if (polygon.plane)
  18279. polygons.push(polygon);
  18280. }
  18281. }
  18282. var csg = CSG.FromPolygons(polygons);
  18283. csg.matrix = matrix;
  18284. csg.position = meshPosition;
  18285. csg.rotation = meshRotation;
  18286. csg.scaling = meshScaling;
  18287. currentCSGMeshId++;
  18288. return csg;
  18289. };
  18290. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  18291. CSG.FromPolygons = function (polygons) {
  18292. var csg = new BABYLON.CSG();
  18293. csg.polygons = polygons;
  18294. return csg;
  18295. };
  18296. CSG.prototype.clone = function () {
  18297. var csg = new BABYLON.CSG();
  18298. csg.polygons = this.polygons.map(function (p) {
  18299. return p.clone();
  18300. });
  18301. csg.copyTransformAttributes(this);
  18302. return csg;
  18303. };
  18304. CSG.prototype.toPolygons = function () {
  18305. return this.polygons;
  18306. };
  18307. CSG.prototype.union = function (csg) {
  18308. var a = new Node(this.clone().polygons);
  18309. var b = new Node(csg.clone().polygons);
  18310. a.clipTo(b);
  18311. b.clipTo(a);
  18312. b.invert();
  18313. b.clipTo(a);
  18314. b.invert();
  18315. a.build(b.allPolygons());
  18316. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  18317. };
  18318. CSG.prototype.unionInPlace = function (csg) {
  18319. var a = new Node(this.polygons);
  18320. var b = new Node(csg.polygons);
  18321. a.clipTo(b);
  18322. b.clipTo(a);
  18323. b.invert();
  18324. b.clipTo(a);
  18325. b.invert();
  18326. a.build(b.allPolygons());
  18327. this.polygons = a.allPolygons();
  18328. };
  18329. CSG.prototype.subtract = function (csg) {
  18330. var a = new Node(this.clone().polygons);
  18331. var b = new Node(csg.clone().polygons);
  18332. a.invert();
  18333. a.clipTo(b);
  18334. b.clipTo(a);
  18335. b.invert();
  18336. b.clipTo(a);
  18337. b.invert();
  18338. a.build(b.allPolygons());
  18339. a.invert();
  18340. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  18341. };
  18342. CSG.prototype.subtractInPlace = function (csg) {
  18343. var a = new Node(this.polygons);
  18344. var b = new Node(csg.polygons);
  18345. a.invert();
  18346. a.clipTo(b);
  18347. b.clipTo(a);
  18348. b.invert();
  18349. b.clipTo(a);
  18350. b.invert();
  18351. a.build(b.allPolygons());
  18352. a.invert();
  18353. this.polygons = a.allPolygons();
  18354. };
  18355. CSG.prototype.intersect = function (csg) {
  18356. var a = new Node(this.clone().polygons);
  18357. var b = new Node(csg.clone().polygons);
  18358. a.invert();
  18359. b.clipTo(a);
  18360. b.invert();
  18361. a.clipTo(b);
  18362. b.clipTo(a);
  18363. a.build(b.allPolygons());
  18364. a.invert();
  18365. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  18366. };
  18367. CSG.prototype.intersectInPlace = function (csg) {
  18368. var a = new Node(this.polygons);
  18369. var b = new Node(csg.polygons);
  18370. a.invert();
  18371. b.clipTo(a);
  18372. b.invert();
  18373. a.clipTo(b);
  18374. b.clipTo(a);
  18375. a.build(b.allPolygons());
  18376. a.invert();
  18377. this.polygons = a.allPolygons();
  18378. };
  18379. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  18380. // not modified.
  18381. CSG.prototype.inverse = function () {
  18382. var csg = this.clone();
  18383. csg.inverseInPlace();
  18384. return csg;
  18385. };
  18386. CSG.prototype.inverseInPlace = function () {
  18387. this.polygons.map(function (p) {
  18388. p.flip();
  18389. });
  18390. };
  18391. // This is used to keep meshes transformations so they can be restored
  18392. // when we build back a Babylon Mesh
  18393. // NB : All CSG operations are performed in world coordinates
  18394. CSG.prototype.copyTransformAttributes = function (csg) {
  18395. this.matrix = csg.matrix;
  18396. this.position = csg.position;
  18397. this.rotation = csg.rotation;
  18398. this.scaling = csg.scaling;
  18399. return this;
  18400. };
  18401. // Build Raw mesh from CSG
  18402. // Coordinates here are in world space
  18403. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  18404. var matrix = this.matrix.clone();
  18405. matrix.invert();
  18406. 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;
  18407. if (keepSubMeshes) {
  18408. // Sort Polygons, since subMeshes are indices range
  18409. polygons.sort(function (a, b) {
  18410. if (a.shared.meshId === b.shared.meshId) {
  18411. return a.shared.subMeshId - b.shared.subMeshId;
  18412. } else {
  18413. return a.shared.meshId - b.shared.meshId;
  18414. }
  18415. });
  18416. }
  18417. for (var i = 0, il = polygons.length; i < il; i++) {
  18418. polygon = polygons[i];
  18419. // Building SubMeshes
  18420. if (!subMesh_dict[polygon.shared.meshId]) {
  18421. subMesh_dict[polygon.shared.meshId] = {};
  18422. }
  18423. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  18424. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  18425. indexStart: +Infinity,
  18426. indexEnd: -Infinity,
  18427. materialIndex: polygon.shared.materialIndex
  18428. };
  18429. }
  18430. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  18431. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  18432. polygonIndices[0] = 0;
  18433. polygonIndices[1] = j - 1;
  18434. polygonIndices[2] = j;
  18435. for (var k = 0; k < 3; k++) {
  18436. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  18437. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  18438. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  18439. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  18440. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  18441. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  18442. // Check if 2 points can be merged
  18443. 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)) {
  18444. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  18445. uvs.push(uv.x, uv.y);
  18446. normals.push(normal.x, normal.y, normal.z);
  18447. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  18448. }
  18449. indices.push(vertex_idx);
  18450. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  18451. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  18452. currentIndex++;
  18453. }
  18454. }
  18455. }
  18456. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  18457. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  18458. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  18459. mesh.setIndices(indices);
  18460. if (keepSubMeshes) {
  18461. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  18462. var materialIndexOffset = 0, materialMaxIndex;
  18463. mesh.subMeshes.length = 0;
  18464. for (var m in subMesh_dict) {
  18465. materialMaxIndex = -1;
  18466. for (var sm in subMesh_dict[m]) {
  18467. subMesh_obj = subMesh_dict[m][sm];
  18468. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  18469. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  18470. }
  18471. materialIndexOffset += ++materialMaxIndex;
  18472. }
  18473. }
  18474. return mesh;
  18475. };
  18476. // Build Mesh from CSG taking material and transforms into account
  18477. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  18478. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  18479. mesh.material = material;
  18480. mesh.position.copyFrom(this.position);
  18481. mesh.rotation.copyFrom(this.rotation);
  18482. mesh.scaling.copyFrom(this.scaling);
  18483. mesh.computeWorldMatrix(true);
  18484. return mesh;
  18485. };
  18486. return CSG;
  18487. })();
  18488. BABYLON.CSG = CSG;
  18489. })(BABYLON || (BABYLON = {}));
  18490. //# sourceMappingURL=babylon.csg.js.map
  18491. var BABYLON;
  18492. (function (BABYLON) {
  18493. var OculusDistortionCorrectionPostProcess = (function (_super) {
  18494. __extends(OculusDistortionCorrectionPostProcess, _super);
  18495. //ANY
  18496. function OculusDistortionCorrectionPostProcess(name, camera, isRightEye, cameraSettings) {
  18497. var _this = this;
  18498. _super.call(this, name, "oculusDistortionCorrection", [
  18499. 'LensCenter',
  18500. 'Scale',
  18501. 'ScaleIn',
  18502. 'HmdWarpParam'
  18503. ], null, cameraSettings.PostProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  18504. this._isRightEye = isRightEye;
  18505. this._distortionFactors = cameraSettings.DistortionK;
  18506. this._postProcessScaleFactor = cameraSettings.PostProcessScaleFactor;
  18507. this._lensCenterOffset = cameraSettings.LensCenterOffset;
  18508. this.onSizeChanged = function () {
  18509. _this.aspectRatio = _this.width * .5 / _this.height;
  18510. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  18511. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  18512. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  18513. };
  18514. this.onApply = function (effect) {
  18515. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  18516. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  18517. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  18518. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  18519. };
  18520. }
  18521. return OculusDistortionCorrectionPostProcess;
  18522. })(BABYLON.PostProcess);
  18523. BABYLON.OculusDistortionCorrectionPostProcess = OculusDistortionCorrectionPostProcess;
  18524. })(BABYLON || (BABYLON = {}));
  18525. //# sourceMappingURL=babylon.oculusDistortionCorrectionPostProcess.js.map
  18526. // Mainly based on these 2 articles :
  18527. // 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
  18528. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  18529. var BABYLON;
  18530. (function (BABYLON) {
  18531. (function (JoystickAxis) {
  18532. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  18533. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  18534. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  18535. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  18536. var JoystickAxis = BABYLON.JoystickAxis;
  18537. var VirtualJoystick = (function () {
  18538. function VirtualJoystick(leftJoystick) {
  18539. var _this = this;
  18540. if (leftJoystick) {
  18541. this._leftJoystick = true;
  18542. } else {
  18543. this._leftJoystick = false;
  18544. }
  18545. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  18546. VirtualJoystick._globalJoystickIndex++;
  18547. // By default left & right arrow keys are moving the X
  18548. // and up & down keys are moving the Y
  18549. this._axisTargetedByLeftAndRight = 0 /* X */;
  18550. this._axisTargetedByUpAndDown = 1 /* Y */;
  18551. this.reverseLeftRight = false;
  18552. this.reverseUpDown = false;
  18553. // collections of pointers
  18554. this._touches = new BABYLON.VirtualJoystick.Collection();
  18555. this.deltaPosition = BABYLON.Vector3.Zero();
  18556. this._joystickSensibility = 25;
  18557. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  18558. this._rotationSpeed = 25;
  18559. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  18560. this._rotateOnAxisRelativeToMesh = false;
  18561. // injecting a canvas element on top of the canvas 3D game
  18562. if (!VirtualJoystick.vjCanvas) {
  18563. window.addEventListener("resize", function () {
  18564. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  18565. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  18566. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  18567. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  18568. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  18569. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  18570. }, false);
  18571. VirtualJoystick.vjCanvas = document.createElement("canvas");
  18572. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  18573. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  18574. VirtualJoystick.vjCanvas.width = window.innerWidth;
  18575. VirtualJoystick.vjCanvas.height = window.innerHeight;
  18576. VirtualJoystick.vjCanvas.style.width = "100%";
  18577. VirtualJoystick.vjCanvas.style.height = "100%";
  18578. VirtualJoystick.vjCanvas.style.position = "absolute";
  18579. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  18580. VirtualJoystick.vjCanvas.style.top = "0px";
  18581. VirtualJoystick.vjCanvas.style.left = "0px";
  18582. VirtualJoystick.vjCanvas.style.zIndex = "5";
  18583. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  18584. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  18585. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  18586. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  18587. document.body.appendChild(VirtualJoystick.vjCanvas);
  18588. }
  18589. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  18590. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  18591. this.pressed = false;
  18592. // default joystick color
  18593. this._joystickColor = "cyan";
  18594. this._joystickPointerID = -1;
  18595. // current joystick position
  18596. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  18597. // origin joystick position
  18598. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  18599. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  18600. VirtualJoystick.vjCanvas.addEventListener('pointerdown', function (evt) {
  18601. _this._onPointerDown(evt);
  18602. }, false);
  18603. VirtualJoystick.vjCanvas.addEventListener('pointermove', function (evt) {
  18604. _this._onPointerMove(evt);
  18605. }, false);
  18606. VirtualJoystick.vjCanvas.addEventListener('pointerup', function (evt) {
  18607. _this._onPointerUp(evt);
  18608. }, false);
  18609. VirtualJoystick.vjCanvas.addEventListener('pointerout', function (evt) {
  18610. _this._onPointerUp(evt);
  18611. }, false);
  18612. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  18613. evt.preventDefault(); // Disables system menu
  18614. }, false);
  18615. requestAnimationFrame(function () {
  18616. _this._drawVirtualJoystick();
  18617. });
  18618. }
  18619. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  18620. this._joystickSensibility = newJoystickSensibility;
  18621. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  18622. };
  18623. VirtualJoystick.prototype._onPointerDown = function (e) {
  18624. var positionOnScreenCondition;
  18625. e.preventDefault();
  18626. if (this._leftJoystick === true) {
  18627. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  18628. } else {
  18629. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  18630. }
  18631. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  18632. // First contact will be dedicated to the virtual joystick
  18633. this._joystickPointerID = e.pointerId;
  18634. this._joystickPointerStartPos.x = e.clientX;
  18635. this._joystickPointerStartPos.y = e.clientY;
  18636. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  18637. this._deltaJoystickVector.x = 0;
  18638. this._deltaJoystickVector.y = 0;
  18639. this.pressed = true;
  18640. this._touches.add(e.pointerId.toString(), e);
  18641. } else {
  18642. // You can only trigger the action buttons with a joystick declared
  18643. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  18644. this._action();
  18645. this._touches.add(e.pointerId.toString(), e);
  18646. }
  18647. }
  18648. };
  18649. VirtualJoystick.prototype._onPointerMove = function (e) {
  18650. // If the current pointer is the one associated to the joystick (first touch contact)
  18651. if (this._joystickPointerID == e.pointerId) {
  18652. this._joystickPointerPos.x = e.clientX;
  18653. this._joystickPointerPos.y = e.clientY;
  18654. this._deltaJoystickVector = this._joystickPointerPos.clone();
  18655. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  18656. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  18657. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  18658. switch (this._axisTargetedByLeftAndRight) {
  18659. case 0 /* X */:
  18660. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  18661. break;
  18662. case 1 /* Y */:
  18663. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  18664. break;
  18665. case 2 /* Z */:
  18666. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  18667. break;
  18668. }
  18669. var directionUpDown = this.reverseUpDown ? 1 : -1;
  18670. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  18671. switch (this._axisTargetedByUpAndDown) {
  18672. case 0 /* X */:
  18673. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  18674. break;
  18675. case 1 /* Y */:
  18676. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  18677. break;
  18678. case 2 /* Z */:
  18679. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  18680. break;
  18681. }
  18682. } else {
  18683. if (this._touches.item(e.pointerId.toString())) {
  18684. this._touches.item(e.pointerId.toString()).x = e.clientX;
  18685. this._touches.item(e.pointerId.toString()).y = e.clientY;
  18686. }
  18687. }
  18688. };
  18689. VirtualJoystick.prototype._onPointerUp = function (e) {
  18690. this._clearCanvas();
  18691. if (this._joystickPointerID == e.pointerId) {
  18692. this._joystickPointerID = -1;
  18693. this.pressed = false;
  18694. }
  18695. this._deltaJoystickVector.x = 0;
  18696. this._deltaJoystickVector.y = 0;
  18697. this._touches.remove(e.pointerId.toString());
  18698. };
  18699. /**
  18700. * Change the color of the virtual joystick
  18701. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  18702. */
  18703. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  18704. this._joystickColor = newColor;
  18705. };
  18706. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  18707. this._action = action;
  18708. };
  18709. // Define which axis you'd like to control for left & right
  18710. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  18711. switch (axis) {
  18712. case 0 /* X */:
  18713. case 1 /* Y */:
  18714. case 2 /* Z */:
  18715. this._axisTargetedByLeftAndRight = axis;
  18716. break;
  18717. default:
  18718. this._axisTargetedByLeftAndRight = 0 /* X */;
  18719. break;
  18720. }
  18721. };
  18722. // Define which axis you'd like to control for up & down
  18723. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  18724. switch (axis) {
  18725. case 0 /* X */:
  18726. case 1 /* Y */:
  18727. case 2 /* Z */:
  18728. this._axisTargetedByUpAndDown = axis;
  18729. break;
  18730. default:
  18731. this._axisTargetedByUpAndDown = 1 /* Y */;
  18732. break;
  18733. }
  18734. };
  18735. VirtualJoystick.prototype._clearCanvas = function () {
  18736. if (this._leftJoystick) {
  18737. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  18738. } else {
  18739. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  18740. }
  18741. };
  18742. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  18743. var _this = this;
  18744. if (this.pressed) {
  18745. this._clearCanvas();
  18746. this._touches.forEach(function (touch) {
  18747. if (touch.pointerId === _this._joystickPointerID) {
  18748. VirtualJoystick.vjCanvasContext.beginPath();
  18749. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  18750. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  18751. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  18752. VirtualJoystick.vjCanvasContext.stroke();
  18753. VirtualJoystick.vjCanvasContext.beginPath();
  18754. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  18755. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  18756. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  18757. VirtualJoystick.vjCanvasContext.stroke();
  18758. VirtualJoystick.vjCanvasContext.beginPath();
  18759. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  18760. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  18761. VirtualJoystick.vjCanvasContext.stroke();
  18762. } else {
  18763. VirtualJoystick.vjCanvasContext.beginPath();
  18764. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  18765. VirtualJoystick.vjCanvasContext.beginPath();
  18766. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  18767. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  18768. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  18769. VirtualJoystick.vjCanvasContext.stroke();
  18770. }
  18771. ;
  18772. });
  18773. }
  18774. requestAnimationFrame(function () {
  18775. _this._drawVirtualJoystick();
  18776. });
  18777. };
  18778. VirtualJoystick.prototype.releaseCanvas = function () {
  18779. if (VirtualJoystick.vjCanvas) {
  18780. document.body.removeChild(VirtualJoystick.vjCanvas);
  18781. VirtualJoystick.vjCanvas = null;
  18782. }
  18783. };
  18784. VirtualJoystick._globalJoystickIndex = 0;
  18785. return VirtualJoystick;
  18786. })();
  18787. BABYLON.VirtualJoystick = VirtualJoystick;
  18788. })(BABYLON || (BABYLON = {}));
  18789. var BABYLON;
  18790. (function (BABYLON) {
  18791. (function (VirtualJoystick) {
  18792. var Collection = (function () {
  18793. function Collection() {
  18794. this._count = 0;
  18795. this._collection = new Array();
  18796. }
  18797. Collection.prototype.Count = function () {
  18798. return this._count;
  18799. };
  18800. Collection.prototype.add = function (key, item) {
  18801. if (this._collection[key] != undefined) {
  18802. return undefined;
  18803. }
  18804. this._collection[key] = item;
  18805. return ++this._count;
  18806. };
  18807. Collection.prototype.remove = function (key) {
  18808. if (this._collection[key] == undefined) {
  18809. return undefined;
  18810. }
  18811. delete this._collection[key];
  18812. return --this._count;
  18813. };
  18814. Collection.prototype.item = function (key) {
  18815. return this._collection[key];
  18816. };
  18817. Collection.prototype.forEach = function (block) {
  18818. var key;
  18819. for (key in this._collection) {
  18820. if (this._collection.hasOwnProperty(key)) {
  18821. block(this._collection[key]);
  18822. }
  18823. }
  18824. };
  18825. return Collection;
  18826. })();
  18827. VirtualJoystick.Collection = Collection;
  18828. })(BABYLON.VirtualJoystick || (BABYLON.VirtualJoystick = {}));
  18829. var VirtualJoystick = BABYLON.VirtualJoystick;
  18830. })(BABYLON || (BABYLON = {}));
  18831. //# sourceMappingURL=babylon.virtualJoystick.js.map
  18832. var BABYLON;
  18833. (function (BABYLON) {
  18834. var OculusRiftDevKit2013_Metric = {
  18835. HResolution: 1280,
  18836. VResolution: 800,
  18837. HScreenSize: 0.149759993,
  18838. VScreenSize: 0.0935999975,
  18839. VScreenCenter: 0.0467999987,
  18840. EyeToScreenDistance: 0.0410000011,
  18841. LensSeparationDistance: 0.0635000020,
  18842. InterpupillaryDistance: 0.0640000030,
  18843. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  18844. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  18845. PostProcessScaleFactor: 1.714605507808412,
  18846. LensCenterOffset: 0.151976421
  18847. };
  18848. var _OculusInnerCamera = (function (_super) {
  18849. __extends(_OculusInnerCamera, _super);
  18850. function _OculusInnerCamera(name, position, scene, isLeftEye) {
  18851. _super.call(this, name, position, scene);
  18852. this._workMatrix = new BABYLON.Matrix();
  18853. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  18854. // Constants
  18855. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  18856. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  18857. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  18858. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  18859. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  18860. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  18861. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  18862. // Postprocess
  18863. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  18864. }
  18865. _OculusInnerCamera.prototype.getProjectionMatrix = function () {
  18866. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  18867. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  18868. return this._projectionMatrix;
  18869. };
  18870. _OculusInnerCamera.prototype._getViewMatrix = function () {
  18871. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  18872. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  18873. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  18874. // Computing target and final matrix
  18875. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  18876. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  18877. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  18878. return this._viewMatrix;
  18879. };
  18880. return _OculusInnerCamera;
  18881. })(BABYLON.FreeCamera);
  18882. var OculusCamera = (function (_super) {
  18883. __extends(OculusCamera, _super);
  18884. function OculusCamera(name, position, scene) {
  18885. _super.call(this, name, position, scene);
  18886. this._leftCamera = new _OculusInnerCamera(name + "_left", position.clone(), scene, true);
  18887. this._rightCamera = new _OculusInnerCamera(name + "_right", position.clone(), scene, false);
  18888. this.subCameras.push(this._leftCamera);
  18889. this.subCameras.push(this._rightCamera);
  18890. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  18891. }
  18892. OculusCamera.prototype._update = function () {
  18893. this._leftCamera.position.copyFrom(this.position);
  18894. this._rightCamera.position.copyFrom(this.position);
  18895. this._updateCamera(this._leftCamera);
  18896. this._updateCamera(this._rightCamera);
  18897. _super.prototype._update.call(this);
  18898. };
  18899. OculusCamera.prototype._updateCamera = function (camera) {
  18900. camera.minZ = this.minZ;
  18901. camera.maxZ = this.maxZ;
  18902. camera.rotation.x = this.rotation.x;
  18903. camera.rotation.y = this.rotation.y;
  18904. camera.rotation.z = this.rotation.z;
  18905. };
  18906. // Oculus events
  18907. OculusCamera.prototype._onOrientationEvent = function (evt) {
  18908. var yaw = evt.alpha / 180 * Math.PI;
  18909. var pitch = evt.beta / 180 * Math.PI;
  18910. var roll = evt.gamma / 180 * Math.PI;
  18911. if (!this._offsetOrientation) {
  18912. this._offsetOrientation = {
  18913. yaw: yaw,
  18914. pitch: pitch,
  18915. roll: roll
  18916. };
  18917. return;
  18918. } else {
  18919. this.rotation.y += yaw - this._offsetOrientation.yaw;
  18920. this.rotation.x += pitch - this._offsetOrientation.pitch;
  18921. this.rotation.z += this._offsetOrientation.roll - roll;
  18922. this._offsetOrientation.yaw = yaw;
  18923. this._offsetOrientation.pitch = pitch;
  18924. this._offsetOrientation.roll = roll;
  18925. }
  18926. };
  18927. OculusCamera.prototype.attachControl = function (element, noPreventDefault) {
  18928. _super.prototype.attachControl.call(this, element, noPreventDefault);
  18929. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  18930. };
  18931. OculusCamera.prototype.detachControl = function (element) {
  18932. _super.prototype.detachControl.call(this, element);
  18933. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  18934. };
  18935. return OculusCamera;
  18936. })(BABYLON.FreeCamera);
  18937. BABYLON.OculusCamera = OculusCamera;
  18938. })(BABYLON || (BABYLON = {}));
  18939. //# sourceMappingURL=babylon.oculusCamera.js.map
  18940. var BABYLON;
  18941. (function (BABYLON) {
  18942. var OculusRiftDevKit2013_Metric = {
  18943. HResolution: 1280,
  18944. VResolution: 800,
  18945. HScreenSize: 0.149759993,
  18946. VScreenSize: 0.0935999975,
  18947. VScreenCenter: 0.0467999987,
  18948. EyeToScreenDistance: 0.0410000011,
  18949. LensSeparationDistance: 0.0635000020,
  18950. InterpupillaryDistance: 0.0640000030,
  18951. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  18952. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  18953. PostProcessScaleFactor: 1.714605507808412,
  18954. LensCenterOffset: 0.151976421
  18955. };
  18956. var _OculusInnerGamepadCamera = (function (_super) {
  18957. __extends(_OculusInnerGamepadCamera, _super);
  18958. function _OculusInnerGamepadCamera(name, position, scene, isLeftEye) {
  18959. _super.call(this, name, position, scene);
  18960. this._workMatrix = new BABYLON.Matrix();
  18961. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  18962. // Constants
  18963. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  18964. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  18965. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  18966. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  18967. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  18968. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  18969. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  18970. // Postprocess
  18971. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  18972. }
  18973. _OculusInnerGamepadCamera.prototype.getProjectionMatrix = function () {
  18974. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  18975. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  18976. return this._projectionMatrix;
  18977. };
  18978. _OculusInnerGamepadCamera.prototype._getViewMatrix = function () {
  18979. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  18980. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  18981. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  18982. // Computing target and final matrix
  18983. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  18984. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  18985. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  18986. return this._viewMatrix;
  18987. };
  18988. return _OculusInnerGamepadCamera;
  18989. })(BABYLON.FreeCamera);
  18990. var OculusGamepadCamera = (function (_super) {
  18991. __extends(OculusGamepadCamera, _super);
  18992. function OculusGamepadCamera(name, position, scene) {
  18993. var _this = this;
  18994. _super.call(this, name, position, scene);
  18995. this.angularSensibility = 200;
  18996. this.moveSensibility = 75;
  18997. this._leftCamera = new _OculusInnerGamepadCamera(name + "_left", position.clone(), scene, true);
  18998. this._rightCamera = new _OculusInnerGamepadCamera(name + "_right", position.clone(), scene, false);
  18999. this.subCameras.push(this._leftCamera);
  19000. this.subCameras.push(this._rightCamera);
  19001. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  19002. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  19003. _this._onNewGameConnected(gamepad);
  19004. });
  19005. }
  19006. OculusGamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  19007. // Only the first gamepad can control the camera
  19008. if (gamepad.index === 0) {
  19009. this._gamepad = gamepad;
  19010. }
  19011. };
  19012. OculusGamepadCamera.prototype._update = function () {
  19013. this._leftCamera.position.copyFrom(this.position);
  19014. this._rightCamera.position.copyFrom(this.position);
  19015. this._updateCamera(this._leftCamera);
  19016. this._updateCamera(this._rightCamera);
  19017. _super.prototype._update.call(this);
  19018. };
  19019. OculusGamepadCamera.prototype._checkInputs = function () {
  19020. if (!this._gamepad) {
  19021. return;
  19022. }
  19023. var LSValues = this._gamepad.leftStick;
  19024. var normalizedLX = LSValues.x / this.moveSensibility;
  19025. var normalizedLY = LSValues.y / this.moveSensibility;
  19026. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  19027. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  19028. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  19029. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x, 0, -LSValues.y), cameraTransform);
  19030. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  19031. };
  19032. OculusGamepadCamera.prototype._updateCamera = function (camera) {
  19033. camera.minZ = this.minZ;
  19034. camera.maxZ = this.maxZ;
  19035. camera.rotation.x = this.rotation.x;
  19036. camera.rotation.y = this.rotation.y;
  19037. camera.rotation.z = this.rotation.z;
  19038. };
  19039. // Oculus events
  19040. OculusGamepadCamera.prototype._onOrientationEvent = function (evt) {
  19041. var yaw = evt.alpha / 180 * Math.PI;
  19042. var pitch = evt.beta / 180 * Math.PI;
  19043. var roll = evt.gamma / 180 * Math.PI;
  19044. if (!this._offsetOrientation) {
  19045. this._offsetOrientation = {
  19046. yaw: yaw,
  19047. pitch: pitch,
  19048. roll: roll
  19049. };
  19050. return;
  19051. } else {
  19052. this.rotation.y += yaw - this._offsetOrientation.yaw;
  19053. this.rotation.x += pitch - this._offsetOrientation.pitch;
  19054. this.rotation.z += this._offsetOrientation.roll - roll;
  19055. this._offsetOrientation.yaw = yaw;
  19056. this._offsetOrientation.pitch = pitch;
  19057. this._offsetOrientation.roll = roll;
  19058. }
  19059. };
  19060. OculusGamepadCamera.prototype.attachControl = function (element, noPreventDefault) {
  19061. _super.prototype.attachControl.call(this, element, noPreventDefault);
  19062. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  19063. };
  19064. OculusGamepadCamera.prototype.detachControl = function (element) {
  19065. _super.prototype.detachControl.call(this, element);
  19066. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  19067. };
  19068. OculusGamepadCamera.prototype.dispose = function () {
  19069. this._gamepads.dispose();
  19070. _super.prototype.dispose.call(this);
  19071. };
  19072. return OculusGamepadCamera;
  19073. })(BABYLON.FreeCamera);
  19074. BABYLON.OculusGamepadCamera = OculusGamepadCamera;
  19075. })(BABYLON || (BABYLON = {}));
  19076. //# sourceMappingURL=babylon.oculusGamepadCamera.js.map
  19077. var BABYLON;
  19078. (function (BABYLON) {
  19079. // We're mainly based on the logic defined into the FreeCamera code
  19080. var VirtualJoysticksCamera = (function (_super) {
  19081. __extends(VirtualJoysticksCamera, _super);
  19082. function VirtualJoysticksCamera(name, position, scene) {
  19083. _super.call(this, name, position, scene);
  19084. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  19085. this._leftjoystick.setAxisForUpDown(2 /* Z */);
  19086. this._leftjoystick.setAxisForLeftRight(0 /* X */);
  19087. this._leftjoystick.setJoystickSensibility(0.15);
  19088. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  19089. this._rightjoystick.setAxisForUpDown(0 /* X */);
  19090. this._rightjoystick.setAxisForLeftRight(1 /* Y */);
  19091. this._rightjoystick.reverseUpDown = true;
  19092. this._rightjoystick.setJoystickSensibility(0.05);
  19093. this._rightjoystick.setJoystickColor("yellow");
  19094. }
  19095. VirtualJoysticksCamera.prototype._checkInputs = function () {
  19096. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  19097. var deltaTransform = BABYLON.Vector3.TransformCoordinates(this._leftjoystick.deltaPosition, cameraTransform);
  19098. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  19099. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  19100. if (!this._leftjoystick.pressed) {
  19101. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  19102. }
  19103. if (!this._rightjoystick.pressed) {
  19104. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  19105. }
  19106. };
  19107. VirtualJoysticksCamera.prototype.dispose = function () {
  19108. this._leftjoystick.releaseCanvas();
  19109. _super.prototype.dispose.call(this);
  19110. };
  19111. return VirtualJoysticksCamera;
  19112. })(BABYLON.FreeCamera);
  19113. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  19114. })(BABYLON || (BABYLON = {}));
  19115. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  19116. var BABYLON;
  19117. (function (BABYLON) {
  19118. var ShaderMaterial = (function (_super) {
  19119. __extends(ShaderMaterial, _super);
  19120. function ShaderMaterial(name, scene, shaderPath, options) {
  19121. _super.call(this, name, scene);
  19122. this._textures = new Array();
  19123. this._floats = new Array();
  19124. this._floatsArrays = {};
  19125. this._colors3 = new Array();
  19126. this._colors4 = new Array();
  19127. this._vectors2 = new Array();
  19128. this._vectors3 = new Array();
  19129. this._matrices = new Array();
  19130. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  19131. this._shaderPath = shaderPath;
  19132. options.needAlphaBlending = options.needAlphaBlending || false;
  19133. options.needAlphaTesting = options.needAlphaTesting || false;
  19134. options.attributes = options.attributes || ["position", "normal", "uv"];
  19135. options.uniforms = options.uniforms || ["worldViewProjection"];
  19136. options.samplers = options.samplers || [];
  19137. this._options = options;
  19138. }
  19139. ShaderMaterial.prototype.needAlphaBlending = function () {
  19140. return this._options.needAlphaBlending;
  19141. };
  19142. ShaderMaterial.prototype.needAlphaTesting = function () {
  19143. return this._options.needAlphaTesting;
  19144. };
  19145. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  19146. if (this._options.uniforms.indexOf(uniformName) === -1) {
  19147. this._options.uniforms.push(uniformName);
  19148. }
  19149. };
  19150. ShaderMaterial.prototype.setTexture = function (name, texture) {
  19151. if (this._options.samplers.indexOf(name) === -1) {
  19152. this._options.samplers.push(name);
  19153. }
  19154. this._textures[name] = texture;
  19155. return this;
  19156. };
  19157. ShaderMaterial.prototype.setFloat = function (name, value) {
  19158. this._checkUniform(name);
  19159. this._floats[name] = value;
  19160. return this;
  19161. };
  19162. ShaderMaterial.prototype.setFloats = function (name, value) {
  19163. this._checkUniform(name);
  19164. this._floatsArrays[name] = value;
  19165. return this;
  19166. };
  19167. ShaderMaterial.prototype.setColor3 = function (name, value) {
  19168. this._checkUniform(name);
  19169. this._colors3[name] = value;
  19170. return this;
  19171. };
  19172. ShaderMaterial.prototype.setColor4 = function (name, value) {
  19173. this._checkUniform(name);
  19174. this._colors4[name] = value;
  19175. return this;
  19176. };
  19177. ShaderMaterial.prototype.setVector2 = function (name, value) {
  19178. this._checkUniform(name);
  19179. this._vectors2[name] = value;
  19180. return this;
  19181. };
  19182. ShaderMaterial.prototype.setVector3 = function (name, value) {
  19183. this._checkUniform(name);
  19184. this._vectors3[name] = value;
  19185. return this;
  19186. };
  19187. ShaderMaterial.prototype.setMatrix = function (name, value) {
  19188. this._checkUniform(name);
  19189. this._matrices[name] = value;
  19190. return this;
  19191. };
  19192. ShaderMaterial.prototype.isReady = function () {
  19193. var scene = this.getScene();
  19194. var engine = scene.getEngine();
  19195. if (!this.checkReadyOnEveryCall) {
  19196. if (this._renderId === scene.getRenderId()) {
  19197. return true;
  19198. }
  19199. }
  19200. var previousEffect = this._effect;
  19201. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, "", null, this.onCompiled, this.onError);
  19202. if (!this._effect.isReady()) {
  19203. return false;
  19204. }
  19205. if (previousEffect !== this._effect) {
  19206. scene.resetCachedMaterial();
  19207. }
  19208. this._renderId = scene.getRenderId();
  19209. return true;
  19210. };
  19211. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  19212. var scene = this.getScene();
  19213. if (this._options.uniforms.indexOf("world") !== -1) {
  19214. this._effect.setMatrix("world", world);
  19215. }
  19216. if (this._options.uniforms.indexOf("worldView") !== -1) {
  19217. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  19218. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  19219. }
  19220. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  19221. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  19222. }
  19223. };
  19224. ShaderMaterial.prototype.bind = function (world) {
  19225. // Std values
  19226. this.bindOnlyWorldMatrix(world);
  19227. if (this.getScene().getCachedMaterial() !== this) {
  19228. if (this._options.uniforms.indexOf("view") !== -1) {
  19229. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  19230. }
  19231. if (this._options.uniforms.indexOf("projection") !== -1) {
  19232. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  19233. }
  19234. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  19235. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  19236. }
  19237. for (var name in this._textures) {
  19238. this._effect.setTexture(name, this._textures[name]);
  19239. }
  19240. for (name in this._floats) {
  19241. this._effect.setFloat(name, this._floats[name]);
  19242. }
  19243. for (name in this._floatsArrays) {
  19244. this._effect.setArray(name, this._floatsArrays[name]);
  19245. }
  19246. for (name in this._colors3) {
  19247. this._effect.setColor3(name, this._colors3[name]);
  19248. }
  19249. for (name in this._colors4) {
  19250. var color = this._colors4[name];
  19251. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  19252. }
  19253. for (name in this._vectors2) {
  19254. this._effect.setVector2(name, this._vectors2[name]);
  19255. }
  19256. for (name in this._vectors3) {
  19257. this._effect.setVector3(name, this._vectors3[name]);
  19258. }
  19259. for (name in this._matrices) {
  19260. this._effect.setMatrix(name, this._matrices[name]);
  19261. }
  19262. }
  19263. _super.prototype.bind.call(this, world, null);
  19264. };
  19265. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  19266. for (var name in this._textures) {
  19267. this._textures[name].dispose();
  19268. }
  19269. this._textures = [];
  19270. _super.prototype.dispose.call(this, forceDisposeEffect);
  19271. };
  19272. return ShaderMaterial;
  19273. })(BABYLON.Material);
  19274. BABYLON.ShaderMaterial = ShaderMaterial;
  19275. })(BABYLON || (BABYLON = {}));
  19276. //# sourceMappingURL=babylon.shaderMaterial.js.map
  19277. var BABYLON;
  19278. (function (BABYLON) {
  19279. var VertexData = (function () {
  19280. function VertexData() {
  19281. }
  19282. VertexData.prototype.set = function (data, kind) {
  19283. switch (kind) {
  19284. case BABYLON.VertexBuffer.PositionKind:
  19285. this.positions = data;
  19286. break;
  19287. case BABYLON.VertexBuffer.NormalKind:
  19288. this.normals = data;
  19289. break;
  19290. case BABYLON.VertexBuffer.UVKind:
  19291. this.uvs = data;
  19292. break;
  19293. case BABYLON.VertexBuffer.UV2Kind:
  19294. this.uv2s = data;
  19295. break;
  19296. case BABYLON.VertexBuffer.ColorKind:
  19297. this.colors = data;
  19298. break;
  19299. case BABYLON.VertexBuffer.MatricesIndicesKind:
  19300. this.matricesIndices = data;
  19301. break;
  19302. case BABYLON.VertexBuffer.MatricesWeightsKind:
  19303. this.matricesWeights = data;
  19304. break;
  19305. }
  19306. };
  19307. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  19308. this._applyTo(mesh, updatable);
  19309. };
  19310. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  19311. this._applyTo(geometry, updatable);
  19312. };
  19313. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  19314. this._update(mesh);
  19315. };
  19316. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  19317. this._update(geometry);
  19318. };
  19319. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  19320. if (this.positions) {
  19321. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  19322. }
  19323. if (this.normals) {
  19324. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  19325. }
  19326. if (this.uvs) {
  19327. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  19328. }
  19329. if (this.uv2s) {
  19330. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updatable);
  19331. }
  19332. if (this.colors) {
  19333. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  19334. }
  19335. if (this.matricesIndices) {
  19336. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  19337. }
  19338. if (this.matricesWeights) {
  19339. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  19340. }
  19341. if (this.indices) {
  19342. meshOrGeometry.setIndices(this.indices);
  19343. }
  19344. };
  19345. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  19346. if (this.positions) {
  19347. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  19348. }
  19349. if (this.normals) {
  19350. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  19351. }
  19352. if (this.uvs) {
  19353. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  19354. }
  19355. if (this.uv2s) {
  19356. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updateExtends, makeItUnique);
  19357. }
  19358. if (this.colors) {
  19359. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  19360. }
  19361. if (this.matricesIndices) {
  19362. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  19363. }
  19364. if (this.matricesWeights) {
  19365. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  19366. }
  19367. if (this.indices) {
  19368. meshOrGeometry.setIndices(this.indices);
  19369. }
  19370. };
  19371. VertexData.prototype.transform = function (matrix) {
  19372. var transformed = BABYLON.Vector3.Zero();
  19373. if (this.positions) {
  19374. var position = BABYLON.Vector3.Zero();
  19375. for (var index = 0; index < this.positions.length; index += 3) {
  19376. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  19377. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  19378. this.positions[index] = transformed.x;
  19379. this.positions[index + 1] = transformed.y;
  19380. this.positions[index + 2] = transformed.z;
  19381. }
  19382. }
  19383. if (this.normals) {
  19384. var normal = BABYLON.Vector3.Zero();
  19385. for (index = 0; index < this.normals.length; index += 3) {
  19386. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  19387. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  19388. this.normals[index] = transformed.x;
  19389. this.normals[index + 1] = transformed.y;
  19390. this.normals[index + 2] = transformed.z;
  19391. }
  19392. }
  19393. };
  19394. VertexData.prototype.merge = function (other) {
  19395. if (other.indices) {
  19396. if (!this.indices) {
  19397. this.indices = [];
  19398. }
  19399. var offset = this.positions ? this.positions.length / 3 : 0;
  19400. for (var index = 0; index < other.indices.length; index++) {
  19401. this.indices.push(other.indices[index] + offset);
  19402. }
  19403. }
  19404. if (other.positions) {
  19405. if (!this.positions) {
  19406. this.positions = [];
  19407. }
  19408. for (index = 0; index < other.positions.length; index++) {
  19409. this.positions.push(other.positions[index]);
  19410. }
  19411. }
  19412. if (other.normals) {
  19413. if (!this.normals) {
  19414. this.normals = [];
  19415. }
  19416. for (index = 0; index < other.normals.length; index++) {
  19417. this.normals.push(other.normals[index]);
  19418. }
  19419. }
  19420. if (other.uvs) {
  19421. if (!this.uvs) {
  19422. this.uvs = [];
  19423. }
  19424. for (index = 0; index < other.uvs.length; index++) {
  19425. this.uvs.push(other.uvs[index]);
  19426. }
  19427. }
  19428. if (other.uv2s) {
  19429. if (!this.uv2s) {
  19430. this.uv2s = [];
  19431. }
  19432. for (index = 0; index < other.uv2s.length; index++) {
  19433. this.uv2s.push(other.uv2s[index]);
  19434. }
  19435. }
  19436. if (other.matricesIndices) {
  19437. if (!this.matricesIndices) {
  19438. this.matricesIndices = [];
  19439. }
  19440. for (index = 0; index < other.matricesIndices.length; index++) {
  19441. this.matricesIndices.push(other.matricesIndices[index]);
  19442. }
  19443. }
  19444. if (other.matricesWeights) {
  19445. if (!this.matricesWeights) {
  19446. this.matricesWeights = [];
  19447. }
  19448. for (index = 0; index < other.matricesWeights.length; index++) {
  19449. this.matricesWeights.push(other.matricesWeights[index]);
  19450. }
  19451. }
  19452. if (other.colors) {
  19453. if (!this.colors) {
  19454. this.colors = [];
  19455. }
  19456. for (index = 0; index < other.colors.length; index++) {
  19457. this.colors.push(other.colors[index]);
  19458. }
  19459. }
  19460. };
  19461. // Statics
  19462. VertexData.ExtractFromMesh = function (mesh) {
  19463. return VertexData._ExtractFrom(mesh);
  19464. };
  19465. VertexData.ExtractFromGeometry = function (geometry) {
  19466. return VertexData._ExtractFrom(geometry);
  19467. };
  19468. VertexData._ExtractFrom = function (meshOrGeometry) {
  19469. var result = new BABYLON.VertexData();
  19470. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  19471. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19472. }
  19473. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  19474. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19475. }
  19476. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  19477. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind);
  19478. }
  19479. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  19480. result.uv2s = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  19481. }
  19482. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  19483. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  19484. }
  19485. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  19486. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  19487. }
  19488. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  19489. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  19490. }
  19491. result.indices = meshOrGeometry.getIndices();
  19492. return result;
  19493. };
  19494. VertexData.CreateBox = function (size) {
  19495. var normalsSource = [
  19496. new BABYLON.Vector3(0, 0, 1),
  19497. new BABYLON.Vector3(0, 0, -1),
  19498. new BABYLON.Vector3(1, 0, 0),
  19499. new BABYLON.Vector3(-1, 0, 0),
  19500. new BABYLON.Vector3(0, 1, 0),
  19501. new BABYLON.Vector3(0, -1, 0)
  19502. ];
  19503. var indices = [];
  19504. var positions = [];
  19505. var normals = [];
  19506. var uvs = [];
  19507. size = size || 1;
  19508. for (var index = 0; index < normalsSource.length; index++) {
  19509. var normal = normalsSource[index];
  19510. // Get two vectors perpendicular to the face normal and to each other.
  19511. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  19512. var side2 = BABYLON.Vector3.Cross(normal, side1);
  19513. // Six indices (two triangles) per face.
  19514. var verticesLength = positions.length / 3;
  19515. indices.push(verticesLength);
  19516. indices.push(verticesLength + 1);
  19517. indices.push(verticesLength + 2);
  19518. indices.push(verticesLength);
  19519. indices.push(verticesLength + 2);
  19520. indices.push(verticesLength + 3);
  19521. // Four vertices per face.
  19522. var vertex = normal.subtract(side1).subtract(side2).scale(size / 2);
  19523. positions.push(vertex.x, vertex.y, vertex.z);
  19524. normals.push(normal.x, normal.y, normal.z);
  19525. uvs.push(1.0, 1.0);
  19526. vertex = normal.subtract(side1).add(side2).scale(size / 2);
  19527. positions.push(vertex.x, vertex.y, vertex.z);
  19528. normals.push(normal.x, normal.y, normal.z);
  19529. uvs.push(0.0, 1.0);
  19530. vertex = normal.add(side1).add(side2).scale(size / 2);
  19531. positions.push(vertex.x, vertex.y, vertex.z);
  19532. normals.push(normal.x, normal.y, normal.z);
  19533. uvs.push(0.0, 0.0);
  19534. vertex = normal.add(side1).subtract(side2).scale(size / 2);
  19535. positions.push(vertex.x, vertex.y, vertex.z);
  19536. normals.push(normal.x, normal.y, normal.z);
  19537. uvs.push(1.0, 0.0);
  19538. }
  19539. // Result
  19540. var vertexData = new BABYLON.VertexData();
  19541. vertexData.indices = indices;
  19542. vertexData.positions = positions;
  19543. vertexData.normals = normals;
  19544. vertexData.uvs = uvs;
  19545. return vertexData;
  19546. };
  19547. VertexData.CreateSphere = function (segments, diameter) {
  19548. segments = segments || 32;
  19549. diameter = diameter || 1;
  19550. var radius = diameter / 2;
  19551. var totalZRotationSteps = 2 + segments;
  19552. var totalYRotationSteps = 2 * totalZRotationSteps;
  19553. var indices = [];
  19554. var positions = [];
  19555. var normals = [];
  19556. var uvs = [];
  19557. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  19558. var normalizedZ = zRotationStep / totalZRotationSteps;
  19559. var angleZ = (normalizedZ * Math.PI);
  19560. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  19561. var normalizedY = yRotationStep / totalYRotationSteps;
  19562. var angleY = normalizedY * Math.PI * 2;
  19563. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  19564. var rotationY = BABYLON.Matrix.RotationY(angleY);
  19565. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  19566. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  19567. var vertex = complete.scale(radius);
  19568. var normal = BABYLON.Vector3.Normalize(vertex);
  19569. positions.push(vertex.x, vertex.y, vertex.z);
  19570. normals.push(normal.x, normal.y, normal.z);
  19571. uvs.push(normalizedZ, normalizedY);
  19572. }
  19573. if (zRotationStep > 0) {
  19574. var verticesCount = positions.length / 3;
  19575. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  19576. indices.push((firstIndex));
  19577. indices.push((firstIndex + 1));
  19578. indices.push(firstIndex + totalYRotationSteps + 1);
  19579. indices.push((firstIndex + totalYRotationSteps + 1));
  19580. indices.push((firstIndex + 1));
  19581. indices.push((firstIndex + totalYRotationSteps + 2));
  19582. }
  19583. }
  19584. }
  19585. // Result
  19586. var vertexData = new BABYLON.VertexData();
  19587. vertexData.indices = indices;
  19588. vertexData.positions = positions;
  19589. vertexData.normals = normals;
  19590. vertexData.uvs = uvs;
  19591. return vertexData;
  19592. };
  19593. VertexData.CreateCylinder = function (height, diameterTop, diameterBottom, tessellation, subdivisions) {
  19594. if (typeof subdivisions === "undefined") { subdivisions = 1; }
  19595. var radiusTop = diameterTop / 2;
  19596. var radiusBottom = diameterBottom / 2;
  19597. var indices = [];
  19598. var positions = [];
  19599. var normals = [];
  19600. var uvs = [];
  19601. height = height || 1;
  19602. diameterTop = diameterTop || 0.5;
  19603. diameterBottom = diameterBottom || 1;
  19604. tessellation = tessellation || 16;
  19605. subdivisions = subdivisions || 1;
  19606. subdivisions = (subdivisions < 1) ? 1 : subdivisions;
  19607. var getCircleVector = function (i) {
  19608. var angle = (i * 2.0 * Math.PI / tessellation);
  19609. var dx = Math.cos(angle);
  19610. var dz = Math.sin(angle);
  19611. return new BABYLON.Vector3(dx, 0, dz);
  19612. };
  19613. var createCylinderCap = function (isTop) {
  19614. var radius = isTop ? radiusTop : radiusBottom;
  19615. if (radius == 0) {
  19616. return;
  19617. }
  19618. var vbase = positions.length / 3;
  19619. var offset = new BABYLON.Vector3(0, height / 2, 0);
  19620. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  19621. if (!isTop) {
  19622. offset.scaleInPlace(-1);
  19623. textureScale.x = -textureScale.x;
  19624. }
  19625. for (i = 0; i < tessellation; i++) {
  19626. var circleVector = getCircleVector(i);
  19627. var position = circleVector.scale(radius).add(offset);
  19628. var textureCoordinate = new BABYLON.Vector2(circleVector.x * textureScale.x + 0.5, circleVector.z * textureScale.y + 0.5);
  19629. positions.push(position.x, position.y, position.z);
  19630. uvs.push(textureCoordinate.x, textureCoordinate.y);
  19631. }
  19632. for (var i = 0; i < tessellation - 2; i++) {
  19633. if (!isTop) {
  19634. indices.push(vbase);
  19635. indices.push(vbase + (i + 2) % tessellation);
  19636. indices.push(vbase + (i + 1) % tessellation);
  19637. } else {
  19638. indices.push(vbase);
  19639. indices.push(vbase + (i + 1) % tessellation);
  19640. indices.push(vbase + (i + 2) % tessellation);
  19641. }
  19642. }
  19643. };
  19644. var base = new BABYLON.Vector3(0, -1, 0).scale(height / 2);
  19645. var offset = new BABYLON.Vector3(0, 1, 0).scale(height / subdivisions);
  19646. var stride = tessellation + 1;
  19647. for (var i = 0; i <= tessellation; i++) {
  19648. var circleVector = getCircleVector(i);
  19649. var textureCoordinate = new BABYLON.Vector2(i / tessellation, 0);
  19650. var position, radius = radiusBottom;
  19651. for (var s = 0; s <= subdivisions; s++) {
  19652. // Update variables
  19653. position = circleVector.scale(radius);
  19654. position.addInPlace(base.add(offset.scale(s)));
  19655. textureCoordinate.y += 1 / subdivisions;
  19656. radius += (radiusTop - radiusBottom) / subdivisions;
  19657. // Push in arrays
  19658. positions.push(position.x, position.y, position.z);
  19659. uvs.push(textureCoordinate.x, textureCoordinate.y);
  19660. }
  19661. }
  19662. subdivisions += 1;
  19663. for (var s = 0; s < subdivisions - 1; s++) {
  19664. for (var i = 0; i <= tessellation; i++) {
  19665. indices.push(i * subdivisions + s);
  19666. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  19667. indices.push(i * subdivisions + (s + 1));
  19668. indices.push(i * subdivisions + (s + 1));
  19669. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  19670. indices.push((i * subdivisions + (s + subdivisions + 1)) % (stride * subdivisions));
  19671. }
  19672. }
  19673. // Create flat triangle fan caps to seal the top and bottom.
  19674. createCylinderCap(true);
  19675. createCylinderCap(false);
  19676. // Normals
  19677. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  19678. // Result
  19679. var vertexData = new BABYLON.VertexData();
  19680. vertexData.indices = indices;
  19681. vertexData.positions = positions;
  19682. vertexData.normals = normals;
  19683. vertexData.uvs = uvs;
  19684. return vertexData;
  19685. };
  19686. VertexData.CreateTorus = function (diameter, thickness, tessellation) {
  19687. var indices = [];
  19688. var positions = [];
  19689. var normals = [];
  19690. var uvs = [];
  19691. diameter = diameter || 1;
  19692. thickness = thickness || 0.5;
  19693. tessellation = tessellation || 16;
  19694. var stride = tessellation + 1;
  19695. for (var i = 0; i <= tessellation; i++) {
  19696. var u = i / tessellation;
  19697. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  19698. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  19699. for (var j = 0; j <= tessellation; j++) {
  19700. var v = 1 - j / tessellation;
  19701. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  19702. var dx = Math.cos(innerAngle);
  19703. var dy = Math.sin(innerAngle);
  19704. // Create a vertex.
  19705. var normal = new BABYLON.Vector3(dx, dy, 0);
  19706. var position = normal.scale(thickness / 2);
  19707. var textureCoordinate = new BABYLON.Vector2(u, v);
  19708. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  19709. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  19710. positions.push(position.x, position.y, position.z);
  19711. normals.push(normal.x, normal.y, normal.z);
  19712. uvs.push(textureCoordinate.x, textureCoordinate.y);
  19713. // And create indices for two triangles.
  19714. var nextI = (i + 1) % stride;
  19715. var nextJ = (j + 1) % stride;
  19716. indices.push(i * stride + j);
  19717. indices.push(i * stride + nextJ);
  19718. indices.push(nextI * stride + j);
  19719. indices.push(i * stride + nextJ);
  19720. indices.push(nextI * stride + nextJ);
  19721. indices.push(nextI * stride + j);
  19722. }
  19723. }
  19724. // Result
  19725. var vertexData = new BABYLON.VertexData();
  19726. vertexData.indices = indices;
  19727. vertexData.positions = positions;
  19728. vertexData.normals = normals;
  19729. vertexData.uvs = uvs;
  19730. return vertexData;
  19731. };
  19732. VertexData.CreateLines = function (points) {
  19733. var indices = [];
  19734. var positions = [];
  19735. for (var index = 0; index < points.length; index++) {
  19736. positions.push(points[index].x, points[index].y, points[index].z);
  19737. if (index > 0) {
  19738. indices.push(index - 1);
  19739. indices.push(index);
  19740. }
  19741. }
  19742. // Result
  19743. var vertexData = new BABYLON.VertexData();
  19744. vertexData.indices = indices;
  19745. vertexData.positions = positions;
  19746. return vertexData;
  19747. };
  19748. VertexData.CreateGround = function (width, height, subdivisions) {
  19749. var indices = [];
  19750. var positions = [];
  19751. var normals = [];
  19752. var uvs = [];
  19753. var row, col;
  19754. width = width || 1;
  19755. height = height || 1;
  19756. subdivisions = subdivisions || 1;
  19757. for (row = 0; row <= subdivisions; row++) {
  19758. for (col = 0; col <= subdivisions; col++) {
  19759. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  19760. var normal = new BABYLON.Vector3(0, 1.0, 0);
  19761. positions.push(position.x, position.y, position.z);
  19762. normals.push(normal.x, normal.y, normal.z);
  19763. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  19764. }
  19765. }
  19766. for (row = 0; row < subdivisions; row++) {
  19767. for (col = 0; col < subdivisions; col++) {
  19768. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  19769. indices.push(col + 1 + row * (subdivisions + 1));
  19770. indices.push(col + row * (subdivisions + 1));
  19771. indices.push(col + (row + 1) * (subdivisions + 1));
  19772. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  19773. indices.push(col + row * (subdivisions + 1));
  19774. }
  19775. }
  19776. // Result
  19777. var vertexData = new BABYLON.VertexData();
  19778. vertexData.indices = indices;
  19779. vertexData.positions = positions;
  19780. vertexData.normals = normals;
  19781. vertexData.uvs = uvs;
  19782. return vertexData;
  19783. };
  19784. VertexData.CreateTiledGround = function (xmin, zmin, xmax, zmax, subdivisions, precision) {
  19785. if (typeof subdivisions === "undefined") { subdivisions = { w: 1, h: 1 }; }
  19786. if (typeof precision === "undefined") { precision = { w: 1, h: 1 }; }
  19787. var indices = [];
  19788. var positions = [];
  19789. var normals = [];
  19790. var uvs = [];
  19791. var row, col, tileRow, tileCol;
  19792. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  19793. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  19794. precision.w = (precision.w < 1) ? 1 : precision.w;
  19795. precision.h = (precision.h < 1) ? 1 : precision.h;
  19796. var tileSize = {
  19797. 'w': (xmax - xmin) / subdivisions.w,
  19798. 'h': (zmax - zmin) / subdivisions.h
  19799. };
  19800. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  19801. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  19802. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  19803. }
  19804. }
  19805. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  19806. // Indices
  19807. var base = positions.length / 3;
  19808. var rowLength = precision.w + 1;
  19809. for (row = 0; row < precision.h; row++) {
  19810. for (col = 0; col < precision.w; col++) {
  19811. var square = [
  19812. base + col + row * rowLength,
  19813. base + (col + 1) + row * rowLength,
  19814. base + (col + 1) + (row + 1) * rowLength,
  19815. base + col + (row + 1) * rowLength
  19816. ];
  19817. indices.push(square[1]);
  19818. indices.push(square[2]);
  19819. indices.push(square[3]);
  19820. indices.push(square[0]);
  19821. indices.push(square[1]);
  19822. indices.push(square[3]);
  19823. }
  19824. }
  19825. // Position, normals and uvs
  19826. var position = BABYLON.Vector3.Zero();
  19827. var normal = new BABYLON.Vector3(0, 1.0, 0);
  19828. for (row = 0; row <= precision.h; row++) {
  19829. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  19830. for (col = 0; col <= precision.w; col++) {
  19831. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  19832. position.y = 0;
  19833. positions.push(position.x, position.y, position.z);
  19834. normals.push(normal.x, normal.y, normal.z);
  19835. uvs.push(col / precision.w, row / precision.h);
  19836. }
  19837. }
  19838. }
  19839. // Result
  19840. var vertexData = new BABYLON.VertexData();
  19841. vertexData.indices = indices;
  19842. vertexData.positions = positions;
  19843. vertexData.normals = normals;
  19844. vertexData.uvs = uvs;
  19845. return vertexData;
  19846. };
  19847. VertexData.CreateGroundFromHeightMap = function (width, height, subdivisions, minHeight, maxHeight, buffer, bufferWidth, bufferHeight) {
  19848. var indices = [];
  19849. var positions = [];
  19850. var normals = [];
  19851. var uvs = [];
  19852. var row, col;
  19853. for (row = 0; row <= subdivisions; row++) {
  19854. for (col = 0; col <= subdivisions; col++) {
  19855. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  19856. // Compute height
  19857. var heightMapX = (((position.x + width / 2) / width) * (bufferWidth - 1)) | 0;
  19858. var heightMapY = ((1.0 - (position.z + height / 2) / height) * (bufferHeight - 1)) | 0;
  19859. var pos = (heightMapX + heightMapY * bufferWidth) * 4;
  19860. var r = buffer[pos] / 255.0;
  19861. var g = buffer[pos + 1] / 255.0;
  19862. var b = buffer[pos + 2] / 255.0;
  19863. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  19864. position.y = minHeight + (maxHeight - minHeight) * gradient;
  19865. // Add vertex
  19866. positions.push(position.x, position.y, position.z);
  19867. normals.push(0, 0, 0);
  19868. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  19869. }
  19870. }
  19871. for (row = 0; row < subdivisions; row++) {
  19872. for (col = 0; col < subdivisions; col++) {
  19873. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  19874. indices.push(col + 1 + row * (subdivisions + 1));
  19875. indices.push(col + row * (subdivisions + 1));
  19876. indices.push(col + (row + 1) * (subdivisions + 1));
  19877. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  19878. indices.push(col + row * (subdivisions + 1));
  19879. }
  19880. }
  19881. // Normals
  19882. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  19883. // Result
  19884. var vertexData = new BABYLON.VertexData();
  19885. vertexData.indices = indices;
  19886. vertexData.positions = positions;
  19887. vertexData.normals = normals;
  19888. vertexData.uvs = uvs;
  19889. return vertexData;
  19890. };
  19891. VertexData.CreatePlane = function (size) {
  19892. var indices = [];
  19893. var positions = [];
  19894. var normals = [];
  19895. var uvs = [];
  19896. size = size || 1;
  19897. // Vertices
  19898. var halfSize = size / 2.0;
  19899. positions.push(-halfSize, -halfSize, 0);
  19900. normals.push(0, 0, -1.0);
  19901. uvs.push(0.0, 0.0);
  19902. positions.push(halfSize, -halfSize, 0);
  19903. normals.push(0, 0, -1.0);
  19904. uvs.push(1.0, 0.0);
  19905. positions.push(halfSize, halfSize, 0);
  19906. normals.push(0, 0, -1.0);
  19907. uvs.push(1.0, 1.0);
  19908. positions.push(-halfSize, halfSize, 0);
  19909. normals.push(0, 0, -1.0);
  19910. uvs.push(0.0, 1.0);
  19911. // Indices
  19912. indices.push(0);
  19913. indices.push(1);
  19914. indices.push(2);
  19915. indices.push(0);
  19916. indices.push(2);
  19917. indices.push(3);
  19918. // Result
  19919. var vertexData = new BABYLON.VertexData();
  19920. vertexData.indices = indices;
  19921. vertexData.positions = positions;
  19922. vertexData.normals = normals;
  19923. vertexData.uvs = uvs;
  19924. return vertexData;
  19925. };
  19926. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  19927. VertexData.CreateTorusKnot = function (radius, tube, radialSegments, tubularSegments, p, q) {
  19928. var indices = [];
  19929. var positions = [];
  19930. var normals = [];
  19931. var uvs = [];
  19932. radius = radius || 2;
  19933. tube = tube || 0.5;
  19934. radialSegments = radialSegments || 32;
  19935. tubularSegments = tubularSegments || 32;
  19936. p = p || 2;
  19937. q = q || 3;
  19938. // Helper
  19939. var getPos = function (angle) {
  19940. var cu = Math.cos(angle);
  19941. var su = Math.sin(angle);
  19942. var quOverP = q / p * angle;
  19943. var cs = Math.cos(quOverP);
  19944. var tx = radius * (2 + cs) * 0.5 * cu;
  19945. var ty = radius * (2 + cs) * su * 0.5;
  19946. var tz = radius * Math.sin(quOverP) * 0.5;
  19947. return new BABYLON.Vector3(tx, ty, tz);
  19948. };
  19949. for (var i = 0; i <= radialSegments; i++) {
  19950. var modI = i % radialSegments;
  19951. var u = modI / radialSegments * 2 * p * Math.PI;
  19952. var p1 = getPos(u);
  19953. var p2 = getPos(u + 0.01);
  19954. var tang = p2.subtract(p1);
  19955. var n = p2.add(p1);
  19956. var bitan = BABYLON.Vector3.Cross(tang, n);
  19957. n = BABYLON.Vector3.Cross(bitan, tang);
  19958. bitan.normalize();
  19959. n.normalize();
  19960. for (var j = 0; j < tubularSegments; j++) {
  19961. var modJ = j % tubularSegments;
  19962. var v = modJ / tubularSegments * 2 * Math.PI;
  19963. var cx = -tube * Math.cos(v);
  19964. var cy = tube * Math.sin(v);
  19965. positions.push(p1.x + cx * n.x + cy * bitan.x);
  19966. positions.push(p1.y + cx * n.y + cy * bitan.y);
  19967. positions.push(p1.z + cx * n.z + cy * bitan.z);
  19968. uvs.push(i / radialSegments);
  19969. uvs.push(j / tubularSegments);
  19970. }
  19971. }
  19972. for (i = 0; i < radialSegments; i++) {
  19973. for (j = 0; j < tubularSegments; j++) {
  19974. var jNext = (j + 1) % tubularSegments;
  19975. var a = i * tubularSegments + j;
  19976. var b = (i + 1) * tubularSegments + j;
  19977. var c = (i + 1) * tubularSegments + jNext;
  19978. var d = i * tubularSegments + jNext;
  19979. indices.push(d);
  19980. indices.push(b);
  19981. indices.push(a);
  19982. indices.push(d);
  19983. indices.push(c);
  19984. indices.push(b);
  19985. }
  19986. }
  19987. // Normals
  19988. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  19989. // Result
  19990. var vertexData = new BABYLON.VertexData();
  19991. vertexData.indices = indices;
  19992. vertexData.positions = positions;
  19993. vertexData.normals = normals;
  19994. vertexData.uvs = uvs;
  19995. return vertexData;
  19996. };
  19997. // Tools
  19998. VertexData.ComputeNormals = function (positions, indices, normals) {
  19999. var positionVectors = [];
  20000. var facesOfVertices = [];
  20001. var index;
  20002. for (index = 0; index < positions.length; index += 3) {
  20003. var vector3 = new BABYLON.Vector3(positions[index], positions[index + 1], positions[index + 2]);
  20004. positionVectors.push(vector3);
  20005. facesOfVertices.push([]);
  20006. }
  20007. // Compute normals
  20008. var facesNormals = [];
  20009. for (index = 0; index < indices.length / 3; index++) {
  20010. var i1 = indices[index * 3];
  20011. var i2 = indices[index * 3 + 1];
  20012. var i3 = indices[index * 3 + 2];
  20013. var p1 = positionVectors[i1];
  20014. var p2 = positionVectors[i2];
  20015. var p3 = positionVectors[i3];
  20016. var p1p2 = p1.subtract(p2);
  20017. var p3p2 = p3.subtract(p2);
  20018. facesNormals[index] = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  20019. facesOfVertices[i1].push(index);
  20020. facesOfVertices[i2].push(index);
  20021. facesOfVertices[i3].push(index);
  20022. }
  20023. for (index = 0; index < positionVectors.length; index++) {
  20024. var faces = facesOfVertices[index];
  20025. var normal = BABYLON.Vector3.Zero();
  20026. for (var faceIndex = 0; faceIndex < faces.length; faceIndex++) {
  20027. normal.addInPlace(facesNormals[faces[faceIndex]]);
  20028. }
  20029. normal = BABYLON.Vector3.Normalize(normal.scale(1.0 / faces.length));
  20030. normals[index * 3] = normal.x;
  20031. normals[index * 3 + 1] = normal.y;
  20032. normals[index * 3 + 2] = normal.z;
  20033. }
  20034. };
  20035. return VertexData;
  20036. })();
  20037. BABYLON.VertexData = VertexData;
  20038. })(BABYLON || (BABYLON = {}));
  20039. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  20040. var BABYLON;
  20041. (function (BABYLON) {
  20042. var buildCamera = function (that, name) {
  20043. that._leftCamera.isIntermediate = true;
  20044. that.subCameras.push(that._leftCamera);
  20045. that.subCameras.push(that._rightCamera);
  20046. that._leftTexture = new BABYLON.PassPostProcess(name + "_leftTexture", 1.0, that._leftCamera);
  20047. that._anaglyphPostProcess = new BABYLON.AnaglyphPostProcess(name + "_anaglyph", 1.0, that._rightCamera);
  20048. that._anaglyphPostProcess.onApply = function (effect) {
  20049. effect.setTextureFromPostProcess("leftSampler", that._leftTexture);
  20050. };
  20051. that._update();
  20052. };
  20053. var AnaglyphArcRotateCamera = (function (_super) {
  20054. __extends(AnaglyphArcRotateCamera, _super);
  20055. // ANY
  20056. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, eyeSpace, scene) {
  20057. _super.call(this, name, alpha, beta, radius, target, scene);
  20058. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  20059. this._leftCamera = new BABYLON.ArcRotateCamera(name + "_left", alpha - this._eyeSpace, beta, radius, target, scene);
  20060. this._rightCamera = new BABYLON.ArcRotateCamera(name + "_right", alpha + this._eyeSpace, beta, radius, target, scene);
  20061. buildCamera(this, name);
  20062. }
  20063. AnaglyphArcRotateCamera.prototype._update = function () {
  20064. this._updateCamera(this._leftCamera);
  20065. this._updateCamera(this._rightCamera);
  20066. this._leftCamera.alpha = this.alpha - this._eyeSpace;
  20067. this._rightCamera.alpha = this.alpha + this._eyeSpace;
  20068. _super.prototype._update.call(this);
  20069. };
  20070. AnaglyphArcRotateCamera.prototype._updateCamera = function (camera) {
  20071. camera.beta = this.beta;
  20072. camera.radius = this.radius;
  20073. camera.minZ = this.minZ;
  20074. camera.maxZ = this.maxZ;
  20075. camera.fov = this.fov;
  20076. camera.target = this.target;
  20077. };
  20078. return AnaglyphArcRotateCamera;
  20079. })(BABYLON.ArcRotateCamera);
  20080. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  20081. var AnaglyphFreeCamera = (function (_super) {
  20082. __extends(AnaglyphFreeCamera, _super);
  20083. function AnaglyphFreeCamera(name, position, eyeSpace, scene) {
  20084. _super.call(this, name, position, scene);
  20085. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  20086. this._transformMatrix = new BABYLON.Matrix();
  20087. this._leftCamera = new BABYLON.FreeCamera(name + "_left", position.clone(), scene);
  20088. this._rightCamera = new BABYLON.FreeCamera(name + "_right", position.clone(), scene);
  20089. buildCamera(this, name);
  20090. }
  20091. AnaglyphFreeCamera.prototype._getSubCameraPosition = function (eyeSpace, result) {
  20092. var target = this.getTarget();
  20093. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(eyeSpace), this._transformMatrix);
  20094. this._transformMatrix = this._transformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  20095. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._transformMatrix, result);
  20096. };
  20097. AnaglyphFreeCamera.prototype._update = function () {
  20098. this._getSubCameraPosition(-this._eyeSpace, this._leftCamera.position);
  20099. this._getSubCameraPosition(this._eyeSpace, this._rightCamera.position);
  20100. this._updateCamera(this._leftCamera);
  20101. this._updateCamera(this._rightCamera);
  20102. _super.prototype._update.call(this);
  20103. };
  20104. AnaglyphFreeCamera.prototype._updateCamera = function (camera) {
  20105. camera.minZ = this.minZ;
  20106. camera.maxZ = this.maxZ;
  20107. camera.fov = this.fov;
  20108. camera.viewport = this.viewport;
  20109. camera.setTarget(this.getTarget());
  20110. };
  20111. return AnaglyphFreeCamera;
  20112. })(BABYLON.FreeCamera);
  20113. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  20114. })(BABYLON || (BABYLON = {}));
  20115. //# sourceMappingURL=babylon.anaglyphCamera.js.map
  20116. var BABYLON;
  20117. (function (BABYLON) {
  20118. var AnaglyphPostProcess = (function (_super) {
  20119. __extends(AnaglyphPostProcess, _super);
  20120. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  20121. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  20122. }
  20123. return AnaglyphPostProcess;
  20124. })(BABYLON.PostProcess);
  20125. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  20126. })(BABYLON || (BABYLON = {}));
  20127. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  20128. var BABYLON;
  20129. (function (BABYLON) {
  20130. var Tags = (function () {
  20131. function Tags() {
  20132. }
  20133. Tags.EnableFor = function (obj) {
  20134. obj._tags = obj._tags || {};
  20135. obj.hasTags = function () {
  20136. return Tags.HasTags(obj);
  20137. };
  20138. obj.addTags = function (tagsString) {
  20139. return Tags.AddTagsTo(obj, tagsString);
  20140. };
  20141. obj.removeTags = function (tagsString) {
  20142. return Tags.RemoveTagsFrom(obj, tagsString);
  20143. };
  20144. obj.matchesTagsQuery = function (tagsQuery) {
  20145. return Tags.MatchesQuery(obj, tagsQuery);
  20146. };
  20147. };
  20148. Tags.DisableFor = function (obj) {
  20149. delete obj._tags;
  20150. delete obj.hasTags;
  20151. delete obj.addTags;
  20152. delete obj.removeTags;
  20153. delete obj.matchesTagsQuery;
  20154. };
  20155. Tags.HasTags = function (obj) {
  20156. if (!obj._tags) {
  20157. return false;
  20158. }
  20159. return !BABYLON.Tools.IsEmpty(obj._tags);
  20160. };
  20161. Tags.GetTags = function (obj) {
  20162. if (!obj._tags) {
  20163. return null;
  20164. }
  20165. return obj._tags;
  20166. };
  20167. // the tags 'true' and 'false' are reserved and cannot be used as tags
  20168. // a tag cannot start with '||', '&&', and '!'
  20169. // it cannot contain whitespaces
  20170. Tags.AddTagsTo = function (obj, tagsString) {
  20171. if (!tagsString) {
  20172. return;
  20173. }
  20174. var tags = tagsString.split(" ");
  20175. for (var t in tags) {
  20176. Tags._AddTagTo(obj, tags[t]);
  20177. }
  20178. };
  20179. Tags._AddTagTo = function (obj, tag) {
  20180. tag = tag.trim();
  20181. if (tag === "" || tag === "true" || tag === "false") {
  20182. return;
  20183. }
  20184. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  20185. return;
  20186. }
  20187. Tags.EnableFor(obj);
  20188. obj._tags[tag] = true;
  20189. };
  20190. Tags.RemoveTagsFrom = function (obj, tagsString) {
  20191. if (!Tags.HasTags(obj)) {
  20192. return;
  20193. }
  20194. var tags = tagsString.split(" ");
  20195. for (var t in tags) {
  20196. Tags._RemoveTagFrom(obj, tags[t]);
  20197. }
  20198. };
  20199. Tags._RemoveTagFrom = function (obj, tag) {
  20200. delete obj._tags[tag];
  20201. };
  20202. Tags.MatchesQuery = function (obj, tagsQuery) {
  20203. if (tagsQuery === undefined) {
  20204. return true;
  20205. }
  20206. if (tagsQuery === "") {
  20207. return Tags.HasTags(obj);
  20208. }
  20209. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) {
  20210. return Tags.HasTags(obj) && obj._tags[r];
  20211. });
  20212. };
  20213. return Tags;
  20214. })();
  20215. BABYLON.Tags = Tags;
  20216. })(BABYLON || (BABYLON = {}));
  20217. //# sourceMappingURL=babylon.tags.js.map
  20218. var BABYLON;
  20219. (function (BABYLON) {
  20220. (function (Internals) {
  20221. var AndOrNotEvaluator = (function () {
  20222. function AndOrNotEvaluator() {
  20223. }
  20224. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  20225. if (!query.match(/\([^\(\)]*\)/g)) {
  20226. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  20227. } else {
  20228. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  20229. // remove parenthesis
  20230. r = r.slice(1, r.length - 1);
  20231. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  20232. });
  20233. }
  20234. if (query === "true") {
  20235. return true;
  20236. }
  20237. if (query === "false") {
  20238. return false;
  20239. }
  20240. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  20241. };
  20242. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  20243. evaluateCallback = evaluateCallback || (function (r) {
  20244. return r === "true" ? true : false;
  20245. });
  20246. var result;
  20247. var or = parenthesisContent.split("||");
  20248. for (var i in or) {
  20249. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  20250. var and = ori.split("&&");
  20251. if (and.length > 1) {
  20252. for (var j = 0; j < and.length; ++j) {
  20253. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  20254. if (andj !== "true" && andj !== "false") {
  20255. if (andj[0] === "!") {
  20256. result = !evaluateCallback(andj.substring(1));
  20257. } else {
  20258. result = evaluateCallback(andj);
  20259. }
  20260. } else {
  20261. result = andj === "true" ? true : false;
  20262. }
  20263. if (!result) {
  20264. ori = "false";
  20265. break;
  20266. }
  20267. }
  20268. }
  20269. if (result || ori === "true") {
  20270. result = true;
  20271. break;
  20272. }
  20273. // result equals false (or undefined)
  20274. if (ori !== "true" && ori !== "false") {
  20275. if (ori[0] === "!") {
  20276. result = !evaluateCallback(ori.substring(1));
  20277. } else {
  20278. result = evaluateCallback(ori);
  20279. }
  20280. } else {
  20281. result = ori === "true" ? true : false;
  20282. }
  20283. }
  20284. // the whole parenthesis scope is replaced by 'true' or 'false'
  20285. return result ? "true" : "false";
  20286. };
  20287. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  20288. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  20289. // remove whitespaces
  20290. r = r.replace(/[\s]/g, function () {
  20291. return "";
  20292. });
  20293. return r.length % 2 ? "!" : "";
  20294. });
  20295. booleanString = booleanString.trim();
  20296. if (booleanString === "!true") {
  20297. booleanString = "false";
  20298. } else if (booleanString === "!false") {
  20299. booleanString = "true";
  20300. }
  20301. return booleanString;
  20302. };
  20303. return AndOrNotEvaluator;
  20304. })();
  20305. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  20306. })(BABYLON.Internals || (BABYLON.Internals = {}));
  20307. var Internals = BABYLON.Internals;
  20308. })(BABYLON || (BABYLON = {}));
  20309. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  20310. var BABYLON;
  20311. (function (BABYLON) {
  20312. var PostProcessRenderPass = (function () {
  20313. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  20314. this._enabled = true;
  20315. this._refCount = 0;
  20316. this._name = name;
  20317. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  20318. this.setRenderList(renderList);
  20319. this._renderTexture.onBeforeRender = beforeRender;
  20320. this._renderTexture.onAfterRender = afterRender;
  20321. this._scene = scene;
  20322. this._renderList = renderList;
  20323. }
  20324. // private
  20325. PostProcessRenderPass.prototype._incRefCount = function () {
  20326. if (this._refCount === 0) {
  20327. this._scene.customRenderTargets.push(this._renderTexture);
  20328. }
  20329. return ++this._refCount;
  20330. };
  20331. PostProcessRenderPass.prototype._decRefCount = function () {
  20332. this._refCount--;
  20333. if (this._refCount <= 0) {
  20334. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  20335. }
  20336. return this._refCount;
  20337. };
  20338. PostProcessRenderPass.prototype._update = function () {
  20339. this.setRenderList(this._renderList);
  20340. };
  20341. // public
  20342. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  20343. this._renderTexture.renderList = renderList;
  20344. };
  20345. PostProcessRenderPass.prototype.getRenderTexture = function () {
  20346. return this._renderTexture;
  20347. };
  20348. return PostProcessRenderPass;
  20349. })();
  20350. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  20351. })(BABYLON || (BABYLON = {}));
  20352. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  20353. var BABYLON;
  20354. (function (BABYLON) {
  20355. var PostProcessRenderEffect = (function () {
  20356. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  20357. this._engine = engine;
  20358. this._name = name;
  20359. this._singleInstance = singleInstance || true;
  20360. this._getPostProcess = getPostProcess;
  20361. this._cameras = [];
  20362. this._indicesForCamera = [];
  20363. this._postProcesses = {};
  20364. this._renderPasses = {};
  20365. this._renderEffectAsPasses = {};
  20366. }
  20367. PostProcessRenderEffect.prototype._update = function () {
  20368. for (var renderPassName in this._renderPasses) {
  20369. this._renderPasses[renderPassName]._update();
  20370. }
  20371. };
  20372. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  20373. this._renderPasses[renderPass._name] = renderPass;
  20374. this._linkParameters();
  20375. };
  20376. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  20377. delete this._renderPasses[renderPass._name];
  20378. this._linkParameters();
  20379. };
  20380. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  20381. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  20382. this._linkParameters();
  20383. };
  20384. PostProcessRenderEffect.prototype.getPass = function (passName) {
  20385. for (var renderPassName in this._renderPasses) {
  20386. if (renderPassName === passName) {
  20387. return this._renderPasses[passName];
  20388. }
  20389. }
  20390. };
  20391. PostProcessRenderEffect.prototype.emptyPasses = function () {
  20392. this._renderPasses = {};
  20393. this._linkParameters();
  20394. };
  20395. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  20396. var cameraKey;
  20397. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  20398. for (var i = 0; i < _cam.length; i++) {
  20399. var camera = _cam[i];
  20400. var cameraName = camera.name;
  20401. if (this._singleInstance) {
  20402. cameraKey = 0;
  20403. } else {
  20404. cameraKey = cameraName;
  20405. }
  20406. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  20407. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  20408. if (!this._indicesForCamera[cameraName]) {
  20409. this._indicesForCamera[cameraName] = [];
  20410. }
  20411. this._indicesForCamera[cameraName].push(index);
  20412. if (this._cameras.indexOf(camera) === -1) {
  20413. this._cameras[cameraName] = camera;
  20414. }
  20415. for (var passName in this._renderPasses) {
  20416. this._renderPasses[passName]._incRefCount();
  20417. }
  20418. }
  20419. this._linkParameters();
  20420. };
  20421. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  20422. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  20423. for (var i = 0; i < _cam.length; i++) {
  20424. var camera = _cam[i];
  20425. var cameraName = camera.name;
  20426. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  20427. var index = this._cameras.indexOf(cameraName);
  20428. this._indicesForCamera.splice(index, 1);
  20429. this._cameras.splice(index, 1);
  20430. for (var passName in this._renderPasses) {
  20431. this._renderPasses[passName]._decRefCount();
  20432. }
  20433. }
  20434. };
  20435. PostProcessRenderEffect.prototype._enable = function (cameras) {
  20436. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  20437. for (var i = 0; i < _cam.length; i++) {
  20438. var camera = _cam[i];
  20439. var cameraName = camera.name;
  20440. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  20441. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  20442. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  20443. }
  20444. }
  20445. for (var passName in this._renderPasses) {
  20446. this._renderPasses[passName]._incRefCount();
  20447. }
  20448. }
  20449. };
  20450. PostProcessRenderEffect.prototype._disable = function (cameras) {
  20451. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  20452. for (var i = 0; i < _cam.length; i++) {
  20453. var camera = _cam[i];
  20454. var cameraName = camera.Name;
  20455. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  20456. for (var passName in this._renderPasses) {
  20457. this._renderPasses[passName]._decRefCount();
  20458. }
  20459. }
  20460. };
  20461. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  20462. if (this._singleInstance) {
  20463. return this._postProcesses[0];
  20464. } else {
  20465. return this._postProcesses[camera.name];
  20466. }
  20467. };
  20468. PostProcessRenderEffect.prototype._linkParameters = function () {
  20469. var _this = this;
  20470. for (var index in this._postProcesses) {
  20471. if (this.applyParameters) {
  20472. this.applyParameters(this._postProcesses[index]);
  20473. }
  20474. this._postProcesses[index].onBeforeRender = function (effect) {
  20475. _this._linkTextures(effect);
  20476. };
  20477. }
  20478. };
  20479. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  20480. for (var renderPassName in this._renderPasses) {
  20481. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  20482. }
  20483. for (var renderEffectName in this._renderEffectAsPasses) {
  20484. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  20485. }
  20486. };
  20487. return PostProcessRenderEffect;
  20488. })();
  20489. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  20490. })(BABYLON || (BABYLON = {}));
  20491. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  20492. var BABYLON;
  20493. (function (BABYLON) {
  20494. var PostProcessRenderPipeline = (function () {
  20495. function PostProcessRenderPipeline(engine, name) {
  20496. this._engine = engine;
  20497. this._name = name;
  20498. this._renderEffects = {};
  20499. this._renderEffectsForIsolatedPass = {};
  20500. this._cameras = [];
  20501. }
  20502. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  20503. this._renderEffects[renderEffect._name] = renderEffect;
  20504. };
  20505. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  20506. var renderEffects = this._renderEffects[renderEffectName];
  20507. if (!renderEffects) {
  20508. return;
  20509. }
  20510. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  20511. };
  20512. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  20513. var renderEffects = this._renderEffects[renderEffectName];
  20514. if (!renderEffects) {
  20515. return;
  20516. }
  20517. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  20518. };
  20519. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  20520. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  20521. var indicesToDelete = [];
  20522. for (var i = 0; i < _cam.length; i++) {
  20523. var camera = _cam[i];
  20524. var cameraName = camera.name;
  20525. if (this._cameras.indexOf(camera) === -1) {
  20526. this._cameras[cameraName] = camera;
  20527. } else if (unique) {
  20528. indicesToDelete.push(i);
  20529. }
  20530. }
  20531. for (var i = 0; i < indicesToDelete.length; i++) {
  20532. cameras.splice(indicesToDelete[i], 1);
  20533. }
  20534. for (var renderEffectName in this._renderEffects) {
  20535. this._renderEffects[renderEffectName]._attachCameras(_cam);
  20536. }
  20537. };
  20538. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  20539. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  20540. for (var renderEffectName in this._renderEffects) {
  20541. this._renderEffects[renderEffectName]._detachCameras(_cam);
  20542. }
  20543. for (var i = 0; i < _cam.length; i++) {
  20544. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  20545. }
  20546. };
  20547. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  20548. var _this = this;
  20549. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  20550. var pass = null;
  20551. for (var renderEffectName in this._renderEffects) {
  20552. pass = this._renderEffects[renderEffectName].getPass(passName);
  20553. if (pass != null) {
  20554. break;
  20555. }
  20556. }
  20557. if (pass === null) {
  20558. return;
  20559. }
  20560. for (var renderEffectName in this._renderEffects) {
  20561. this._renderEffects[renderEffectName]._disable(_cam);
  20562. }
  20563. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  20564. for (var i = 0; i < _cam.length; i++) {
  20565. var camera = _cam[i];
  20566. var cameraName = camera.name;
  20567. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  20568. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  20569. });
  20570. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  20571. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  20572. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  20573. }
  20574. };
  20575. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  20576. var _this = this;
  20577. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  20578. for (var i = 0; i < _cam.length; i++) {
  20579. var camera = _cam[i];
  20580. var cameraName = camera.name;
  20581. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  20582. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  20583. });
  20584. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  20585. }
  20586. for (var renderEffectName in this._renderEffects) {
  20587. this._renderEffects[renderEffectName]._enable(_cam);
  20588. }
  20589. };
  20590. PostProcessRenderPipeline.prototype._update = function () {
  20591. for (var renderEffectName in this._renderEffects) {
  20592. this._renderEffects[renderEffectName]._update();
  20593. }
  20594. for (var i = 0; i < this._cameras.length; i++) {
  20595. var cameraName = this._cameras[i].name;
  20596. if (this._renderEffectsForIsolatedPass[cameraName]) {
  20597. this._renderEffectsForIsolatedPass[cameraName]._update();
  20598. }
  20599. }
  20600. };
  20601. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  20602. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  20603. return PostProcessRenderPipeline;
  20604. })();
  20605. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  20606. })(BABYLON || (BABYLON = {}));
  20607. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  20608. var BABYLON;
  20609. (function (BABYLON) {
  20610. var PostProcessRenderPipelineManager = (function () {
  20611. function PostProcessRenderPipelineManager() {
  20612. this._renderPipelines = {};
  20613. }
  20614. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  20615. this._renderPipelines[renderPipeline._name] = renderPipeline;
  20616. };
  20617. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  20618. var renderPipeline = this._renderPipelines[renderPipelineName];
  20619. if (!renderPipeline) {
  20620. return;
  20621. }
  20622. renderPipeline._attachCameras(cameras, unique);
  20623. };
  20624. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  20625. var renderPipeline = this._renderPipelines[renderPipelineName];
  20626. if (!renderPipeline) {
  20627. return;
  20628. }
  20629. renderPipeline._detachCameras(cameras);
  20630. };
  20631. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  20632. var renderPipeline = this._renderPipelines[renderPipelineName];
  20633. if (!renderPipeline) {
  20634. return;
  20635. }
  20636. renderPipeline._enableEffect(renderEffectName, cameras);
  20637. };
  20638. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  20639. var renderPipeline = this._renderPipelines[renderPipelineName];
  20640. if (!renderPipeline) {
  20641. return;
  20642. }
  20643. renderPipeline._disableEffect(renderEffectName, cameras);
  20644. };
  20645. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  20646. var renderPipeline = this._renderPipelines[renderPipelineName];
  20647. if (!renderPipeline) {
  20648. return;
  20649. }
  20650. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  20651. };
  20652. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  20653. var renderPipeline = this._renderPipelines[renderPipelineName];
  20654. if (!renderPipeline) {
  20655. return;
  20656. }
  20657. renderPipeline._disableDisplayOnlyPass(cameras);
  20658. };
  20659. PostProcessRenderPipelineManager.prototype.update = function () {
  20660. for (var renderPipelineName in this._renderPipelines) {
  20661. this._renderPipelines[renderPipelineName]._update();
  20662. }
  20663. };
  20664. return PostProcessRenderPipelineManager;
  20665. })();
  20666. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  20667. })(BABYLON || (BABYLON = {}));
  20668. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  20669. var BABYLON;
  20670. (function (BABYLON) {
  20671. var DisplayPassPostProcess = (function (_super) {
  20672. __extends(DisplayPassPostProcess, _super);
  20673. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  20674. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  20675. }
  20676. return DisplayPassPostProcess;
  20677. })(BABYLON.PostProcess);
  20678. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  20679. })(BABYLON || (BABYLON = {}));
  20680. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  20681. var BABYLON;
  20682. (function (BABYLON) {
  20683. var BoundingBoxRenderer = (function () {
  20684. function BoundingBoxRenderer(scene) {
  20685. this.frontColor = new BABYLON.Color3(1, 1, 1);
  20686. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  20687. this.showBackLines = true;
  20688. this.renderList = new BABYLON.SmartArray(32);
  20689. this._scene = scene;
  20690. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  20691. attributes: ["position"],
  20692. uniforms: ["worldViewProjection", "color"]
  20693. });
  20694. var engine = this._scene.getEngine();
  20695. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  20696. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  20697. 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]);
  20698. }
  20699. BoundingBoxRenderer.prototype.reset = function () {
  20700. this.renderList.reset();
  20701. };
  20702. BoundingBoxRenderer.prototype.render = function () {
  20703. if (this.renderList.length === 0 || !this._colorShader.isReady()) {
  20704. return;
  20705. }
  20706. var engine = this._scene.getEngine();
  20707. engine.setDepthWrite(false);
  20708. this._colorShader._preBind();
  20709. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  20710. var boundingBox = this.renderList.data[boundingBoxIndex];
  20711. var min = boundingBox.minimum;
  20712. var max = boundingBox.maximum;
  20713. var diff = max.subtract(min);
  20714. var median = min.add(diff.scale(0.5));
  20715. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z).multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z)).multiply(boundingBox.getWorldMatrix());
  20716. // VBOs
  20717. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  20718. if (this.showBackLines) {
  20719. // Back
  20720. engine.setDepthFunctionToGreaterOrEqual();
  20721. this._scene.resetCachedMaterial();
  20722. this._colorShader.setColor4("color", this.backColor.toColor4());
  20723. this._colorShader.bind(worldMatrix);
  20724. // Draw order
  20725. engine.draw(false, 0, 24);
  20726. }
  20727. // Front
  20728. engine.setDepthFunctionToLess();
  20729. this._scene.resetCachedMaterial();
  20730. this._colorShader.setColor4("color", this.frontColor.toColor4());
  20731. this._colorShader.bind(worldMatrix);
  20732. // Draw order
  20733. engine.draw(false, 0, 24);
  20734. }
  20735. this._colorShader.unbind();
  20736. engine.setDepthFunctionToLessOrEqual();
  20737. engine.setDepthWrite(true);
  20738. };
  20739. BoundingBoxRenderer.prototype.dispose = function () {
  20740. this._colorShader.dispose();
  20741. this._vb.dispose();
  20742. this._scene.getEngine()._releaseBuffer(this._ib);
  20743. };
  20744. return BoundingBoxRenderer;
  20745. })();
  20746. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  20747. })(BABYLON || (BABYLON = {}));
  20748. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  20749. /**
  20750. * Based on jsTGALoader - Javascript loader for TGA file
  20751. * By Vincent Thibault
  20752. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  20753. */
  20754. var BABYLON;
  20755. (function (BABYLON) {
  20756. (function (Internals) {
  20757. var TGATools = (function () {
  20758. function TGATools() {
  20759. }
  20760. TGATools.GetTGAHeader = function (data) {
  20761. var offset = 0;
  20762. var header = {
  20763. id_length: data[offset++],
  20764. colormap_type: data[offset++],
  20765. image_type: data[offset++],
  20766. colormap_index: data[offset++] | data[offset++] << 8,
  20767. colormap_length: data[offset++] | data[offset++] << 8,
  20768. colormap_size: data[offset++],
  20769. origin: [
  20770. data[offset++] | data[offset++] << 8,
  20771. data[offset++] | data[offset++] << 8
  20772. ],
  20773. width: data[offset++] | data[offset++] << 8,
  20774. height: data[offset++] | data[offset++] << 8,
  20775. pixel_size: data[offset++],
  20776. flags: data[offset++]
  20777. };
  20778. return header;
  20779. };
  20780. TGATools.UploadContent = function (gl, data) {
  20781. // Not enough data to contain header ?
  20782. if (data.length < 19) {
  20783. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  20784. return;
  20785. }
  20786. // Read Header
  20787. var offset = 18;
  20788. var header = TGATools.GetTGAHeader(data);
  20789. // Assume it's a valid Targa file.
  20790. if (header.id_length + offset > data.length) {
  20791. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  20792. return;
  20793. }
  20794. // Skip not needed data
  20795. offset += header.id_length;
  20796. var use_rle = false;
  20797. var use_pal = false;
  20798. var use_rgb = false;
  20799. var use_grey = false;
  20800. switch (header.image_type) {
  20801. case TGATools._TYPE_RLE_INDEXED:
  20802. use_rle = true;
  20803. case TGATools._TYPE_INDEXED:
  20804. use_pal = true;
  20805. break;
  20806. case TGATools._TYPE_RLE_RGB:
  20807. use_rle = true;
  20808. case TGATools._TYPE_RGB:
  20809. use_rgb = true;
  20810. break;
  20811. case TGATools._TYPE_RLE_GREY:
  20812. use_rle = true;
  20813. case TGATools._TYPE_GREY:
  20814. use_grey = true;
  20815. break;
  20816. }
  20817. var pixel_data;
  20818. var numAlphaBits = header.flags & 0xf;
  20819. var pixel_size = header.pixel_size >> 3;
  20820. var pixel_total = header.width * header.height * pixel_size;
  20821. // Read palettes
  20822. var palettes;
  20823. if (use_pal) {
  20824. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  20825. }
  20826. // Read LRE
  20827. if (use_rle) {
  20828. pixel_data = new Uint8Array(pixel_total);
  20829. var c, count, i;
  20830. var localOffset = 0;
  20831. var pixels = new Uint8Array(pixel_size);
  20832. while (offset < pixel_total && localOffset < pixel_total) {
  20833. c = data[offset++];
  20834. count = (c & 0x7f) + 1;
  20835. // RLE pixels
  20836. if (c & 0x80) {
  20837. for (i = 0; i < pixel_size; ++i) {
  20838. pixels[i] = data[offset++];
  20839. }
  20840. for (i = 0; i < count; ++i) {
  20841. pixel_data.set(pixels, localOffset + i * pixel_size);
  20842. }
  20843. localOffset += pixel_size * count;
  20844. } else {
  20845. count *= pixel_size;
  20846. for (i = 0; i < count; ++i) {
  20847. pixel_data[localOffset + i] = data[offset++];
  20848. }
  20849. localOffset += count;
  20850. }
  20851. }
  20852. } else {
  20853. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  20854. }
  20855. // Load to texture
  20856. var x_start, y_start, x_step, y_step, y_end, x_end;
  20857. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  20858. default:
  20859. case TGATools._ORIGIN_UL:
  20860. x_start = 0;
  20861. x_step = 1;
  20862. x_end = header.width;
  20863. y_start = 0;
  20864. y_step = 1;
  20865. y_end = header.height;
  20866. break;
  20867. case TGATools._ORIGIN_BL:
  20868. x_start = 0;
  20869. x_step = 1;
  20870. x_end = header.width;
  20871. y_start = header.height - 1;
  20872. y_step = -1;
  20873. y_end = -1;
  20874. break;
  20875. case TGATools._ORIGIN_UR:
  20876. x_start = header.width - 1;
  20877. x_step = -1;
  20878. x_end = -1;
  20879. y_start = 0;
  20880. y_step = 1;
  20881. y_end = header.height;
  20882. break;
  20883. case TGATools._ORIGIN_BR:
  20884. x_start = header.width - 1;
  20885. x_step = -1;
  20886. x_end = -1;
  20887. y_start = header.height - 1;
  20888. y_step = -1;
  20889. y_end = -1;
  20890. break;
  20891. }
  20892. // Load the specify method
  20893. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  20894. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  20895. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  20896. };
  20897. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  20898. var image = pixel_data, colormap = palettes;
  20899. var width = header.width, height = header.height;
  20900. var color, i = 0, x, y;
  20901. var imageData = new Uint8Array(width * height * 4);
  20902. for (y = y_start; y !== y_end; y += y_step) {
  20903. for (x = x_start; x !== x_end; x += x_step, i++) {
  20904. color = image[i];
  20905. imageData[(x + width * y) * 4 + 3] = 255;
  20906. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  20907. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  20908. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  20909. }
  20910. }
  20911. return imageData;
  20912. };
  20913. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  20914. var image = pixel_data;
  20915. var width = header.width, height = header.height;
  20916. var color, i = 0, x, y;
  20917. var imageData = new Uint8Array(width * height * 4);
  20918. for (y = y_start; y !== y_end; y += y_step) {
  20919. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  20920. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  20921. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  20922. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  20923. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  20924. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  20925. }
  20926. }
  20927. return imageData;
  20928. };
  20929. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  20930. var image = pixel_data;
  20931. var width = header.width, height = header.height;
  20932. var i = 0, x, y;
  20933. var imageData = new Uint8Array(width * height * 4);
  20934. for (y = y_start; y !== y_end; y += y_step) {
  20935. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  20936. imageData[(x + width * y) * 4 + 3] = 255;
  20937. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  20938. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  20939. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  20940. }
  20941. }
  20942. return imageData;
  20943. };
  20944. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  20945. var image = pixel_data;
  20946. var width = header.width, height = header.height;
  20947. var i = 0, x, y;
  20948. var imageData = new Uint8Array(width * height * 4);
  20949. for (y = y_start; y !== y_end; y += y_step) {
  20950. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  20951. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  20952. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  20953. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  20954. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  20955. }
  20956. }
  20957. return imageData;
  20958. };
  20959. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  20960. var image = pixel_data;
  20961. var width = header.width, height = header.height;
  20962. var color, i = 0, x, y;
  20963. var imageData = new Uint8Array(width * height * 4);
  20964. for (y = y_start; y !== y_end; y += y_step) {
  20965. for (x = x_start; x !== x_end; x += x_step, i++) {
  20966. color = image[i];
  20967. imageData[(x + width * y) * 4 + 0] = color;
  20968. imageData[(x + width * y) * 4 + 1] = color;
  20969. imageData[(x + width * y) * 4 + 2] = color;
  20970. imageData[(x + width * y) * 4 + 3] = 255;
  20971. }
  20972. }
  20973. return imageData;
  20974. };
  20975. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  20976. var image = pixel_data;
  20977. var width = header.width, height = header.height;
  20978. var i = 0, x, y;
  20979. var imageData = new Uint8Array(width * height * 4);
  20980. for (y = y_start; y !== y_end; y += y_step) {
  20981. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  20982. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  20983. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  20984. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  20985. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  20986. }
  20987. }
  20988. return imageData;
  20989. };
  20990. TGATools._TYPE_NO_DATA = 0;
  20991. TGATools._TYPE_INDEXED = 1;
  20992. TGATools._TYPE_RGB = 2;
  20993. TGATools._TYPE_GREY = 3;
  20994. TGATools._TYPE_RLE_INDEXED = 9;
  20995. TGATools._TYPE_RLE_RGB = 10;
  20996. TGATools._TYPE_RLE_GREY = 11;
  20997. TGATools._ORIGIN_MASK = 0x30;
  20998. TGATools._ORIGIN_SHIFT = 0x04;
  20999. TGATools._ORIGIN_BL = 0x00;
  21000. TGATools._ORIGIN_BR = 0x01;
  21001. TGATools._ORIGIN_UL = 0x02;
  21002. TGATools._ORIGIN_UR = 0x03;
  21003. return TGATools;
  21004. })();
  21005. Internals.TGATools = TGATools;
  21006. })(BABYLON.Internals || (BABYLON.Internals = {}));
  21007. var Internals = BABYLON.Internals;
  21008. })(BABYLON || (BABYLON = {}));
  21009. //# sourceMappingURL=babylon.tools.tga.js.map
  21010. var BABYLON;
  21011. (function (BABYLON) {
  21012. (function (Internals) {
  21013. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  21014. // All values and structures referenced from:
  21015. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  21016. var DDS_MAGIC = 0x20534444;
  21017. 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;
  21018. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  21019. 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;
  21020. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  21021. function FourCCToInt32(value) {
  21022. return value.charCodeAt(0) + (value.charCodeAt(1) << 8) + (value.charCodeAt(2) << 16) + (value.charCodeAt(3) << 24);
  21023. }
  21024. function Int32ToFourCC(value) {
  21025. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  21026. }
  21027. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  21028. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  21029. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  21030. var headerLengthInt = 31;
  21031. // Offsets into the header array
  21032. var off_magic = 0;
  21033. var off_size = 1;
  21034. var off_flags = 2;
  21035. var off_height = 3;
  21036. var off_width = 4;
  21037. var off_mipmapCount = 7;
  21038. var off_pfFlags = 20;
  21039. var off_pfFourCC = 21;
  21040. var off_RGBbpp = 22;
  21041. var off_RMask = 23;
  21042. var off_GMask = 24;
  21043. var off_BMask = 25;
  21044. var off_AMask = 26;
  21045. var off_caps1 = 27;
  21046. var off_caps2 = 28;
  21047. ;
  21048. var DDSTools = (function () {
  21049. function DDSTools() {
  21050. }
  21051. DDSTools.GetDDSInfo = function (arrayBuffer) {
  21052. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  21053. var mipmapCount = 1;
  21054. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  21055. mipmapCount = Math.max(1, header[off_mipmapCount]);
  21056. }
  21057. return {
  21058. width: header[off_width],
  21059. height: header[off_height],
  21060. mipmapCount: mipmapCount,
  21061. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  21062. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  21063. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  21064. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  21065. };
  21066. };
  21067. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  21068. var byteArray = new Uint8Array(dataLength);
  21069. var srcData = new Uint8Array(arrayBuffer);
  21070. var index = 0;
  21071. for (var y = height - 1; y >= 0; y--) {
  21072. for (var x = 0; x < width; x++) {
  21073. var srcPos = dataOffset + (x + y * width) * 4;
  21074. byteArray[index + 2] = srcData[srcPos];
  21075. byteArray[index + 1] = srcData[srcPos + 1];
  21076. byteArray[index] = srcData[srcPos + 2];
  21077. byteArray[index + 3] = srcData[srcPos + 3];
  21078. index += 4;
  21079. }
  21080. }
  21081. return byteArray;
  21082. };
  21083. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  21084. var byteArray = new Uint8Array(dataLength);
  21085. var srcData = new Uint8Array(arrayBuffer);
  21086. var index = 0;
  21087. for (var y = height - 1; y >= 0; y--) {
  21088. for (var x = 0; x < width; x++) {
  21089. var srcPos = dataOffset + (x + y * width) * 3;
  21090. byteArray[index + 2] = srcData[srcPos];
  21091. byteArray[index + 1] = srcData[srcPos + 1];
  21092. byteArray[index] = srcData[srcPos + 2];
  21093. index += 3;
  21094. }
  21095. }
  21096. return byteArray;
  21097. };
  21098. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  21099. var byteArray = new Uint8Array(dataLength);
  21100. var srcData = new Uint8Array(arrayBuffer);
  21101. var index = 0;
  21102. for (var y = height - 1; y >= 0; y--) {
  21103. for (var x = 0; x < width; x++) {
  21104. var srcPos = dataOffset + (x + y * width);
  21105. byteArray[index] = srcData[srcPos];
  21106. index++;
  21107. }
  21108. }
  21109. return byteArray;
  21110. };
  21111. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  21112. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  21113. if (header[off_magic] != DDS_MAGIC) {
  21114. BABYLON.Tools.Error("Invalid magic number in DDS header");
  21115. return;
  21116. }
  21117. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  21118. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  21119. return;
  21120. }
  21121. if (info.isFourCC) {
  21122. fourCC = header[off_pfFourCC];
  21123. switch (fourCC) {
  21124. case FOURCC_DXT1:
  21125. blockBytes = 8;
  21126. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  21127. break;
  21128. case FOURCC_DXT3:
  21129. blockBytes = 16;
  21130. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  21131. break;
  21132. case FOURCC_DXT5:
  21133. blockBytes = 16;
  21134. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  21135. break;
  21136. default:
  21137. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  21138. return;
  21139. }
  21140. }
  21141. mipmapCount = 1;
  21142. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  21143. mipmapCount = Math.max(1, header[off_mipmapCount]);
  21144. }
  21145. var bpp = header[off_RGBbpp];
  21146. for (var face = 0; face < faces; face++) {
  21147. var sampler = faces == 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  21148. width = header[off_width];
  21149. height = header[off_height];
  21150. dataOffset = header[off_size] + 4;
  21151. for (i = 0; i < mipmapCount; ++i) {
  21152. if (info.isRGB) {
  21153. if (bpp == 24) {
  21154. dataLength = width * height * 3;
  21155. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  21156. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  21157. } else {
  21158. dataLength = width * height * 4;
  21159. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  21160. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  21161. }
  21162. } else if (info.isLuminance) {
  21163. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  21164. var unpaddedRowSize = width;
  21165. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  21166. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  21167. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  21168. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  21169. } else {
  21170. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  21171. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  21172. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  21173. }
  21174. dataOffset += dataLength;
  21175. width *= 0.5;
  21176. height *= 0.5;
  21177. width = Math.max(1.0, width);
  21178. height = Math.max(1.0, height);
  21179. }
  21180. }
  21181. };
  21182. return DDSTools;
  21183. })();
  21184. Internals.DDSTools = DDSTools;
  21185. })(BABYLON.Internals || (BABYLON.Internals = {}));
  21186. var Internals = BABYLON.Internals;
  21187. })(BABYLON || (BABYLON = {}));
  21188. //# sourceMappingURL=babylon.tools.dds.js.map
  21189. var BABYLON;
  21190. (function (BABYLON) {
  21191. var SmartArray = (function () {
  21192. function SmartArray(capacity) {
  21193. this.length = 0;
  21194. this._duplicateId = 0;
  21195. this.data = new Array(capacity);
  21196. this._id = SmartArray._GlobalId++;
  21197. }
  21198. SmartArray.prototype.push = function (value) {
  21199. this.data[this.length++] = value;
  21200. if (this.length > this.data.length) {
  21201. this.data.length *= 2;
  21202. }
  21203. if (!value.__smartArrayFlags) {
  21204. value.__smartArrayFlags = {};
  21205. }
  21206. value.__smartArrayFlags[this._id] = this._duplicateId;
  21207. };
  21208. SmartArray.prototype.pushNoDuplicate = function (value) {
  21209. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  21210. return;
  21211. }
  21212. this.push(value);
  21213. };
  21214. SmartArray.prototype.sort = function (compareFn) {
  21215. this.data.sort(compareFn);
  21216. };
  21217. SmartArray.prototype.reset = function () {
  21218. this.length = 0;
  21219. this._duplicateId++;
  21220. };
  21221. SmartArray.prototype.concat = function (array) {
  21222. if (array.length === 0) {
  21223. return;
  21224. }
  21225. if (this.length + array.length > this.data.length) {
  21226. this.data.length = (this.length + array.length) * 2;
  21227. }
  21228. for (var index = 0; index < array.length; index++) {
  21229. this.data[this.length++] = (array.data || array)[index];
  21230. }
  21231. };
  21232. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  21233. if (array.length === 0) {
  21234. return;
  21235. }
  21236. if (this.length + array.length > this.data.length) {
  21237. this.data.length = (this.length + array.length) * 2;
  21238. }
  21239. for (var index = 0; index < array.length; index++) {
  21240. var item = (array.data || array)[index];
  21241. this.pushNoDuplicate(item);
  21242. }
  21243. };
  21244. SmartArray.prototype.indexOf = function (value) {
  21245. var position = this.data.indexOf(value);
  21246. if (position >= this.length) {
  21247. return -1;
  21248. }
  21249. return position;
  21250. };
  21251. SmartArray._GlobalId = 0;
  21252. return SmartArray;
  21253. })();
  21254. BABYLON.SmartArray = SmartArray;
  21255. })(BABYLON || (BABYLON = {}));
  21256. //# sourceMappingURL=babylon.smartArray.js.map
  21257. var BABYLON;
  21258. (function (BABYLON) {
  21259. var CannonJSPlugin = (function () {
  21260. function CannonJSPlugin() {
  21261. this._registeredMeshes = [];
  21262. this._physicsMaterials = [];
  21263. this.updateBodyPosition = function (mesh) {
  21264. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21265. var registeredMesh = this._registeredMeshes[index];
  21266. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  21267. var body = registeredMesh.body;
  21268. var center = mesh.getBoundingInfo().boundingBox.center;
  21269. body.position.set(center.x, center.z, center.y);
  21270. body.quaternion.x = mesh.rotationQuaternion.x;
  21271. body.quaternion.z = mesh.rotationQuaternion.y;
  21272. body.quaternion.y = mesh.rotationQuaternion.z;
  21273. body.quaternion.w = -mesh.rotationQuaternion.w;
  21274. return;
  21275. }
  21276. }
  21277. };
  21278. }
  21279. CannonJSPlugin.prototype.initialize = function (iterations) {
  21280. if (typeof iterations === "undefined") { iterations = 10; }
  21281. this._world = new CANNON.World();
  21282. this._world.broadphase = new CANNON.NaiveBroadphase();
  21283. this._world.solver.iterations = iterations;
  21284. };
  21285. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  21286. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  21287. };
  21288. CannonJSPlugin.prototype.runOneStep = function (delta) {
  21289. this._world.step(delta);
  21290. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21291. var registeredMesh = this._registeredMeshes[index];
  21292. if (registeredMesh.isChild) {
  21293. continue;
  21294. }
  21295. // Body position
  21296. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  21297. var deltaPos = registeredMesh.delta;
  21298. if (deltaPos) {
  21299. registeredMesh.mesh.position.x = bodyX + deltaPos.x;
  21300. registeredMesh.mesh.position.y = bodyZ + deltaPos.y;
  21301. registeredMesh.mesh.position.z = bodyY + deltaPos.z;
  21302. } else {
  21303. registeredMesh.mesh.position.x = bodyX;
  21304. registeredMesh.mesh.position.y = bodyZ;
  21305. registeredMesh.mesh.position.z = bodyY;
  21306. }
  21307. if (!registeredMesh.mesh.rotationQuaternion) {
  21308. registeredMesh.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  21309. }
  21310. registeredMesh.mesh.rotationQuaternion.x = registeredMesh.body.quaternion.x;
  21311. registeredMesh.mesh.rotationQuaternion.y = registeredMesh.body.quaternion.z;
  21312. registeredMesh.mesh.rotationQuaternion.z = registeredMesh.body.quaternion.y;
  21313. registeredMesh.mesh.rotationQuaternion.w = -registeredMesh.body.quaternion.w;
  21314. }
  21315. };
  21316. CannonJSPlugin.prototype.setGravity = function (gravity) {
  21317. this._world.gravity.set(gravity.x, gravity.z, gravity.y);
  21318. };
  21319. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  21320. this.unregisterMesh(mesh);
  21321. mesh.computeWorldMatrix(true);
  21322. switch (impostor) {
  21323. case BABYLON.PhysicsEngine.SphereImpostor:
  21324. var bbox = mesh.getBoundingInfo().boundingBox;
  21325. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  21326. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  21327. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  21328. return this._createSphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2, mesh, options);
  21329. case BABYLON.PhysicsEngine.BoxImpostor:
  21330. bbox = mesh.getBoundingInfo().boundingBox;
  21331. var min = bbox.minimumWorld;
  21332. var max = bbox.maximumWorld;
  21333. var box = max.subtract(min).scale(0.5);
  21334. return this._createBox(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z), mesh, options);
  21335. case BABYLON.PhysicsEngine.PlaneImpostor:
  21336. return this._createPlane(mesh, options);
  21337. case BABYLON.PhysicsEngine.MeshImpostor:
  21338. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21339. var rawFaces = mesh.getIndices();
  21340. return this._createConvexPolyhedron(rawVerts, rawFaces, mesh, options);
  21341. }
  21342. return null;
  21343. };
  21344. CannonJSPlugin.prototype._createSphere = function (radius, mesh, options) {
  21345. var shape = new CANNON.Sphere(radius);
  21346. if (!options) {
  21347. return shape;
  21348. }
  21349. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  21350. };
  21351. CannonJSPlugin.prototype._createBox = function (x, y, z, mesh, options) {
  21352. var shape = new CANNON.Box(new CANNON.Vec3(x, z, y));
  21353. if (!options) {
  21354. return shape;
  21355. }
  21356. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  21357. };
  21358. CannonJSPlugin.prototype._createPlane = function (mesh, options) {
  21359. var shape = new CANNON.Plane();
  21360. if (!options) {
  21361. return shape;
  21362. }
  21363. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  21364. };
  21365. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh, options) {
  21366. var verts = [], faces = [];
  21367. mesh.computeWorldMatrix(true);
  21368. for (var i = 0; i < rawVerts.length; i += 3) {
  21369. var transformed = BABYLON.Vector3.Zero();
  21370. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  21371. verts.push(new CANNON.Vec3(transformed.x, transformed.z, transformed.y));
  21372. }
  21373. for (var j = 0; j < rawFaces.length; j += 3) {
  21374. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  21375. }
  21376. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  21377. if (!options) {
  21378. return shape;
  21379. }
  21380. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  21381. };
  21382. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  21383. var index;
  21384. var mat;
  21385. for (index = 0; index < this._physicsMaterials.length; index++) {
  21386. mat = this._physicsMaterials[index];
  21387. if (mat.friction === friction && mat.restitution === restitution) {
  21388. return mat;
  21389. }
  21390. }
  21391. var currentMat = new CANNON.Material();
  21392. currentMat.friction = friction;
  21393. currentMat.restitution = restitution;
  21394. this._physicsMaterials.push(currentMat);
  21395. for (index = 0; index < this._physicsMaterials.length; index++) {
  21396. mat = this._physicsMaterials[index];
  21397. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, mat.friction * currentMat.friction, mat.restitution * currentMat.restitution);
  21398. contactMaterial.contactEquationStiffness = 1e10;
  21399. contactMaterial.contactEquationRegularizationTime = 10;
  21400. this._world.addContactMaterial(contactMaterial);
  21401. }
  21402. return currentMat;
  21403. };
  21404. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, mass, friction, restitution) {
  21405. var initialRotation = null;
  21406. if (mesh.rotationQuaternion) {
  21407. initialRotation = mesh.rotationQuaternion.clone();
  21408. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  21409. }
  21410. // The delta between the mesh position and the mesh bounding box center
  21411. var bbox = mesh.getBoundingInfo().boundingBox;
  21412. var deltaPosition = mesh.position.subtract(bbox.center);
  21413. var material = this._addMaterial(friction, restitution);
  21414. var body = new CANNON.RigidBody(mass, shape, material);
  21415. if (initialRotation) {
  21416. body.quaternion.x = initialRotation.x;
  21417. body.quaternion.z = initialRotation.y;
  21418. body.quaternion.y = initialRotation.z;
  21419. body.quaternion.w = -initialRotation.w;
  21420. }
  21421. body.position.set(bbox.center.x, bbox.center.z, bbox.center.y);
  21422. this._world.add(body);
  21423. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition });
  21424. return body;
  21425. };
  21426. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  21427. var compoundShape = new CANNON.Compound();
  21428. for (var index = 0; index < parts.length; index++) {
  21429. var mesh = parts[index].mesh;
  21430. var shape = this.registerMesh(mesh, parts[index].impostor);
  21431. if (index == 0) {
  21432. compoundShape.addChild(shape, new CANNON.Vec3(0, 0, 0));
  21433. } else {
  21434. compoundShape.addChild(shape, new CANNON.Vec3(mesh.position.x, mesh.position.z, mesh.position.y));
  21435. }
  21436. }
  21437. var initialMesh = parts[0].mesh;
  21438. var body = this._createRigidBodyFromShape(compoundShape, initialMesh, options.mass, options.friction, options.restitution);
  21439. body.parts = parts;
  21440. return body;
  21441. };
  21442. CannonJSPlugin.prototype._unbindBody = function (body) {
  21443. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21444. var registeredMesh = this._registeredMeshes[index];
  21445. if (registeredMesh.body === body) {
  21446. registeredMesh.body = null;
  21447. registeredMesh.delta = 0;
  21448. }
  21449. }
  21450. };
  21451. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  21452. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21453. var registeredMesh = this._registeredMeshes[index];
  21454. if (registeredMesh.mesh === mesh) {
  21455. // Remove body
  21456. if (registeredMesh.body) {
  21457. this._world.remove(registeredMesh.body);
  21458. this._unbindBody(registeredMesh.body);
  21459. }
  21460. this._registeredMeshes.splice(index, 1);
  21461. return;
  21462. }
  21463. }
  21464. };
  21465. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  21466. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.z, contactPoint.y);
  21467. var impulse = new CANNON.Vec3(force.x, force.z, force.y);
  21468. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21469. var registeredMesh = this._registeredMeshes[index];
  21470. if (registeredMesh.mesh === mesh) {
  21471. registeredMesh.body.applyImpulse(impulse, worldPoint);
  21472. return;
  21473. }
  21474. }
  21475. };
  21476. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  21477. var body1 = null, body2 = null;
  21478. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21479. var registeredMesh = this._registeredMeshes[index];
  21480. if (registeredMesh.mesh === mesh1) {
  21481. body1 = registeredMesh.body;
  21482. } else if (registeredMesh.mesh === mesh2) {
  21483. body2 = registeredMesh.body;
  21484. }
  21485. }
  21486. if (!body1 || !body2) {
  21487. return false;
  21488. }
  21489. 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));
  21490. this._world.addConstraint(constraint);
  21491. return true;
  21492. };
  21493. CannonJSPlugin.prototype.dispose = function () {
  21494. while (this._registeredMeshes.length) {
  21495. this.unregisterMesh(this._registeredMeshes[0].mesh);
  21496. }
  21497. };
  21498. CannonJSPlugin.prototype.isSupported = function () {
  21499. return window.CANNON !== undefined;
  21500. };
  21501. return CannonJSPlugin;
  21502. })();
  21503. BABYLON.CannonJSPlugin = CannonJSPlugin;
  21504. })(BABYLON || (BABYLON = {}));
  21505. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  21506. var BABYLON;
  21507. (function (BABYLON) {
  21508. var Condition = (function () {
  21509. function Condition(actionManager) {
  21510. this._actionManager = actionManager;
  21511. }
  21512. Condition.prototype.isValid = function () {
  21513. return true;
  21514. };
  21515. Condition.prototype._getProperty = function (propertyPath) {
  21516. return this._actionManager._getProperty(propertyPath);
  21517. };
  21518. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  21519. return this._actionManager._getEffectiveTarget(target, propertyPath);
  21520. };
  21521. return Condition;
  21522. })();
  21523. BABYLON.Condition = Condition;
  21524. var ValueCondition = (function (_super) {
  21525. __extends(ValueCondition, _super);
  21526. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  21527. if (typeof operator === "undefined") { operator = ValueCondition.IsEqual; }
  21528. _super.call(this, actionManager);
  21529. this.propertyPath = propertyPath;
  21530. this.value = value;
  21531. this.operator = operator;
  21532. this._target = this._getEffectiveTarget(target, this.propertyPath);
  21533. this._property = this._getProperty(this.propertyPath);
  21534. }
  21535. Object.defineProperty(ValueCondition, "IsEqual", {
  21536. get: function () {
  21537. return ValueCondition._IsEqual;
  21538. },
  21539. enumerable: true,
  21540. configurable: true
  21541. });
  21542. Object.defineProperty(ValueCondition, "IsDifferent", {
  21543. get: function () {
  21544. return ValueCondition._IsDifferent;
  21545. },
  21546. enumerable: true,
  21547. configurable: true
  21548. });
  21549. Object.defineProperty(ValueCondition, "IsGreater", {
  21550. get: function () {
  21551. return ValueCondition._IsGreater;
  21552. },
  21553. enumerable: true,
  21554. configurable: true
  21555. });
  21556. Object.defineProperty(ValueCondition, "IsLesser", {
  21557. get: function () {
  21558. return ValueCondition._IsLesser;
  21559. },
  21560. enumerable: true,
  21561. configurable: true
  21562. });
  21563. // Methods
  21564. ValueCondition.prototype.isValid = function () {
  21565. switch (this.operator) {
  21566. case ValueCondition.IsGreater:
  21567. return this._target[this._property] > this.value;
  21568. case ValueCondition.IsLesser:
  21569. return this._target[this._property] < this.value;
  21570. case ValueCondition.IsEqual:
  21571. case ValueCondition.IsDifferent:
  21572. var check;
  21573. if (this.value.equals) {
  21574. check = this.value.equals(this._target[this._property]);
  21575. } else {
  21576. check = this.value === this._target[this._property];
  21577. }
  21578. return this.operator === ValueCondition.IsEqual ? check : !check;
  21579. }
  21580. return false;
  21581. };
  21582. ValueCondition._IsEqual = 0;
  21583. ValueCondition._IsDifferent = 1;
  21584. ValueCondition._IsGreater = 2;
  21585. ValueCondition._IsLesser = 3;
  21586. return ValueCondition;
  21587. })(Condition);
  21588. BABYLON.ValueCondition = ValueCondition;
  21589. var PredicateCondition = (function (_super) {
  21590. __extends(PredicateCondition, _super);
  21591. function PredicateCondition(actionManager, predicate) {
  21592. _super.call(this, actionManager);
  21593. this.predicate = predicate;
  21594. }
  21595. PredicateCondition.prototype.isValid = function () {
  21596. return this.predicate();
  21597. };
  21598. return PredicateCondition;
  21599. })(Condition);
  21600. BABYLON.PredicateCondition = PredicateCondition;
  21601. var StateCondition = (function (_super) {
  21602. __extends(StateCondition, _super);
  21603. function StateCondition(actionManager, target, value) {
  21604. _super.call(this, actionManager);
  21605. this.value = value;
  21606. this._target = target;
  21607. }
  21608. // Methods
  21609. StateCondition.prototype.isValid = function () {
  21610. return this._target.state === this.value;
  21611. };
  21612. return StateCondition;
  21613. })(Condition);
  21614. BABYLON.StateCondition = StateCondition;
  21615. })(BABYLON || (BABYLON = {}));
  21616. //# sourceMappingURL=babylon.condition.js.map
  21617. var BABYLON;
  21618. (function (BABYLON) {
  21619. var Action = (function () {
  21620. function Action(triggerOptions, condition) {
  21621. this.triggerOptions = triggerOptions;
  21622. if (triggerOptions.parameter) {
  21623. this.trigger = triggerOptions.trigger;
  21624. this._triggerParameter = triggerOptions.parameter;
  21625. } else {
  21626. this.trigger = triggerOptions;
  21627. }
  21628. this._nextActiveAction = this;
  21629. this._condition = condition;
  21630. }
  21631. // Methods
  21632. Action.prototype._prepare = function () {
  21633. };
  21634. Action.prototype.getTriggerParameter = function () {
  21635. return this._triggerParameter;
  21636. };
  21637. Action.prototype._executeCurrent = function (evt) {
  21638. if (this._condition) {
  21639. var currentRenderId = this._actionManager.getScene().getRenderId();
  21640. // We cache the current evaluation for the current frame
  21641. if (this._condition._evaluationId === currentRenderId) {
  21642. if (!this._condition._currentResult) {
  21643. return;
  21644. }
  21645. } else {
  21646. this._condition._evaluationId = currentRenderId;
  21647. if (!this._condition.isValid()) {
  21648. this._condition._currentResult = false;
  21649. return;
  21650. }
  21651. this._condition._currentResult = true;
  21652. }
  21653. }
  21654. this._nextActiveAction.execute(evt);
  21655. if (this._nextActiveAction._child) {
  21656. if (!this._nextActiveAction._child._actionManager) {
  21657. this._nextActiveAction._child._actionManager = this._actionManager;
  21658. }
  21659. this._nextActiveAction = this._nextActiveAction._child;
  21660. } else {
  21661. this._nextActiveAction = this;
  21662. }
  21663. };
  21664. Action.prototype.execute = function (evt) {
  21665. };
  21666. Action.prototype.then = function (action) {
  21667. this._child = action;
  21668. action._actionManager = this._actionManager;
  21669. action._prepare();
  21670. return action;
  21671. };
  21672. Action.prototype._getProperty = function (propertyPath) {
  21673. return this._actionManager._getProperty(propertyPath);
  21674. };
  21675. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  21676. return this._actionManager._getEffectiveTarget(target, propertyPath);
  21677. };
  21678. return Action;
  21679. })();
  21680. BABYLON.Action = Action;
  21681. })(BABYLON || (BABYLON = {}));
  21682. //# sourceMappingURL=babylon.action.js.map
  21683. var BABYLON;
  21684. (function (BABYLON) {
  21685. var ActionEvent = (function () {
  21686. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent) {
  21687. this.source = source;
  21688. this.pointerX = pointerX;
  21689. this.pointerY = pointerY;
  21690. this.meshUnderPointer = meshUnderPointer;
  21691. this.sourceEvent = sourceEvent;
  21692. }
  21693. ActionEvent.CreateNew = function (source, evt) {
  21694. var scene = source.getScene();
  21695. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  21696. };
  21697. ActionEvent.CreateNewFromScene = function (scene, evt) {
  21698. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  21699. };
  21700. return ActionEvent;
  21701. })();
  21702. BABYLON.ActionEvent = ActionEvent;
  21703. var ActionManager = (function () {
  21704. function ActionManager(scene) {
  21705. // Members
  21706. this.actions = new Array();
  21707. this._scene = scene;
  21708. scene._actionManagers.push(this);
  21709. }
  21710. Object.defineProperty(ActionManager, "NothingTrigger", {
  21711. get: function () {
  21712. return ActionManager._NothingTrigger;
  21713. },
  21714. enumerable: true,
  21715. configurable: true
  21716. });
  21717. Object.defineProperty(ActionManager, "OnPickTrigger", {
  21718. get: function () {
  21719. return ActionManager._OnPickTrigger;
  21720. },
  21721. enumerable: true,
  21722. configurable: true
  21723. });
  21724. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  21725. get: function () {
  21726. return ActionManager._OnLeftPickTrigger;
  21727. },
  21728. enumerable: true,
  21729. configurable: true
  21730. });
  21731. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  21732. get: function () {
  21733. return ActionManager._OnRightPickTrigger;
  21734. },
  21735. enumerable: true,
  21736. configurable: true
  21737. });
  21738. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  21739. get: function () {
  21740. return ActionManager._OnCenterPickTrigger;
  21741. },
  21742. enumerable: true,
  21743. configurable: true
  21744. });
  21745. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  21746. get: function () {
  21747. return ActionManager._OnPointerOverTrigger;
  21748. },
  21749. enumerable: true,
  21750. configurable: true
  21751. });
  21752. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  21753. get: function () {
  21754. return ActionManager._OnPointerOutTrigger;
  21755. },
  21756. enumerable: true,
  21757. configurable: true
  21758. });
  21759. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  21760. get: function () {
  21761. return ActionManager._OnEveryFrameTrigger;
  21762. },
  21763. enumerable: true,
  21764. configurable: true
  21765. });
  21766. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  21767. get: function () {
  21768. return ActionManager._OnIntersectionEnterTrigger;
  21769. },
  21770. enumerable: true,
  21771. configurable: true
  21772. });
  21773. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  21774. get: function () {
  21775. return ActionManager._OnIntersectionExitTrigger;
  21776. },
  21777. enumerable: true,
  21778. configurable: true
  21779. });
  21780. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  21781. get: function () {
  21782. return ActionManager._OnKeyDownTrigger;
  21783. },
  21784. enumerable: true,
  21785. configurable: true
  21786. });
  21787. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  21788. get: function () {
  21789. return ActionManager._OnKeyUpTrigger;
  21790. },
  21791. enumerable: true,
  21792. configurable: true
  21793. });
  21794. // Methods
  21795. ActionManager.prototype.dispose = function () {
  21796. var index = this._scene._actionManagers.indexOf(this);
  21797. if (index > -1) {
  21798. this._scene._actionManagers.splice(index, 1);
  21799. }
  21800. };
  21801. ActionManager.prototype.getScene = function () {
  21802. return this._scene;
  21803. };
  21804. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  21805. for (var index = 0; index < this.actions.length; index++) {
  21806. var action = this.actions[index];
  21807. if (triggers.indexOf(action.trigger) > -1) {
  21808. return true;
  21809. }
  21810. }
  21811. return false;
  21812. };
  21813. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  21814. get: function () {
  21815. for (var index = 0; index < this.actions.length; index++) {
  21816. var action = this.actions[index];
  21817. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  21818. return true;
  21819. }
  21820. }
  21821. return false;
  21822. },
  21823. enumerable: true,
  21824. configurable: true
  21825. });
  21826. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  21827. get: function () {
  21828. for (var index = 0; index < this.actions.length; index++) {
  21829. var action = this.actions[index];
  21830. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  21831. return true;
  21832. }
  21833. }
  21834. return false;
  21835. },
  21836. enumerable: true,
  21837. configurable: true
  21838. });
  21839. ActionManager.prototype.registerAction = function (action) {
  21840. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  21841. if (this.getScene().actionManager !== this) {
  21842. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  21843. return null;
  21844. }
  21845. }
  21846. this.actions.push(action);
  21847. action._actionManager = this;
  21848. action._prepare();
  21849. return action;
  21850. };
  21851. ActionManager.prototype.processTrigger = function (trigger, evt) {
  21852. for (var index = 0; index < this.actions.length; index++) {
  21853. var action = this.actions[index];
  21854. if (action.trigger === trigger) {
  21855. if (trigger === ActionManager.OnKeyUpTrigger || trigger === ActionManager.OnKeyDownTrigger) {
  21856. var parameter = action.getTriggerParameter();
  21857. if (parameter) {
  21858. if (evt.sourceEvent.key !== parameter) {
  21859. continue;
  21860. }
  21861. }
  21862. }
  21863. action._executeCurrent(evt);
  21864. }
  21865. }
  21866. };
  21867. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  21868. var properties = propertyPath.split(".");
  21869. for (var index = 0; index < properties.length - 1; index++) {
  21870. target = target[properties[index]];
  21871. }
  21872. return target;
  21873. };
  21874. ActionManager.prototype._getProperty = function (propertyPath) {
  21875. var properties = propertyPath.split(".");
  21876. return properties[properties.length - 1];
  21877. };
  21878. ActionManager._NothingTrigger = 0;
  21879. ActionManager._OnPickTrigger = 1;
  21880. ActionManager._OnLeftPickTrigger = 2;
  21881. ActionManager._OnRightPickTrigger = 3;
  21882. ActionManager._OnCenterPickTrigger = 4;
  21883. ActionManager._OnPointerOverTrigger = 5;
  21884. ActionManager._OnPointerOutTrigger = 6;
  21885. ActionManager._OnEveryFrameTrigger = 7;
  21886. ActionManager._OnIntersectionEnterTrigger = 8;
  21887. ActionManager._OnIntersectionExitTrigger = 9;
  21888. ActionManager._OnKeyDownTrigger = 10;
  21889. ActionManager._OnKeyUpTrigger = 11;
  21890. return ActionManager;
  21891. })();
  21892. BABYLON.ActionManager = ActionManager;
  21893. })(BABYLON || (BABYLON = {}));
  21894. //# sourceMappingURL=babylon.actionManager.js.map
  21895. var BABYLON;
  21896. (function (BABYLON) {
  21897. var InterpolateValueAction = (function (_super) {
  21898. __extends(InterpolateValueAction, _super);
  21899. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations) {
  21900. if (typeof duration === "undefined") { duration = 1000; }
  21901. _super.call(this, triggerOptions, condition);
  21902. this.propertyPath = propertyPath;
  21903. this.value = value;
  21904. this.duration = duration;
  21905. this.stopOtherAnimations = stopOtherAnimations;
  21906. this._target = target;
  21907. }
  21908. InterpolateValueAction.prototype._prepare = function () {
  21909. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  21910. this._property = this._getProperty(this.propertyPath);
  21911. };
  21912. InterpolateValueAction.prototype.execute = function () {
  21913. var scene = this._actionManager.getScene();
  21914. var keys = [
  21915. {
  21916. frame: 0,
  21917. value: this._target[this._property]
  21918. }, {
  21919. frame: 100,
  21920. value: this.value
  21921. }
  21922. ];
  21923. var dataType;
  21924. if (typeof this.value === "number") {
  21925. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  21926. } else if (this.value instanceof BABYLON.Color3) {
  21927. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  21928. } else if (this.value instanceof BABYLON.Vector3) {
  21929. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  21930. } else if (this.value instanceof BABYLON.Matrix) {
  21931. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  21932. } else if (this.value instanceof BABYLON.Quaternion) {
  21933. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  21934. } else {
  21935. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  21936. return;
  21937. }
  21938. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  21939. animation.setKeys(keys);
  21940. if (this.stopOtherAnimations) {
  21941. scene.stopAnimation(this._target);
  21942. }
  21943. scene.beginDirectAnimation(this._target, [animation], 0, 100);
  21944. };
  21945. return InterpolateValueAction;
  21946. })(BABYLON.Action);
  21947. BABYLON.InterpolateValueAction = InterpolateValueAction;
  21948. })(BABYLON || (BABYLON = {}));
  21949. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  21950. var BABYLON;
  21951. (function (BABYLON) {
  21952. var SwitchBooleanAction = (function (_super) {
  21953. __extends(SwitchBooleanAction, _super);
  21954. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  21955. _super.call(this, triggerOptions, condition);
  21956. this.propertyPath = propertyPath;
  21957. this._target = target;
  21958. }
  21959. SwitchBooleanAction.prototype._prepare = function () {
  21960. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  21961. this._property = this._getProperty(this.propertyPath);
  21962. };
  21963. SwitchBooleanAction.prototype.execute = function () {
  21964. this._target[this._property] = !this._target[this._property];
  21965. };
  21966. return SwitchBooleanAction;
  21967. })(BABYLON.Action);
  21968. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  21969. var SetStateAction = (function (_super) {
  21970. __extends(SetStateAction, _super);
  21971. function SetStateAction(triggerOptions, target, value, condition) {
  21972. _super.call(this, triggerOptions, condition);
  21973. this.value = value;
  21974. this._target = target;
  21975. }
  21976. SetStateAction.prototype.execute = function () {
  21977. this._target.state = this.value;
  21978. };
  21979. return SetStateAction;
  21980. })(BABYLON.Action);
  21981. BABYLON.SetStateAction = SetStateAction;
  21982. var SetValueAction = (function (_super) {
  21983. __extends(SetValueAction, _super);
  21984. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  21985. _super.call(this, triggerOptions, condition);
  21986. this.propertyPath = propertyPath;
  21987. this.value = value;
  21988. this._target = target;
  21989. }
  21990. SetValueAction.prototype._prepare = function () {
  21991. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  21992. this._property = this._getProperty(this.propertyPath);
  21993. };
  21994. SetValueAction.prototype.execute = function () {
  21995. this._target[this._property] = this.value;
  21996. };
  21997. return SetValueAction;
  21998. })(BABYLON.Action);
  21999. BABYLON.SetValueAction = SetValueAction;
  22000. var IncrementValueAction = (function (_super) {
  22001. __extends(IncrementValueAction, _super);
  22002. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  22003. _super.call(this, triggerOptions, condition);
  22004. this.propertyPath = propertyPath;
  22005. this.value = value;
  22006. this._target = target;
  22007. }
  22008. IncrementValueAction.prototype._prepare = function () {
  22009. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  22010. this._property = this._getProperty(this.propertyPath);
  22011. if (typeof this._target[this._property] !== "number") {
  22012. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  22013. }
  22014. };
  22015. IncrementValueAction.prototype.execute = function () {
  22016. this._target[this._property] += this.value;
  22017. };
  22018. return IncrementValueAction;
  22019. })(BABYLON.Action);
  22020. BABYLON.IncrementValueAction = IncrementValueAction;
  22021. var PlayAnimationAction = (function (_super) {
  22022. __extends(PlayAnimationAction, _super);
  22023. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  22024. _super.call(this, triggerOptions, condition);
  22025. this.from = from;
  22026. this.to = to;
  22027. this.loop = loop;
  22028. this._target = target;
  22029. }
  22030. PlayAnimationAction.prototype._prepare = function () {
  22031. };
  22032. PlayAnimationAction.prototype.execute = function () {
  22033. var scene = this._actionManager.getScene();
  22034. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  22035. };
  22036. return PlayAnimationAction;
  22037. })(BABYLON.Action);
  22038. BABYLON.PlayAnimationAction = PlayAnimationAction;
  22039. var StopAnimationAction = (function (_super) {
  22040. __extends(StopAnimationAction, _super);
  22041. function StopAnimationAction(triggerOptions, target, condition) {
  22042. _super.call(this, triggerOptions, condition);
  22043. this._target = target;
  22044. }
  22045. StopAnimationAction.prototype._prepare = function () {
  22046. };
  22047. StopAnimationAction.prototype.execute = function () {
  22048. var scene = this._actionManager.getScene();
  22049. scene.stopAnimation(this._target);
  22050. };
  22051. return StopAnimationAction;
  22052. })(BABYLON.Action);
  22053. BABYLON.StopAnimationAction = StopAnimationAction;
  22054. var DoNothingAction = (function (_super) {
  22055. __extends(DoNothingAction, _super);
  22056. function DoNothingAction(triggerOptions, condition) {
  22057. if (typeof triggerOptions === "undefined") { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  22058. _super.call(this, triggerOptions, condition);
  22059. }
  22060. DoNothingAction.prototype.execute = function () {
  22061. };
  22062. return DoNothingAction;
  22063. })(BABYLON.Action);
  22064. BABYLON.DoNothingAction = DoNothingAction;
  22065. var CombineAction = (function (_super) {
  22066. __extends(CombineAction, _super);
  22067. function CombineAction(triggerOptions, children, condition) {
  22068. _super.call(this, triggerOptions, condition);
  22069. this.children = children;
  22070. }
  22071. CombineAction.prototype._prepare = function () {
  22072. for (var index = 0; index < this.children.length; index++) {
  22073. this.children[index]._actionManager = this._actionManager;
  22074. this.children[index]._prepare();
  22075. }
  22076. };
  22077. CombineAction.prototype.execute = function (evt) {
  22078. for (var index = 0; index < this.children.length; index++) {
  22079. this.children[index].execute(evt);
  22080. }
  22081. };
  22082. return CombineAction;
  22083. })(BABYLON.Action);
  22084. BABYLON.CombineAction = CombineAction;
  22085. var ExecuteCodeAction = (function (_super) {
  22086. __extends(ExecuteCodeAction, _super);
  22087. function ExecuteCodeAction(triggerOptions, func, condition) {
  22088. _super.call(this, triggerOptions, condition);
  22089. this.func = func;
  22090. }
  22091. ExecuteCodeAction.prototype.execute = function (evt) {
  22092. this.func(evt);
  22093. };
  22094. return ExecuteCodeAction;
  22095. })(BABYLON.Action);
  22096. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  22097. var SetParentAction = (function (_super) {
  22098. __extends(SetParentAction, _super);
  22099. function SetParentAction(triggerOptions, target, parent, condition) {
  22100. _super.call(this, triggerOptions, condition);
  22101. this._target = target;
  22102. this._parent = parent;
  22103. }
  22104. SetParentAction.prototype._prepare = function () {
  22105. };
  22106. SetParentAction.prototype.execute = function () {
  22107. if (this._target.parent === this._parent) {
  22108. return;
  22109. }
  22110. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  22111. invertParentWorldMatrix.invert();
  22112. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  22113. this._target.parent = this._parent;
  22114. };
  22115. return SetParentAction;
  22116. })(BABYLON.Action);
  22117. BABYLON.SetParentAction = SetParentAction;
  22118. })(BABYLON || (BABYLON = {}));
  22119. //# sourceMappingURL=babylon.directActions.js.map
  22120. var BABYLON;
  22121. (function (BABYLON) {
  22122. var Geometry = (function () {
  22123. function Geometry(id, scene, vertexData, updatable, mesh) {
  22124. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  22125. this._totalVertices = 0;
  22126. this._indices = [];
  22127. this.id = id;
  22128. this._engine = scene.getEngine();
  22129. this._meshes = [];
  22130. this._scene = scene;
  22131. // vertexData
  22132. if (vertexData) {
  22133. this.setAllVerticesData(vertexData, updatable);
  22134. } else {
  22135. this._totalVertices = 0;
  22136. this._indices = [];
  22137. }
  22138. // applyToMesh
  22139. if (mesh) {
  22140. this.applyToMesh(mesh);
  22141. }
  22142. }
  22143. Geometry.prototype.getScene = function () {
  22144. return this._scene;
  22145. };
  22146. Geometry.prototype.getEngine = function () {
  22147. return this._engine;
  22148. };
  22149. Geometry.prototype.isReady = function () {
  22150. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  22151. };
  22152. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  22153. vertexData.applyToGeometry(this, updatable);
  22154. };
  22155. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  22156. this._vertexBuffers = this._vertexBuffers || {};
  22157. if (this._vertexBuffers[kind]) {
  22158. this._vertexBuffers[kind].dispose();
  22159. }
  22160. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  22161. if (kind === BABYLON.VertexBuffer.PositionKind) {
  22162. stride = this._vertexBuffers[kind].getStrideSize();
  22163. this._totalVertices = data.length / stride;
  22164. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  22165. var meshes = this._meshes;
  22166. var numOfMeshes = meshes.length;
  22167. for (var index = 0; index < numOfMeshes; index++) {
  22168. var mesh = meshes[index];
  22169. mesh._resetPointsArrayCache();
  22170. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  22171. mesh._createGlobalSubMesh();
  22172. mesh.computeWorldMatrix(true);
  22173. }
  22174. }
  22175. };
  22176. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  22177. var vertexBuffer = this.getVertexBuffer(kind);
  22178. if (!vertexBuffer) {
  22179. return;
  22180. }
  22181. vertexBuffer.updateDirectly(data, offset);
  22182. };
  22183. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  22184. var vertexBuffer = this.getVertexBuffer(kind);
  22185. if (!vertexBuffer) {
  22186. return;
  22187. }
  22188. vertexBuffer.update(data);
  22189. if (kind === BABYLON.VertexBuffer.PositionKind) {
  22190. var extend;
  22191. var stride = vertexBuffer.getStrideSize();
  22192. this._totalVertices = data.length / stride;
  22193. if (updateExtends) {
  22194. extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  22195. }
  22196. var meshes = this._meshes;
  22197. var numOfMeshes = meshes.length;
  22198. for (var index = 0; index < numOfMeshes; index++) {
  22199. var mesh = meshes[index];
  22200. mesh._resetPointsArrayCache();
  22201. if (updateExtends) {
  22202. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  22203. }
  22204. }
  22205. }
  22206. };
  22207. Geometry.prototype.getTotalVertices = function () {
  22208. if (!this.isReady()) {
  22209. return 0;
  22210. }
  22211. return this._totalVertices;
  22212. };
  22213. Geometry.prototype.getVerticesData = function (kind) {
  22214. var vertexBuffer = this.getVertexBuffer(kind);
  22215. if (!vertexBuffer) {
  22216. return null;
  22217. }
  22218. return vertexBuffer.getData();
  22219. };
  22220. Geometry.prototype.getVertexBuffer = function (kind) {
  22221. if (!this.isReady()) {
  22222. return null;
  22223. }
  22224. return this._vertexBuffers[kind];
  22225. };
  22226. Geometry.prototype.getVertexBuffers = function () {
  22227. if (!this.isReady()) {
  22228. return null;
  22229. }
  22230. return this._vertexBuffers;
  22231. };
  22232. Geometry.prototype.isVerticesDataPresent = function (kind) {
  22233. if (!this._vertexBuffers) {
  22234. if (this._delayInfo) {
  22235. return this._delayInfo.indexOf(kind) !== -1;
  22236. }
  22237. return false;
  22238. }
  22239. return this._vertexBuffers[kind] !== undefined;
  22240. };
  22241. Geometry.prototype.getVerticesDataKinds = function () {
  22242. var result = [];
  22243. if (!this._vertexBuffers && this._delayInfo) {
  22244. for (var kind in this._delayInfo) {
  22245. result.push(kind);
  22246. }
  22247. } else {
  22248. for (kind in this._vertexBuffers) {
  22249. result.push(kind);
  22250. }
  22251. }
  22252. return result;
  22253. };
  22254. Geometry.prototype.setIndices = function (indices, totalVertices) {
  22255. if (this._indexBuffer) {
  22256. this._engine._releaseBuffer(this._indexBuffer);
  22257. }
  22258. this._indices = indices;
  22259. if (this._meshes.length !== 0 && this._indices) {
  22260. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  22261. }
  22262. if (totalVertices !== undefined) {
  22263. this._totalVertices = totalVertices;
  22264. }
  22265. var meshes = this._meshes;
  22266. var numOfMeshes = meshes.length;
  22267. for (var index = 0; index < numOfMeshes; index++) {
  22268. meshes[index]._createGlobalSubMesh();
  22269. }
  22270. };
  22271. Geometry.prototype.getTotalIndices = function () {
  22272. if (!this.isReady()) {
  22273. return 0;
  22274. }
  22275. return this._indices.length;
  22276. };
  22277. Geometry.prototype.getIndices = function () {
  22278. if (!this.isReady()) {
  22279. return null;
  22280. }
  22281. return this._indices;
  22282. };
  22283. Geometry.prototype.getIndexBuffer = function () {
  22284. if (!this.isReady()) {
  22285. return null;
  22286. }
  22287. return this._indexBuffer;
  22288. };
  22289. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  22290. var meshes = this._meshes;
  22291. var index = meshes.indexOf(mesh);
  22292. if (index === -1) {
  22293. return;
  22294. }
  22295. for (var kind in this._vertexBuffers) {
  22296. this._vertexBuffers[kind].dispose();
  22297. }
  22298. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  22299. this._indexBuffer = null;
  22300. }
  22301. meshes.splice(index, 1);
  22302. mesh._geometry = null;
  22303. if (meshes.length == 0 && shouldDispose) {
  22304. this.dispose();
  22305. }
  22306. };
  22307. Geometry.prototype.applyToMesh = function (mesh) {
  22308. if (mesh._geometry === this) {
  22309. return;
  22310. }
  22311. var previousGeometry = mesh._geometry;
  22312. if (previousGeometry) {
  22313. previousGeometry.releaseForMesh(mesh);
  22314. }
  22315. var meshes = this._meshes;
  22316. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  22317. mesh._geometry = this;
  22318. this._scene.pushGeometry(this);
  22319. meshes.push(mesh);
  22320. if (this.isReady()) {
  22321. this._applyToMesh(mesh);
  22322. } else {
  22323. mesh._boundingInfo = this._boundingInfo;
  22324. }
  22325. };
  22326. Geometry.prototype._applyToMesh = function (mesh) {
  22327. var numOfMeshes = this._meshes.length;
  22328. for (var kind in this._vertexBuffers) {
  22329. if (numOfMeshes === 1) {
  22330. this._vertexBuffers[kind].create();
  22331. }
  22332. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  22333. if (kind === BABYLON.VertexBuffer.PositionKind) {
  22334. mesh._resetPointsArrayCache();
  22335. var extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  22336. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  22337. mesh._createGlobalSubMesh();
  22338. }
  22339. }
  22340. // indexBuffer
  22341. if (numOfMeshes === 1 && this._indices) {
  22342. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  22343. }
  22344. if (this._indexBuffer) {
  22345. this._indexBuffer.references = numOfMeshes;
  22346. }
  22347. };
  22348. Geometry.prototype.load = function (scene, onLoaded) {
  22349. var _this = this;
  22350. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  22351. return;
  22352. }
  22353. if (this.isReady()) {
  22354. if (onLoaded) {
  22355. onLoaded();
  22356. }
  22357. return;
  22358. }
  22359. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  22360. scene._addPendingData(this);
  22361. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  22362. _this._delayLoadingFunction(JSON.parse(data), _this);
  22363. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  22364. _this._delayInfo = [];
  22365. scene._removePendingData(_this);
  22366. var meshes = _this._meshes;
  22367. var numOfMeshes = meshes.length;
  22368. for (var index = 0; index < numOfMeshes; index++) {
  22369. _this._applyToMesh(meshes[index]);
  22370. }
  22371. if (onLoaded) {
  22372. onLoaded();
  22373. }
  22374. }, function () {
  22375. }, scene.database);
  22376. };
  22377. Geometry.prototype.dispose = function () {
  22378. var meshes = this._meshes;
  22379. var numOfMeshes = meshes.length;
  22380. for (var index = 0; index < numOfMeshes; index++) {
  22381. this.releaseForMesh(meshes[index]);
  22382. }
  22383. this._meshes = [];
  22384. for (var kind in this._vertexBuffers) {
  22385. this._vertexBuffers[kind].dispose();
  22386. }
  22387. this._vertexBuffers = [];
  22388. this._totalVertices = 0;
  22389. if (this._indexBuffer) {
  22390. this._engine._releaseBuffer(this._indexBuffer);
  22391. }
  22392. this._indexBuffer = null;
  22393. this._indices = [];
  22394. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  22395. this.delayLoadingFile = null;
  22396. this._delayLoadingFunction = null;
  22397. this._delayInfo = [];
  22398. this._boundingInfo = null; // todo: .dispose()
  22399. var geometries = this._scene.getGeometries();
  22400. index = geometries.indexOf(this);
  22401. if (index > -1) {
  22402. geometries.splice(index, 1);
  22403. }
  22404. };
  22405. Geometry.prototype.copy = function (id) {
  22406. var vertexData = new BABYLON.VertexData();
  22407. vertexData.indices = [];
  22408. var indices = this.getIndices();
  22409. for (var index = 0; index < indices.length; index++) {
  22410. vertexData.indices.push(indices[index]);
  22411. }
  22412. var updatable = false;
  22413. var stopChecking = false;
  22414. for (var kind in this._vertexBuffers) {
  22415. vertexData.set(this.getVerticesData(kind), kind);
  22416. if (!stopChecking) {
  22417. updatable = this.getVertexBuffer(kind).isUpdatable();
  22418. stopChecking = !updatable;
  22419. }
  22420. }
  22421. var geometry = new BABYLON.Geometry(id, this._scene, vertexData, updatable, null);
  22422. geometry.delayLoadState = this.delayLoadState;
  22423. geometry.delayLoadingFile = this.delayLoadingFile;
  22424. geometry._delayLoadingFunction = this._delayLoadingFunction;
  22425. for (kind in this._delayInfo) {
  22426. geometry._delayInfo = geometry._delayInfo || [];
  22427. geometry._delayInfo.push(kind);
  22428. }
  22429. // Bounding info
  22430. var extend = BABYLON.Tools.ExtractMinAndMax(this.getVerticesData(BABYLON.VertexBuffer.PositionKind), 0, this.getTotalVertices());
  22431. geometry._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  22432. return geometry;
  22433. };
  22434. // Statics
  22435. Geometry.ExtractFromMesh = function (mesh, id) {
  22436. var geometry = mesh._geometry;
  22437. if (!geometry) {
  22438. return null;
  22439. }
  22440. return geometry.copy(id);
  22441. };
  22442. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  22443. // be aware Math.random() could cause collisions
  22444. Geometry.RandomId = function () {
  22445. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  22446. var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
  22447. return v.toString(16);
  22448. });
  22449. };
  22450. return Geometry;
  22451. })();
  22452. BABYLON.Geometry = Geometry;
  22453. (function (Geometry) {
  22454. /////// Primitives //////////////////////////////////////////////
  22455. (function (Primitives) {
  22456. /// Abstract class
  22457. var _Primitive = (function (_super) {
  22458. __extends(_Primitive, _super);
  22459. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  22460. this._beingRegenerated = true;
  22461. this._canBeRegenerated = canBeRegenerated;
  22462. _super.call(this, id, scene, vertexData, false, mesh); // updatable = false to be sure not to update vertices
  22463. this._beingRegenerated = false;
  22464. }
  22465. _Primitive.prototype.canBeRegenerated = function () {
  22466. return this._canBeRegenerated;
  22467. };
  22468. _Primitive.prototype.regenerate = function () {
  22469. if (!this._canBeRegenerated) {
  22470. return;
  22471. }
  22472. this._beingRegenerated = true;
  22473. this.setAllVerticesData(this._regenerateVertexData(), false);
  22474. this._beingRegenerated = false;
  22475. };
  22476. _Primitive.prototype.asNewGeometry = function (id) {
  22477. return _super.prototype.copy.call(this, id);
  22478. };
  22479. // overrides
  22480. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  22481. if (!this._beingRegenerated) {
  22482. return;
  22483. }
  22484. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  22485. };
  22486. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  22487. if (!this._beingRegenerated) {
  22488. return;
  22489. }
  22490. _super.prototype.setVerticesData.call(this, kind, data, false);
  22491. };
  22492. // to override
  22493. // protected
  22494. _Primitive.prototype._regenerateVertexData = function () {
  22495. throw new Error("Abstract method");
  22496. };
  22497. _Primitive.prototype.copy = function (id) {
  22498. throw new Error("Must be overriden in sub-classes.");
  22499. };
  22500. return _Primitive;
  22501. })(Geometry);
  22502. Primitives._Primitive = _Primitive;
  22503. var Box = (function (_super) {
  22504. __extends(Box, _super);
  22505. function Box(id, scene, size, canBeRegenerated, mesh) {
  22506. this.size = size;
  22507. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  22508. }
  22509. Box.prototype._regenerateVertexData = function () {
  22510. return BABYLON.VertexData.CreateBox(this.size);
  22511. };
  22512. Box.prototype.copy = function (id) {
  22513. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null);
  22514. };
  22515. return Box;
  22516. })(_Primitive);
  22517. Primitives.Box = Box;
  22518. var Sphere = (function (_super) {
  22519. __extends(Sphere, _super);
  22520. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh) {
  22521. this.segments = segments;
  22522. this.diameter = diameter;
  22523. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  22524. }
  22525. Sphere.prototype._regenerateVertexData = function () {
  22526. return BABYLON.VertexData.CreateSphere(this.segments, this.diameter);
  22527. };
  22528. Sphere.prototype.copy = function (id) {
  22529. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null);
  22530. };
  22531. return Sphere;
  22532. })(_Primitive);
  22533. Primitives.Sphere = Sphere;
  22534. var Cylinder = (function (_super) {
  22535. __extends(Cylinder, _super);
  22536. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh) {
  22537. if (typeof subdivisions === "undefined") { subdivisions = 1; }
  22538. this.height = height;
  22539. this.diameterTop = diameterTop;
  22540. this.diameterBottom = diameterBottom;
  22541. this.tessellation = tessellation;
  22542. this.subdivisions = subdivisions;
  22543. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  22544. }
  22545. Cylinder.prototype._regenerateVertexData = function () {
  22546. return BABYLON.VertexData.CreateCylinder(this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions);
  22547. };
  22548. Cylinder.prototype.copy = function (id) {
  22549. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null);
  22550. };
  22551. return Cylinder;
  22552. })(_Primitive);
  22553. Primitives.Cylinder = Cylinder;
  22554. var Torus = (function (_super) {
  22555. __extends(Torus, _super);
  22556. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh) {
  22557. this.diameter = diameter;
  22558. this.thickness = thickness;
  22559. this.tessellation = tessellation;
  22560. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  22561. }
  22562. Torus.prototype._regenerateVertexData = function () {
  22563. return BABYLON.VertexData.CreateTorus(this.diameter, this.thickness, this.tessellation);
  22564. };
  22565. Torus.prototype.copy = function (id) {
  22566. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null);
  22567. };
  22568. return Torus;
  22569. })(_Primitive);
  22570. Primitives.Torus = Torus;
  22571. var Ground = (function (_super) {
  22572. __extends(Ground, _super);
  22573. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  22574. this.width = width;
  22575. this.height = height;
  22576. this.subdivisions = subdivisions;
  22577. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  22578. }
  22579. Ground.prototype._regenerateVertexData = function () {
  22580. return BABYLON.VertexData.CreateGround(this.width, this.height, this.subdivisions);
  22581. };
  22582. Ground.prototype.copy = function (id) {
  22583. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  22584. };
  22585. return Ground;
  22586. })(_Primitive);
  22587. Primitives.Ground = Ground;
  22588. var TiledGround = (function (_super) {
  22589. __extends(TiledGround, _super);
  22590. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  22591. this.xmin = xmin;
  22592. this.zmin = zmin;
  22593. this.xmax = xmax;
  22594. this.zmax = zmax;
  22595. this.subdivisions = subdivisions;
  22596. this.precision = precision;
  22597. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  22598. }
  22599. TiledGround.prototype._regenerateVertexData = function () {
  22600. return BABYLON.VertexData.CreateTiledGround(this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision);
  22601. };
  22602. TiledGround.prototype.copy = function (id) {
  22603. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  22604. };
  22605. return TiledGround;
  22606. })(_Primitive);
  22607. Primitives.TiledGround = TiledGround;
  22608. var Plane = (function (_super) {
  22609. __extends(Plane, _super);
  22610. function Plane(id, scene, size, canBeRegenerated, mesh) {
  22611. this.size = size;
  22612. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  22613. }
  22614. Plane.prototype._regenerateVertexData = function () {
  22615. return BABYLON.VertexData.CreatePlane(this.size);
  22616. };
  22617. Plane.prototype.copy = function (id) {
  22618. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null);
  22619. };
  22620. return Plane;
  22621. })(_Primitive);
  22622. Primitives.Plane = Plane;
  22623. var TorusKnot = (function (_super) {
  22624. __extends(TorusKnot, _super);
  22625. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh) {
  22626. this.radius = radius;
  22627. this.tube = tube;
  22628. this.radialSegments = radialSegments;
  22629. this.tubularSegments = tubularSegments;
  22630. this.p = p;
  22631. this.q = q;
  22632. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  22633. }
  22634. TorusKnot.prototype._regenerateVertexData = function () {
  22635. return BABYLON.VertexData.CreateTorusKnot(this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q);
  22636. };
  22637. TorusKnot.prototype.copy = function (id) {
  22638. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null);
  22639. };
  22640. return TorusKnot;
  22641. })(_Primitive);
  22642. Primitives.TorusKnot = TorusKnot;
  22643. })(Geometry.Primitives || (Geometry.Primitives = {}));
  22644. var Primitives = Geometry.Primitives;
  22645. })(BABYLON.Geometry || (BABYLON.Geometry = {}));
  22646. var Geometry = BABYLON.Geometry;
  22647. })(BABYLON || (BABYLON = {}));
  22648. //# sourceMappingURL=babylon.geometry.js.map
  22649. var BABYLON;
  22650. (function (BABYLON) {
  22651. var Gamepads = (function () {
  22652. function Gamepads(ongamedpadconnected) {
  22653. var _this = this;
  22654. this.babylonGamepads = [];
  22655. this.oneGamepadConnected = false;
  22656. this.isMonitoring = false;
  22657. this.gamepadEventSupported = 'GamepadEvent' in window;
  22658. this.gamepadSupportAvailable = (navigator.getGamepads || !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  22659. 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=";
  22660. this._callbackGamepadConnected = ongamedpadconnected;
  22661. if (this.gamepadSupportAvailable) {
  22662. // Checking if the gamepad connected event is supported (like in Firefox)
  22663. if (this.gamepadEventSupported) {
  22664. window.addEventListener('gamepadconnected', function (evt) {
  22665. _this._onGamepadConnected(evt);
  22666. }, false);
  22667. window.addEventListener('gamepaddisconnected', function (evt) {
  22668. _this._onGamepadDisconnected(evt);
  22669. }, false);
  22670. } else {
  22671. this._startMonitoringGamepads();
  22672. }
  22673. if (!this.oneGamepadConnected) {
  22674. this._insertGamepadDOMInstructions();
  22675. }
  22676. } else {
  22677. this._insertGamepadDOMNotSupported();
  22678. }
  22679. }
  22680. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  22681. Gamepads.gamepadDOMInfo = document.createElement("div");
  22682. var buttonAImage = document.createElement("img");
  22683. buttonAImage.src = this.buttonADataURL;
  22684. var spanMessage = document.createElement("span");
  22685. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  22686. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  22687. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  22688. Gamepads.gamepadDOMInfo.style.position = "absolute";
  22689. Gamepads.gamepadDOMInfo.style.width = "100%";
  22690. Gamepads.gamepadDOMInfo.style.height = "48px";
  22691. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  22692. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  22693. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  22694. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  22695. buttonAImage.style.position = "relative";
  22696. buttonAImage.style.bottom = "8px";
  22697. spanMessage.style.position = "relative";
  22698. spanMessage.style.fontSize = "32px";
  22699. spanMessage.style.bottom = "32px";
  22700. spanMessage.style.color = "green";
  22701. document.body.appendChild(Gamepads.gamepadDOMInfo);
  22702. };
  22703. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  22704. Gamepads.gamepadDOMInfo = document.createElement("div");
  22705. var spanMessage = document.createElement("span");
  22706. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  22707. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  22708. Gamepads.gamepadDOMInfo.style.position = "absolute";
  22709. Gamepads.gamepadDOMInfo.style.width = "100%";
  22710. Gamepads.gamepadDOMInfo.style.height = "40px";
  22711. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  22712. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  22713. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  22714. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  22715. spanMessage.style.position = "relative";
  22716. spanMessage.style.fontSize = "32px";
  22717. spanMessage.style.color = "red";
  22718. document.body.appendChild(Gamepads.gamepadDOMInfo);
  22719. };
  22720. Gamepads.prototype.dispose = function () {
  22721. document.body.removeChild(Gamepads.gamepadDOMInfo);
  22722. };
  22723. Gamepads.prototype._onGamepadConnected = function (evt) {
  22724. var newGamepad = this._addNewGamepad(evt.gamepad);
  22725. if (this._callbackGamepadConnected)
  22726. this._callbackGamepadConnected(newGamepad);
  22727. this._startMonitoringGamepads();
  22728. };
  22729. Gamepads.prototype._addNewGamepad = function (gamepad) {
  22730. if (!this.oneGamepadConnected) {
  22731. this.oneGamepadConnected = true;
  22732. if (Gamepads.gamepadDOMInfo) {
  22733. document.body.removeChild(Gamepads.gamepadDOMInfo);
  22734. Gamepads.gamepadDOMInfo = null;
  22735. }
  22736. }
  22737. var newGamepad;
  22738. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  22739. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  22740. } else {
  22741. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  22742. }
  22743. this.babylonGamepads.push(newGamepad);
  22744. return newGamepad;
  22745. };
  22746. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  22747. for (var i in this.babylonGamepads) {
  22748. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  22749. this.babylonGamepads.splice(i, 1);
  22750. break;
  22751. }
  22752. }
  22753. // If no gamepads are left, stop the polling loop.
  22754. if (this.babylonGamepads.length == 0) {
  22755. this._stopMonitoringGamepads();
  22756. }
  22757. };
  22758. Gamepads.prototype._startMonitoringGamepads = function () {
  22759. if (!this.isMonitoring) {
  22760. this.isMonitoring = true;
  22761. this._checkGamepadsStatus();
  22762. }
  22763. };
  22764. Gamepads.prototype._stopMonitoringGamepads = function () {
  22765. this.isMonitoring = false;
  22766. };
  22767. Gamepads.prototype._checkGamepadsStatus = function () {
  22768. var _this = this;
  22769. // updating gamepad objects
  22770. this._updateGamepadObjects();
  22771. for (var i in this.babylonGamepads) {
  22772. this.babylonGamepads[i].update();
  22773. }
  22774. if (this.isMonitoring) {
  22775. if (window.requestAnimationFrame) {
  22776. window.requestAnimationFrame(function () {
  22777. _this._checkGamepadsStatus();
  22778. });
  22779. } else if (window.mozRequestAnimationFrame) {
  22780. window.mozRequestAnimationFrame(function () {
  22781. _this._checkGamepadsStatus();
  22782. });
  22783. } else if (window.webkitRequestAnimationFrame) {
  22784. window.webkitRequestAnimationFrame(function () {
  22785. _this._checkGamepadsStatus();
  22786. });
  22787. }
  22788. }
  22789. };
  22790. // This function is called only on Chrome, which does not yet support
  22791. // connection/disconnection events, but requires you to monitor
  22792. // an array for changes.
  22793. Gamepads.prototype._updateGamepadObjects = function () {
  22794. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  22795. for (var i = 0; i < gamepads.length; i++) {
  22796. if (gamepads[i]) {
  22797. if (!(gamepads[i].index in this.babylonGamepads)) {
  22798. var newGamepad = this._addNewGamepad(gamepads[i]);
  22799. if (this._callbackGamepadConnected) {
  22800. this._callbackGamepadConnected(newGamepad);
  22801. }
  22802. } else {
  22803. this.babylonGamepads[i].browserGamepad = gamepads[i];
  22804. }
  22805. }
  22806. }
  22807. };
  22808. return Gamepads;
  22809. })();
  22810. BABYLON.Gamepads = Gamepads;
  22811. var StickValues = (function () {
  22812. function StickValues(x, y) {
  22813. this.x = x;
  22814. this.y = y;
  22815. }
  22816. return StickValues;
  22817. })();
  22818. BABYLON.StickValues = StickValues;
  22819. var Gamepad = (function () {
  22820. function Gamepad(id, index, browserGamepad) {
  22821. this.id = id;
  22822. this.index = index;
  22823. this.browserGamepad = browserGamepad;
  22824. if (this.browserGamepad.axes.length >= 2) {
  22825. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  22826. }
  22827. if (this.browserGamepad.axes.length >= 4) {
  22828. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  22829. }
  22830. }
  22831. Gamepad.prototype.onleftstickchanged = function (callback) {
  22832. this._onleftstickchanged = callback;
  22833. };
  22834. Gamepad.prototype.onrightstickchanged = function (callback) {
  22835. this._onrightstickchanged = callback;
  22836. };
  22837. Object.defineProperty(Gamepad.prototype, "leftStick", {
  22838. get: function () {
  22839. return this._leftStick;
  22840. },
  22841. set: function (newValues) {
  22842. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  22843. this._onleftstickchanged(newValues);
  22844. }
  22845. this._leftStick = newValues;
  22846. },
  22847. enumerable: true,
  22848. configurable: true
  22849. });
  22850. Object.defineProperty(Gamepad.prototype, "rightStick", {
  22851. get: function () {
  22852. return this._rightStick;
  22853. },
  22854. set: function (newValues) {
  22855. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  22856. this._onrightstickchanged(newValues);
  22857. }
  22858. this._rightStick = newValues;
  22859. },
  22860. enumerable: true,
  22861. configurable: true
  22862. });
  22863. Gamepad.prototype.update = function () {
  22864. if (this._leftStick) {
  22865. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  22866. }
  22867. if (this._rightStick) {
  22868. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  22869. }
  22870. };
  22871. return Gamepad;
  22872. })();
  22873. BABYLON.Gamepad = Gamepad;
  22874. var GenericPad = (function (_super) {
  22875. __extends(GenericPad, _super);
  22876. function GenericPad(id, index, gamepad) {
  22877. _super.call(this, id, index, gamepad);
  22878. this.id = id;
  22879. this.index = index;
  22880. this.gamepad = gamepad;
  22881. this._buttons = new Array(gamepad.buttons.length);
  22882. }
  22883. GenericPad.prototype.onbuttondown = function (callback) {
  22884. this._onbuttondown = callback;
  22885. };
  22886. GenericPad.prototype.onbuttonup = function (callback) {
  22887. this._onbuttonup = callback;
  22888. };
  22889. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  22890. if (newValue !== currentValue) {
  22891. if (this._onbuttondown && newValue === 1) {
  22892. this._onbuttondown(buttonIndex);
  22893. }
  22894. if (this._onbuttonup && newValue === 0) {
  22895. this._onbuttonup(buttonIndex);
  22896. }
  22897. }
  22898. return newValue;
  22899. };
  22900. GenericPad.prototype.update = function () {
  22901. _super.prototype.update.call(this);
  22902. for (var index = 0; index < this._buttons.length; index++) {
  22903. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  22904. }
  22905. };
  22906. return GenericPad;
  22907. })(Gamepad);
  22908. BABYLON.GenericPad = GenericPad;
  22909. (function (Xbox360Button) {
  22910. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  22911. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  22912. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  22913. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  22914. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  22915. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  22916. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  22917. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  22918. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  22919. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  22920. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  22921. var Xbox360Button = BABYLON.Xbox360Button;
  22922. (function (Xbox360Dpad) {
  22923. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  22924. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  22925. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  22926. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  22927. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  22928. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  22929. var Xbox360Pad = (function (_super) {
  22930. __extends(Xbox360Pad, _super);
  22931. function Xbox360Pad() {
  22932. _super.apply(this, arguments);
  22933. this._leftTrigger = 0;
  22934. this._rightTrigger = 0;
  22935. this._buttonA = 0;
  22936. this._buttonB = 0;
  22937. this._buttonX = 0;
  22938. this._buttonY = 0;
  22939. this._buttonBack = 0;
  22940. this._buttonStart = 0;
  22941. this._buttonLB = 0;
  22942. this._buttonRB = 0;
  22943. this._buttonLeftStick = 0;
  22944. this._buttonRightStick = 0;
  22945. this._dPadUp = 0;
  22946. this._dPadDown = 0;
  22947. this._dPadLeft = 0;
  22948. this._dPadRight = 0;
  22949. }
  22950. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  22951. this._onlefttriggerchanged = callback;
  22952. };
  22953. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  22954. this._onrighttriggerchanged = callback;
  22955. };
  22956. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  22957. get: function () {
  22958. return this._leftTrigger;
  22959. },
  22960. set: function (newValue) {
  22961. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  22962. this._onlefttriggerchanged(newValue);
  22963. }
  22964. this._leftTrigger = newValue;
  22965. },
  22966. enumerable: true,
  22967. configurable: true
  22968. });
  22969. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  22970. get: function () {
  22971. return this._rightTrigger;
  22972. },
  22973. set: function (newValue) {
  22974. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  22975. this._onrighttriggerchanged(newValue);
  22976. }
  22977. this._rightTrigger = newValue;
  22978. },
  22979. enumerable: true,
  22980. configurable: true
  22981. });
  22982. Xbox360Pad.prototype.onbuttondown = function (callback) {
  22983. this._onbuttondown = callback;
  22984. };
  22985. Xbox360Pad.prototype.onbuttonup = function (callback) {
  22986. this._onbuttonup = callback;
  22987. };
  22988. Xbox360Pad.prototype.ondpaddown = function (callback) {
  22989. this._ondpaddown = callback;
  22990. };
  22991. Xbox360Pad.prototype.ondpadup = function (callback) {
  22992. this._ondpadup = callback;
  22993. };
  22994. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  22995. if (newValue !== currentValue) {
  22996. if (this._onbuttondown && newValue === 1) {
  22997. this._onbuttondown(buttonType);
  22998. }
  22999. if (this._onbuttonup && newValue === 0) {
  23000. this._onbuttonup(buttonType);
  23001. }
  23002. }
  23003. return newValue;
  23004. };
  23005. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  23006. if (newValue !== currentValue) {
  23007. if (this._ondpaddown && newValue === 1) {
  23008. this._ondpaddown(buttonType);
  23009. }
  23010. if (this._ondpadup && newValue === 0) {
  23011. this._ondpadup(buttonType);
  23012. }
  23013. }
  23014. return newValue;
  23015. };
  23016. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  23017. get: function () {
  23018. return this._buttonA;
  23019. },
  23020. set: function (value) {
  23021. this._buttonA = this._setButtonValue(value, this._buttonA, 0 /* A */);
  23022. },
  23023. enumerable: true,
  23024. configurable: true
  23025. });
  23026. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  23027. get: function () {
  23028. return this._buttonB;
  23029. },
  23030. set: function (value) {
  23031. this._buttonB = this._setButtonValue(value, this._buttonB, 1 /* B */);
  23032. },
  23033. enumerable: true,
  23034. configurable: true
  23035. });
  23036. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  23037. get: function () {
  23038. return this._buttonX;
  23039. },
  23040. set: function (value) {
  23041. this._buttonX = this._setButtonValue(value, this._buttonX, 2 /* X */);
  23042. },
  23043. enumerable: true,
  23044. configurable: true
  23045. });
  23046. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  23047. get: function () {
  23048. return this._buttonY;
  23049. },
  23050. set: function (value) {
  23051. this._buttonY = this._setButtonValue(value, this._buttonY, 3 /* Y */);
  23052. },
  23053. enumerable: true,
  23054. configurable: true
  23055. });
  23056. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  23057. get: function () {
  23058. return this._buttonStart;
  23059. },
  23060. set: function (value) {
  23061. this._buttonStart = this._setButtonValue(value, this._buttonStart, 4 /* Start */);
  23062. },
  23063. enumerable: true,
  23064. configurable: true
  23065. });
  23066. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  23067. get: function () {
  23068. return this._buttonBack;
  23069. },
  23070. set: function (value) {
  23071. this._buttonBack = this._setButtonValue(value, this._buttonBack, 5 /* Back */);
  23072. },
  23073. enumerable: true,
  23074. configurable: true
  23075. });
  23076. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  23077. get: function () {
  23078. return this._buttonLB;
  23079. },
  23080. set: function (value) {
  23081. this._buttonLB = this._setButtonValue(value, this._buttonLB, 6 /* LB */);
  23082. },
  23083. enumerable: true,
  23084. configurable: true
  23085. });
  23086. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  23087. get: function () {
  23088. return this._buttonRB;
  23089. },
  23090. set: function (value) {
  23091. this._buttonRB = this._setButtonValue(value, this._buttonRB, 7 /* RB */);
  23092. },
  23093. enumerable: true,
  23094. configurable: true
  23095. });
  23096. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  23097. get: function () {
  23098. return this._buttonLeftStick;
  23099. },
  23100. set: function (value) {
  23101. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, 8 /* LeftStick */);
  23102. },
  23103. enumerable: true,
  23104. configurable: true
  23105. });
  23106. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  23107. get: function () {
  23108. return this._buttonRightStick;
  23109. },
  23110. set: function (value) {
  23111. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, 9 /* RightStick */);
  23112. },
  23113. enumerable: true,
  23114. configurable: true
  23115. });
  23116. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  23117. get: function () {
  23118. return this._dPadUp;
  23119. },
  23120. set: function (value) {
  23121. this._dPadUp = this._setDPadValue(value, this._dPadUp, 0 /* Up */);
  23122. },
  23123. enumerable: true,
  23124. configurable: true
  23125. });
  23126. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  23127. get: function () {
  23128. return this._dPadDown;
  23129. },
  23130. set: function (value) {
  23131. this._dPadDown = this._setDPadValue(value, this._dPadDown, 1 /* Down */);
  23132. },
  23133. enumerable: true,
  23134. configurable: true
  23135. });
  23136. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  23137. get: function () {
  23138. return this._dPadLeft;
  23139. },
  23140. set: function (value) {
  23141. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, 2 /* Left */);
  23142. },
  23143. enumerable: true,
  23144. configurable: true
  23145. });
  23146. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  23147. get: function () {
  23148. return this._dPadRight;
  23149. },
  23150. set: function (value) {
  23151. this._dPadRight = this._setDPadValue(value, this._dPadRight, 3 /* Right */);
  23152. },
  23153. enumerable: true,
  23154. configurable: true
  23155. });
  23156. Xbox360Pad.prototype.update = function () {
  23157. _super.prototype.update.call(this);
  23158. this.buttonA = this.browserGamepad.buttons[0].value;
  23159. this.buttonB = this.browserGamepad.buttons[1].value;
  23160. this.buttonX = this.browserGamepad.buttons[2].value;
  23161. this.buttonY = this.browserGamepad.buttons[3].value;
  23162. this.buttonLB = this.browserGamepad.buttons[4].value;
  23163. this.buttonRB = this.browserGamepad.buttons[5].value;
  23164. this.leftTrigger = this.browserGamepad.buttons[6].value;
  23165. this.rightTrigger = this.browserGamepad.buttons[7].value;
  23166. this.buttonBack = this.browserGamepad.buttons[8].value;
  23167. this.buttonStart = this.browserGamepad.buttons[9].value;
  23168. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  23169. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  23170. this.dPadUp = this.browserGamepad.buttons[12].value;
  23171. this.dPadDown = this.browserGamepad.buttons[13].value;
  23172. this.dPadLeft = this.browserGamepad.buttons[14].value;
  23173. this.dPadRight = this.browserGamepad.buttons[15].value;
  23174. };
  23175. return Xbox360Pad;
  23176. })(Gamepad);
  23177. BABYLON.Xbox360Pad = Xbox360Pad;
  23178. })(BABYLON || (BABYLON = {}));
  23179. //# sourceMappingURL=babylon.gamepads.js.map
  23180. var BABYLON;
  23181. (function (BABYLON) {
  23182. // We're mainly based on the logic defined into the FreeCamera code
  23183. var GamepadCamera = (function (_super) {
  23184. __extends(GamepadCamera, _super);
  23185. function GamepadCamera(name, position, scene) {
  23186. var _this = this;
  23187. _super.call(this, name, position, scene);
  23188. this.angularSensibility = 200;
  23189. this.moveSensibility = 75;
  23190. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  23191. _this._onNewGameConnected(gamepad);
  23192. });
  23193. }
  23194. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  23195. // Only the first gamepad can control the camera
  23196. if (gamepad.index === 0) {
  23197. this._gamepad = gamepad;
  23198. }
  23199. };
  23200. GamepadCamera.prototype._checkInputs = function () {
  23201. if (!this._gamepad) {
  23202. return;
  23203. }
  23204. var LSValues = this._gamepad.leftStick;
  23205. var normalizedLX = LSValues.x / this.moveSensibility;
  23206. var normalizedLY = LSValues.y / this.moveSensibility;
  23207. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  23208. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  23209. var RSValues = this._gamepad.rightStick;
  23210. var normalizedRX = RSValues.x / this.angularSensibility;
  23211. var normalizedRY = RSValues.y / this.angularSensibility;
  23212. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  23213. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  23214. ;
  23215. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  23216. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x, 0, -LSValues.y), cameraTransform);
  23217. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  23218. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  23219. };
  23220. GamepadCamera.prototype.dispose = function () {
  23221. this._gamepads.dispose();
  23222. _super.prototype.dispose.call(this);
  23223. };
  23224. return GamepadCamera;
  23225. })(BABYLON.FreeCamera);
  23226. BABYLON.GamepadCamera = GamepadCamera;
  23227. })(BABYLON || (BABYLON = {}));
  23228. //# sourceMappingURL=babylon.gamepadCamera.js.map
  23229. var BABYLON;
  23230. (function (BABYLON) {
  23231. var LinesMesh = (function (_super) {
  23232. __extends(LinesMesh, _super);
  23233. function LinesMesh(name, scene, updatable) {
  23234. if (typeof updatable === "undefined") { updatable = false; }
  23235. _super.call(this, name, scene);
  23236. this.color = new BABYLON.Color3(1, 1, 1);
  23237. this.alpha = 1;
  23238. this._indices = new Array();
  23239. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  23240. attributes: ["position"],
  23241. uniforms: ["worldViewProjection", "color"],
  23242. needAlphaBlending: true
  23243. });
  23244. }
  23245. Object.defineProperty(LinesMesh.prototype, "material", {
  23246. get: function () {
  23247. return this._colorShader;
  23248. },
  23249. enumerable: true,
  23250. configurable: true
  23251. });
  23252. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  23253. get: function () {
  23254. return false;
  23255. },
  23256. enumerable: true,
  23257. configurable: true
  23258. });
  23259. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  23260. get: function () {
  23261. return false;
  23262. },
  23263. enumerable: true,
  23264. configurable: true
  23265. });
  23266. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  23267. var engine = this.getScene().getEngine();
  23268. var indexToBind = this._geometry.getIndexBuffer();
  23269. // VBOs
  23270. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  23271. // Color
  23272. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  23273. };
  23274. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  23275. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  23276. return;
  23277. }
  23278. var engine = this.getScene().getEngine();
  23279. // Draw order
  23280. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  23281. };
  23282. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  23283. return null;
  23284. };
  23285. LinesMesh.prototype.dispose = function (doNotRecurse) {
  23286. this._colorShader.dispose();
  23287. _super.prototype.dispose.call(this, doNotRecurse);
  23288. };
  23289. return LinesMesh;
  23290. })(BABYLON.Mesh);
  23291. BABYLON.LinesMesh = LinesMesh;
  23292. })(BABYLON || (BABYLON = {}));
  23293. //# sourceMappingURL=babylon.linesMesh.js.map
  23294. var BABYLON;
  23295. (function (BABYLON) {
  23296. var OutlineRenderer = (function () {
  23297. function OutlineRenderer(scene) {
  23298. this._scene = scene;
  23299. }
  23300. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  23301. if (typeof useOverlay === "undefined") { useOverlay = false; }
  23302. var scene = this._scene;
  23303. var engine = this._scene.getEngine();
  23304. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  23305. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  23306. return;
  23307. }
  23308. var mesh = subMesh.getRenderingMesh();
  23309. var material = subMesh.getMaterial();
  23310. engine.enableEffect(this._effect);
  23311. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  23312. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  23313. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  23314. // Bones
  23315. var useBones = mesh.skeleton && scene.skeletonsEnabled && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  23316. if (useBones) {
  23317. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  23318. }
  23319. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  23320. // Alpha test
  23321. if (material && material.needAlphaTesting()) {
  23322. var alphaTexture = material.getAlphaTestTexture();
  23323. this._effect.setTexture("diffuseSampler", alphaTexture);
  23324. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  23325. }
  23326. if (hardwareInstancedRendering) {
  23327. mesh._renderWithInstances(subMesh, BABYLON.Material.TriangleFillMode, batch, this._effect, engine);
  23328. } else {
  23329. if (batch.renderSelf[subMesh._id]) {
  23330. this._effect.setMatrix("world", mesh.getWorldMatrix());
  23331. // Draw
  23332. mesh._draw(subMesh, BABYLON.Material.TriangleFillMode);
  23333. }
  23334. if (batch.visibleInstances[subMesh._id]) {
  23335. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  23336. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  23337. this._effect.setMatrix("world", instance.getWorldMatrix());
  23338. // Draw
  23339. mesh._draw(subMesh, BABYLON.Material.TriangleFillMode);
  23340. }
  23341. }
  23342. }
  23343. };
  23344. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  23345. var defines = [];
  23346. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  23347. var mesh = subMesh.getMesh();
  23348. var material = subMesh.getMaterial();
  23349. // Alpha test
  23350. if (material && material.needAlphaTesting()) {
  23351. defines.push("#define ALPHATEST");
  23352. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  23353. attribs.push(BABYLON.VertexBuffer.UVKind);
  23354. defines.push("#define UV1");
  23355. }
  23356. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  23357. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  23358. defines.push("#define UV2");
  23359. }
  23360. }
  23361. // Bones
  23362. if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  23363. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  23364. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  23365. defines.push("#define BONES");
  23366. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  23367. }
  23368. // Instances
  23369. if (useInstances) {
  23370. defines.push("#define INSTANCES");
  23371. attribs.push("world0");
  23372. attribs.push("world1");
  23373. attribs.push("world2");
  23374. attribs.push("world3");
  23375. }
  23376. // Get correct effect
  23377. var join = defines.join("\n");
  23378. if (this._cachedDefines != join) {
  23379. this._cachedDefines = join;
  23380. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  23381. }
  23382. return this._effect.isReady();
  23383. };
  23384. return OutlineRenderer;
  23385. })();
  23386. BABYLON.OutlineRenderer = OutlineRenderer;
  23387. })(BABYLON || (BABYLON = {}));
  23388. //# sourceMappingURL=babylon.outlineRenderer.js.map
  23389. var BABYLON;
  23390. (function (BABYLON) {
  23391. var MeshAssetTask = (function () {
  23392. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  23393. this.name = name;
  23394. this.meshesNames = meshesNames;
  23395. this.rootUrl = rootUrl;
  23396. this.sceneFilename = sceneFilename;
  23397. this.isCompleted = false;
  23398. }
  23399. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  23400. var _this = this;
  23401. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  23402. _this.loadedMeshes = meshes;
  23403. _this.loadedParticleSystems = particleSystems;
  23404. _this.loadedSkeletons = skeletons;
  23405. _this.isCompleted = true;
  23406. if (_this.onSuccess) {
  23407. _this.onSuccess(_this);
  23408. }
  23409. onSuccess();
  23410. }, null, function () {
  23411. if (_this.onError) {
  23412. _this.onError(_this);
  23413. }
  23414. onError();
  23415. });
  23416. };
  23417. return MeshAssetTask;
  23418. })();
  23419. BABYLON.MeshAssetTask = MeshAssetTask;
  23420. var TextFileAssetTask = (function () {
  23421. function TextFileAssetTask(name, url) {
  23422. this.name = name;
  23423. this.url = url;
  23424. this.isCompleted = false;
  23425. }
  23426. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  23427. var _this = this;
  23428. BABYLON.Tools.LoadFile(this.url, function (data) {
  23429. _this.text = data;
  23430. _this.isCompleted = true;
  23431. if (_this.onSuccess) {
  23432. _this.onSuccess(_this);
  23433. }
  23434. onSuccess();
  23435. }, null, scene.database, false, function () {
  23436. if (_this.onError) {
  23437. _this.onError(_this);
  23438. }
  23439. onError();
  23440. });
  23441. };
  23442. return TextFileAssetTask;
  23443. })();
  23444. BABYLON.TextFileAssetTask = TextFileAssetTask;
  23445. var BinaryFileAssetTask = (function () {
  23446. function BinaryFileAssetTask(name, url) {
  23447. this.name = name;
  23448. this.url = url;
  23449. this.isCompleted = false;
  23450. }
  23451. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  23452. var _this = this;
  23453. BABYLON.Tools.LoadFile(this.url, function (data) {
  23454. _this.data = data;
  23455. _this.isCompleted = true;
  23456. if (_this.onSuccess) {
  23457. _this.onSuccess(_this);
  23458. }
  23459. onSuccess();
  23460. }, null, scene.database, true, function () {
  23461. if (_this.onError) {
  23462. _this.onError(_this);
  23463. }
  23464. onError();
  23465. });
  23466. };
  23467. return BinaryFileAssetTask;
  23468. })();
  23469. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  23470. var ImageAssetTask = (function () {
  23471. function ImageAssetTask(name, url) {
  23472. this.name = name;
  23473. this.url = url;
  23474. this.isCompleted = false;
  23475. }
  23476. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  23477. var _this = this;
  23478. var img = new Image();
  23479. img.onload = function () {
  23480. _this.image = img;
  23481. _this.isCompleted = true;
  23482. if (_this.onSuccess) {
  23483. _this.onSuccess(_this);
  23484. }
  23485. onSuccess();
  23486. };
  23487. img.onerror = function () {
  23488. if (_this.onError) {
  23489. _this.onError(_this);
  23490. }
  23491. onError();
  23492. };
  23493. img.src = this.url;
  23494. };
  23495. return ImageAssetTask;
  23496. })();
  23497. BABYLON.ImageAssetTask = ImageAssetTask;
  23498. var TextureAssetTask = (function () {
  23499. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  23500. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  23501. this.name = name;
  23502. this.url = url;
  23503. this.noMipmap = noMipmap;
  23504. this.invertY = invertY;
  23505. this.samplingMode = samplingMode;
  23506. this.isCompleted = false;
  23507. }
  23508. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  23509. var _this = this;
  23510. var onload = function () {
  23511. _this.isCompleted = true;
  23512. if (_this.onSuccess) {
  23513. _this.onSuccess(_this);
  23514. }
  23515. onSuccess();
  23516. };
  23517. var onerror = function () {
  23518. if (_this.onError) {
  23519. _this.onError(_this);
  23520. }
  23521. onError();
  23522. };
  23523. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onError);
  23524. };
  23525. return TextureAssetTask;
  23526. })();
  23527. BABYLON.TextureAssetTask = TextureAssetTask;
  23528. var AssetsManager = (function () {
  23529. function AssetsManager(scene) {
  23530. this._tasks = new Array();
  23531. this._waitingTasksCount = 0;
  23532. this.useDefaultLoadingScreen = true;
  23533. this._scene = scene;
  23534. }
  23535. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  23536. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  23537. this._tasks.push(task);
  23538. return task;
  23539. };
  23540. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  23541. var task = new TextFileAssetTask(taskName, url);
  23542. this._tasks.push(task);
  23543. return task;
  23544. };
  23545. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  23546. var task = new BinaryFileAssetTask(taskName, url);
  23547. this._tasks.push(task);
  23548. return task;
  23549. };
  23550. AssetsManager.prototype.addImageTask = function (taskName, url) {
  23551. var task = new ImageAssetTask(taskName, url);
  23552. this._tasks.push(task);
  23553. return task;
  23554. };
  23555. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  23556. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  23557. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  23558. this._tasks.push(task);
  23559. return task;
  23560. };
  23561. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  23562. this._waitingTasksCount--;
  23563. if (this._waitingTasksCount === 0) {
  23564. if (this.onFinish) {
  23565. this.onFinish(this._tasks);
  23566. }
  23567. this._scene.getEngine().hideLoadingUI();
  23568. }
  23569. };
  23570. AssetsManager.prototype._runTask = function (task) {
  23571. var _this = this;
  23572. task.run(this._scene, function () {
  23573. if (_this.onTaskSuccess) {
  23574. _this.onTaskSuccess(task);
  23575. }
  23576. _this._decreaseWaitingTasksCount();
  23577. }, function () {
  23578. if (_this.onTaskError) {
  23579. _this.onTaskError(task);
  23580. }
  23581. _this._decreaseWaitingTasksCount();
  23582. });
  23583. };
  23584. AssetsManager.prototype.reset = function () {
  23585. this._tasks = new Array();
  23586. return this;
  23587. };
  23588. AssetsManager.prototype.load = function () {
  23589. this._waitingTasksCount = this._tasks.length;
  23590. if (this._waitingTasksCount === 0) {
  23591. if (this.onFinish) {
  23592. this.onFinish(this._tasks);
  23593. }
  23594. return this;
  23595. }
  23596. if (this.useDefaultLoadingScreen) {
  23597. this._scene.getEngine().displayLoadingUI();
  23598. }
  23599. for (var index = 0; index < this._tasks.length; index++) {
  23600. var task = this._tasks[index];
  23601. this._runTask(task);
  23602. }
  23603. return this;
  23604. };
  23605. return AssetsManager;
  23606. })();
  23607. BABYLON.AssetsManager = AssetsManager;
  23608. })(BABYLON || (BABYLON = {}));
  23609. //# sourceMappingURL=babylon.assetsManager.js.map
  23610. var BABYLON;
  23611. (function (BABYLON) {
  23612. var VRDeviceOrientationCamera = (function (_super) {
  23613. __extends(VRDeviceOrientationCamera, _super);
  23614. function VRDeviceOrientationCamera(name, position, scene) {
  23615. _super.call(this, name, position, scene);
  23616. this._alpha = 0;
  23617. this._beta = 0;
  23618. this._gamma = 0;
  23619. }
  23620. VRDeviceOrientationCamera.prototype._onOrientationEvent = function (evt) {
  23621. this._alpha = +evt.alpha | 0;
  23622. this._beta = +evt.beta | 0;
  23623. this._gamma = +evt.gamma | 0;
  23624. if (this._gamma < 0) {
  23625. this._gamma = 90 + this._gamma;
  23626. } else {
  23627. // Incline it in the correct angle.
  23628. this._gamma = 270 - this._gamma;
  23629. }
  23630. this.rotation.x = this._gamma / 180.0 * Math.PI;
  23631. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  23632. this.rotation.z = this._beta / 180.0 * Math.PI;
  23633. };
  23634. return VRDeviceOrientationCamera;
  23635. })(BABYLON.OculusCamera);
  23636. BABYLON.VRDeviceOrientationCamera = VRDeviceOrientationCamera;
  23637. })(BABYLON || (BABYLON = {}));
  23638. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  23639. var BABYLON;
  23640. (function (BABYLON) {
  23641. var WebVRCamera = (function (_super) {
  23642. __extends(WebVRCamera, _super);
  23643. function WebVRCamera(name, position, scene) {
  23644. _super.call(this, name, position, scene);
  23645. this._hmdDevice = null;
  23646. this._sensorDevice = null;
  23647. this._cacheState = null;
  23648. this._cacheQuaternion = new BABYLON.Quaternion();
  23649. this._cacheRotation = BABYLON.Vector3.Zero();
  23650. this._vrEnabled = false;
  23651. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  23652. }
  23653. WebVRCamera.prototype._getWebVRDevices = function (devices) {
  23654. var size = devices.length;
  23655. var i = 0;
  23656. // Reset devices.
  23657. this._sensorDevice = null;
  23658. this._hmdDevice = null;
  23659. while (i < size && this._hmdDevice === null) {
  23660. if (devices[i] instanceof HMDVRDevice) {
  23661. this._hmdDevice = devices[i];
  23662. }
  23663. i++;
  23664. }
  23665. i = 0;
  23666. while (i < size && this._sensorDevice === null) {
  23667. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  23668. this._sensorDevice = devices[i];
  23669. }
  23670. i++;
  23671. }
  23672. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  23673. };
  23674. WebVRCamera.prototype._update = function () {
  23675. if (this._vrEnabled) {
  23676. this._cacheState = this._sensorDevice.getState();
  23677. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  23678. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  23679. this.rotation.x = -this._cacheRotation.z;
  23680. this.rotation.y = -this._cacheRotation.y;
  23681. this.rotation.z = this._cacheRotation.x;
  23682. }
  23683. _super.prototype._update.call(this);
  23684. };
  23685. WebVRCamera.prototype.attachControl = function (element, noPreventDefault) {
  23686. _super.prototype.attachControl.call(this, element, noPreventDefault);
  23687. if (navigator.getVRDevices) {
  23688. navigator.getVRDevices().then(this._getWebVRDevices);
  23689. } else if (navigator.mozGetVRDevices) {
  23690. navigator.mozGetVRDevices(this._getWebVRDevices);
  23691. }
  23692. };
  23693. WebVRCamera.prototype.detachControl = function (element) {
  23694. _super.prototype.detachControl.call(this, element);
  23695. this._vrEnabled = false;
  23696. };
  23697. return WebVRCamera;
  23698. })(BABYLON.OculusCamera);
  23699. BABYLON.WebVRCamera = WebVRCamera;
  23700. })(BABYLON || (BABYLON = {}));
  23701. //# sourceMappingURL=babylon.webVRCamera.js.map
  23702. var BABYLON;
  23703. (function (BABYLON) {
  23704. // Standard optimizations
  23705. var SceneOptimization = (function () {
  23706. function SceneOptimization(priority) {
  23707. if (typeof priority === "undefined") { priority = 0; }
  23708. this.priority = priority;
  23709. this.apply = function (scene) {
  23710. return true;
  23711. };
  23712. }
  23713. return SceneOptimization;
  23714. })();
  23715. BABYLON.SceneOptimization = SceneOptimization;
  23716. var TextureOptimization = (function (_super) {
  23717. __extends(TextureOptimization, _super);
  23718. function TextureOptimization(priority, maximumSize) {
  23719. if (typeof priority === "undefined") { priority = 0; }
  23720. if (typeof maximumSize === "undefined") { maximumSize = 1024; }
  23721. var _this = this;
  23722. _super.call(this, priority);
  23723. this.priority = priority;
  23724. this.maximumSize = maximumSize;
  23725. this.apply = function (scene) {
  23726. var allDone = true;
  23727. for (var index = 0; index < scene.textures.length; index++) {
  23728. var texture = scene.textures[index];
  23729. if (!texture.canRescale) {
  23730. continue;
  23731. }
  23732. var currentSize = texture.getSize();
  23733. var maxDimension = Math.max(currentSize.width, currentSize.height);
  23734. if (maxDimension > _this.maximumSize) {
  23735. texture.scale(0.5);
  23736. allDone = false;
  23737. }
  23738. }
  23739. return allDone;
  23740. };
  23741. }
  23742. return TextureOptimization;
  23743. })(SceneOptimization);
  23744. BABYLON.TextureOptimization = TextureOptimization;
  23745. var HardwareScalingOptimization = (function (_super) {
  23746. __extends(HardwareScalingOptimization, _super);
  23747. function HardwareScalingOptimization(priority, maximumScale) {
  23748. if (typeof priority === "undefined") { priority = 0; }
  23749. if (typeof maximumScale === "undefined") { maximumScale = 2; }
  23750. var _this = this;
  23751. _super.call(this, priority);
  23752. this.priority = priority;
  23753. this.maximumScale = maximumScale;
  23754. this._currentScale = 1;
  23755. this.apply = function (scene) {
  23756. _this._currentScale++;
  23757. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  23758. return _this._currentScale >= _this.maximumScale;
  23759. };
  23760. }
  23761. return HardwareScalingOptimization;
  23762. })(SceneOptimization);
  23763. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  23764. var ShadowsOptimization = (function (_super) {
  23765. __extends(ShadowsOptimization, _super);
  23766. function ShadowsOptimization() {
  23767. _super.apply(this, arguments);
  23768. this.apply = function (scene) {
  23769. scene.shadowsEnabled = false;
  23770. return true;
  23771. };
  23772. }
  23773. return ShadowsOptimization;
  23774. })(SceneOptimization);
  23775. BABYLON.ShadowsOptimization = ShadowsOptimization;
  23776. var PostProcessesOptimization = (function (_super) {
  23777. __extends(PostProcessesOptimization, _super);
  23778. function PostProcessesOptimization() {
  23779. _super.apply(this, arguments);
  23780. this.apply = function (scene) {
  23781. scene.postProcessesEnabled = false;
  23782. return true;
  23783. };
  23784. }
  23785. return PostProcessesOptimization;
  23786. })(SceneOptimization);
  23787. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  23788. var LensFlaresOptimization = (function (_super) {
  23789. __extends(LensFlaresOptimization, _super);
  23790. function LensFlaresOptimization() {
  23791. _super.apply(this, arguments);
  23792. this.apply = function (scene) {
  23793. scene.lensFlaresEnabled = false;
  23794. return true;
  23795. };
  23796. }
  23797. return LensFlaresOptimization;
  23798. })(SceneOptimization);
  23799. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  23800. var ParticlesOptimization = (function (_super) {
  23801. __extends(ParticlesOptimization, _super);
  23802. function ParticlesOptimization() {
  23803. _super.apply(this, arguments);
  23804. this.apply = function (scene) {
  23805. scene.particlesEnabled = false;
  23806. return true;
  23807. };
  23808. }
  23809. return ParticlesOptimization;
  23810. })(SceneOptimization);
  23811. BABYLON.ParticlesOptimization = ParticlesOptimization;
  23812. var RenderTargetsOptimization = (function (_super) {
  23813. __extends(RenderTargetsOptimization, _super);
  23814. function RenderTargetsOptimization() {
  23815. _super.apply(this, arguments);
  23816. this.apply = function (scene) {
  23817. scene.renderTargetsEnabled = false;
  23818. return true;
  23819. };
  23820. }
  23821. return RenderTargetsOptimization;
  23822. })(SceneOptimization);
  23823. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  23824. var MergeMeshesOptimization = (function (_super) {
  23825. __extends(MergeMeshesOptimization, _super);
  23826. function MergeMeshesOptimization() {
  23827. _super.apply(this, arguments);
  23828. var _this = this;
  23829. this._canBeMerged = function (abstractMesh) {
  23830. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  23831. return false;
  23832. }
  23833. var mesh = abstractMesh;
  23834. if (!mesh.isVisible || !mesh.isEnabled()) {
  23835. return false;
  23836. }
  23837. if (mesh.instances.length > 0) {
  23838. return false;
  23839. }
  23840. if (mesh.skeleton || mesh.hasLODLevels) {
  23841. return false;
  23842. }
  23843. return true;
  23844. };
  23845. this.apply = function (scene) {
  23846. var globalPool = scene.meshes.slice(0);
  23847. var globalLength = globalPool.length;
  23848. for (var index = 0; index < globalLength; index++) {
  23849. var currentPool = new Array();
  23850. var current = globalPool[index];
  23851. // Checks
  23852. if (!_this._canBeMerged(current)) {
  23853. continue;
  23854. }
  23855. currentPool.push(current);
  23856. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  23857. var otherMesh = globalPool[subIndex];
  23858. if (!_this._canBeMerged(otherMesh)) {
  23859. continue;
  23860. }
  23861. if (otherMesh.material !== current.material) {
  23862. continue;
  23863. }
  23864. if (otherMesh.checkCollisions !== current.checkCollisions) {
  23865. continue;
  23866. }
  23867. currentPool.push(otherMesh);
  23868. globalLength--;
  23869. globalPool.splice(subIndex, 1);
  23870. subIndex--;
  23871. }
  23872. if (currentPool.length < 2) {
  23873. continue;
  23874. }
  23875. // Merge meshes
  23876. BABYLON.Mesh.MergeMeshes(currentPool);
  23877. }
  23878. return true;
  23879. };
  23880. }
  23881. return MergeMeshesOptimization;
  23882. })(SceneOptimization);
  23883. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  23884. // Options
  23885. var SceneOptimizerOptions = (function () {
  23886. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  23887. if (typeof targetFrameRate === "undefined") { targetFrameRate = 60; }
  23888. if (typeof trackerDuration === "undefined") { trackerDuration = 2000; }
  23889. this.targetFrameRate = targetFrameRate;
  23890. this.trackerDuration = trackerDuration;
  23891. this.optimizations = new Array();
  23892. }
  23893. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  23894. var result = new SceneOptimizerOptions(targetFrameRate);
  23895. var priority = 0;
  23896. result.optimizations.push(new MergeMeshesOptimization(priority));
  23897. result.optimizations.push(new ShadowsOptimization(priority));
  23898. result.optimizations.push(new LensFlaresOptimization(priority));
  23899. // Next priority
  23900. priority++;
  23901. result.optimizations.push(new PostProcessesOptimization(priority));
  23902. result.optimizations.push(new ParticlesOptimization(priority));
  23903. // Next priority
  23904. priority++;
  23905. result.optimizations.push(new TextureOptimization(priority, 1024));
  23906. return result;
  23907. };
  23908. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  23909. var result = new SceneOptimizerOptions(targetFrameRate);
  23910. var priority = 0;
  23911. result.optimizations.push(new MergeMeshesOptimization(priority));
  23912. result.optimizations.push(new ShadowsOptimization(priority));
  23913. result.optimizations.push(new LensFlaresOptimization(priority));
  23914. // Next priority
  23915. priority++;
  23916. result.optimizations.push(new PostProcessesOptimization(priority));
  23917. result.optimizations.push(new ParticlesOptimization(priority));
  23918. // Next priority
  23919. priority++;
  23920. result.optimizations.push(new TextureOptimization(priority, 512));
  23921. // Next priority
  23922. priority++;
  23923. result.optimizations.push(new RenderTargetsOptimization(priority));
  23924. // Next priority
  23925. priority++;
  23926. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  23927. return result;
  23928. };
  23929. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  23930. var result = new SceneOptimizerOptions(targetFrameRate);
  23931. var priority = 0;
  23932. result.optimizations.push(new MergeMeshesOptimization(priority));
  23933. result.optimizations.push(new ShadowsOptimization(priority));
  23934. result.optimizations.push(new LensFlaresOptimization(priority));
  23935. // Next priority
  23936. priority++;
  23937. result.optimizations.push(new PostProcessesOptimization(priority));
  23938. result.optimizations.push(new ParticlesOptimization(priority));
  23939. // Next priority
  23940. priority++;
  23941. result.optimizations.push(new TextureOptimization(priority, 256));
  23942. // Next priority
  23943. priority++;
  23944. result.optimizations.push(new RenderTargetsOptimization(priority));
  23945. // Next priority
  23946. priority++;
  23947. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  23948. return result;
  23949. };
  23950. return SceneOptimizerOptions;
  23951. })();
  23952. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  23953. // Scene optimizer tool
  23954. var SceneOptimizer = (function () {
  23955. function SceneOptimizer() {
  23956. }
  23957. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  23958. // TODO: add an epsilon
  23959. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  23960. if (onSuccess) {
  23961. onSuccess();
  23962. }
  23963. return;
  23964. }
  23965. // Apply current level of optimizations
  23966. var allDone = true;
  23967. var noOptimizationApplied = true;
  23968. for (var index = 0; index < options.optimizations.length; index++) {
  23969. var optimization = options.optimizations[index];
  23970. if (optimization.priority === currentPriorityLevel) {
  23971. noOptimizationApplied = false;
  23972. allDone = allDone && optimization.apply(scene);
  23973. }
  23974. }
  23975. // If no optimization was applied, this is a failure :(
  23976. if (noOptimizationApplied) {
  23977. if (onFailure) {
  23978. onFailure();
  23979. }
  23980. return;
  23981. }
  23982. // If all optimizations were done, move to next level
  23983. if (allDone) {
  23984. currentPriorityLevel++;
  23985. }
  23986. // Let's the system running for a specific amount of time before checking FPS
  23987. scene.executeWhenReady(function () {
  23988. setTimeout(function () {
  23989. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  23990. }, options.trackerDuration);
  23991. });
  23992. };
  23993. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  23994. if (!options) {
  23995. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  23996. }
  23997. // Let's the system running for a specific amount of time before checking FPS
  23998. scene.executeWhenReady(function () {
  23999. setTimeout(function () {
  24000. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  24001. }, options.trackerDuration);
  24002. });
  24003. };
  24004. return SceneOptimizer;
  24005. })();
  24006. BABYLON.SceneOptimizer = SceneOptimizer;
  24007. })(BABYLON || (BABYLON = {}));
  24008. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  24009. var BABYLON;
  24010. (function (BABYLON) {
  24011. (function (Internals) {
  24012. var MeshLODLevel = (function () {
  24013. function MeshLODLevel(distance, mesh) {
  24014. this.distance = distance;
  24015. this.mesh = mesh;
  24016. }
  24017. return MeshLODLevel;
  24018. })();
  24019. Internals.MeshLODLevel = MeshLODLevel;
  24020. })(BABYLON.Internals || (BABYLON.Internals = {}));
  24021. var Internals = BABYLON.Internals;
  24022. })(BABYLON || (BABYLON = {}));
  24023. //# sourceMappingURL=babylon.meshLODLevel.js.map
  24024. var BABYLON;
  24025. (function (BABYLON) {
  24026. var AudioEngine = (function () {
  24027. function AudioEngine() {
  24028. this.audioContext = null;
  24029. this.canUseWebAudio = false;
  24030. try {
  24031. if (typeof AudioContext !== 'undefined') {
  24032. this.audioContext = new AudioContext();
  24033. this.canUseWebAudio = true;
  24034. } else if (typeof webkitAudioContext !== 'undefined') {
  24035. this.audioContext = new webkitAudioContext();
  24036. this.canUseWebAudio = true;
  24037. }
  24038. } catch (e) {
  24039. this.canUseWebAudio = false;
  24040. }
  24041. // create a global volume gain node
  24042. if (this.canUseWebAudio) {
  24043. this.masterGain = this.audioContext.createGain();
  24044. this.masterGain.gain.value = 1;
  24045. this.masterGain.connect(this.audioContext.destination);
  24046. }
  24047. }
  24048. AudioEngine.prototype.getGlobalVolume = function () {
  24049. if (this.canUseWebAudio) {
  24050. return this.masterGain.gain.value;
  24051. } else {
  24052. return -1;
  24053. }
  24054. };
  24055. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  24056. if (this.canUseWebAudio) {
  24057. this.masterGain.gain.value = newVolume;
  24058. }
  24059. };
  24060. return AudioEngine;
  24061. })();
  24062. BABYLON.AudioEngine = AudioEngine;
  24063. })(BABYLON || (BABYLON = {}));
  24064. //# sourceMappingURL=babylon.audioengine.js.map
  24065. var BABYLON;
  24066. (function (BABYLON) {
  24067. var Sound = (function () {
  24068. /**
  24069. * Create a sound and attach it to a scene
  24070. * @param name Name of your sound
  24071. * @param url Url to the sound to load async
  24072. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  24073. * @param options Objects to provide with the current available options: autoplay, loop, distanceMax
  24074. */
  24075. function Sound(name, url, scene, readyToPlayCallback, options) {
  24076. var _this = this;
  24077. this.maxDistance = 20;
  24078. this.autoplay = false;
  24079. this.loop = false;
  24080. this.useBabylonJSAttenuation = true;
  24081. this._position = BABYLON.Vector3.Zero();
  24082. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  24083. this._volume = 1;
  24084. this._isLoaded = false;
  24085. this._isReadyToPlay = false;
  24086. this._isPlaying = false;
  24087. this._isDirectional = false;
  24088. // Used if you'd like to create a directional sound.
  24089. // If not set, the sound will be omnidirectional
  24090. this._coneInnerAngle = null;
  24091. this._coneOuterAngle = null;
  24092. this._coneOuterGain = null;
  24093. this._name = name;
  24094. this._scene = scene;
  24095. this._audioEngine = this._scene.getEngine().getAudioEngine();
  24096. this._readyToPlayCallback = readyToPlayCallback;
  24097. this._attenuationFunction = function (currentVolume, currentDistance, maxDistance) {
  24098. return currentVolume * (1 - currentDistance / maxDistance);
  24099. };
  24100. if (options) {
  24101. if (options.maxDistance) {
  24102. this.maxDistance = options.maxDistance;
  24103. }
  24104. if (options.autoplay) {
  24105. this.autoplay = options.autoplay;
  24106. }
  24107. if (options.loop) {
  24108. this.loop = options.loop;
  24109. }
  24110. if (options.volume) {
  24111. this._volume = options.volume;
  24112. }
  24113. if (options.useBabylonJSAttenuation) {
  24114. this.useBabylonJSAttenuation = options.useBabylonJSAttenuation;
  24115. }
  24116. }
  24117. if (this._audioEngine.canUseWebAudio) {
  24118. this._soundGain = this._audioEngine.audioContext.createGain();
  24119. this._soundGain.gain.value = this._volume;
  24120. this._soundPanner = this._audioEngine.audioContext.createPanner();
  24121. this._soundPanner.connect(this._soundGain);
  24122. this._scene.mainSoundTrack.AddSound(this);
  24123. BABYLON.Tools.LoadFile(url, function (data) {
  24124. _this._soundLoaded(data);
  24125. }, null, null, true);
  24126. }
  24127. }
  24128. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  24129. if (this._audioEngine.canUseWebAudio) {
  24130. this._soundGain.disconnect();
  24131. this._soundGain.connect(soundTrackAudioNode);
  24132. }
  24133. };
  24134. /**
  24135. * Transform this sound into a directional source
  24136. * @param coneInnerAngle Size of the inner cone in degree
  24137. * @param coneOuterAngle Size of the outer cone in degree
  24138. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  24139. */
  24140. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  24141. if (coneOuterAngle < coneInnerAngle) {
  24142. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  24143. return;
  24144. }
  24145. this._coneInnerAngle = coneInnerAngle;
  24146. this._coneOuterAngle = coneOuterAngle;
  24147. this._coneOuterGain = coneOuterGain;
  24148. this._isDirectional = true;
  24149. if (this._isPlaying && this.loop) {
  24150. this.stop();
  24151. this.play();
  24152. }
  24153. };
  24154. Sound.prototype.setPosition = function (newPosition) {
  24155. this._position = newPosition;
  24156. if (this._isPlaying) {
  24157. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  24158. }
  24159. };
  24160. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  24161. this._localDirection = newLocalDirection;
  24162. if (this._connectedMesh && this._isPlaying) {
  24163. this._updateDirection();
  24164. }
  24165. };
  24166. Sound.prototype._updateDirection = function () {
  24167. var mat = this._connectedMesh.getWorldMatrix();
  24168. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  24169. direction.normalize();
  24170. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  24171. };
  24172. Sound.prototype.updateDistanceFromListener = function () {
  24173. if (this._connectedMesh) {
  24174. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  24175. if (this.useBabylonJSAttenuation) {
  24176. if (distance < this.maxDistance) {
  24177. //this._soundGain.gain.value = this._volume * (1 - distance / this.maxDistance);
  24178. this._soundGain.gain.value = this._attenuationFunction(this._volume, distance, this.maxDistance);
  24179. } else {
  24180. this._soundGain.gain.value = 0;
  24181. }
  24182. }
  24183. }
  24184. };
  24185. Sound.prototype.setAttenuationFunction = function (callback) {
  24186. this._attenuationFunction = callback;
  24187. };
  24188. /**
  24189. * Play the sound
  24190. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  24191. */
  24192. Sound.prototype.play = function (time) {
  24193. if (this._isReadyToPlay) {
  24194. try {
  24195. var startTime = time ? this._audioEngine.audioContext.currentTime + time : 0;
  24196. this._soundSource = this._audioEngine.audioContext.createBufferSource();
  24197. this._soundSource.buffer = this._audioBuffer;
  24198. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  24199. if (this._isDirectional) {
  24200. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  24201. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  24202. this._soundPanner.coneOuterGain = this._coneOuterGain;
  24203. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  24204. }
  24205. this._soundSource.connect(this._soundPanner);
  24206. this._soundSource.loop = this.loop;
  24207. this._soundSource.start(startTime);
  24208. this._isPlaying = true;
  24209. } catch (ex) {
  24210. BABYLON.Tools.Error("Error while trying to play audio: " + this._name + ", " + ex.message);
  24211. }
  24212. }
  24213. };
  24214. /**
  24215. * Stop the sound
  24216. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  24217. */
  24218. Sound.prototype.stop = function (time) {
  24219. var stopTime = time ? this._audioEngine.audioContext.currentTime + time : 0;
  24220. this._soundSource.stop(stopTime);
  24221. this._isPlaying = false;
  24222. };
  24223. Sound.prototype.pause = function () {
  24224. //this._soundSource.p
  24225. };
  24226. Sound.prototype.setVolume = function (newVolume) {
  24227. this._volume = newVolume;
  24228. };
  24229. Sound.prototype.getVolume = function () {
  24230. return this._volume;
  24231. };
  24232. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  24233. var _this = this;
  24234. this._connectedMesh = meshToConnectTo;
  24235. meshToConnectTo.registerAfterWorldMatrixUpdate(function (connectedMesh) {
  24236. return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh);
  24237. });
  24238. };
  24239. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  24240. this.setPosition(connectedMesh.position);
  24241. if (this._isDirectional && this._isPlaying) {
  24242. this._updateDirection();
  24243. }
  24244. };
  24245. Sound.prototype._soundLoaded = function (audioData) {
  24246. var _this = this;
  24247. this._isLoaded = true;
  24248. this._audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  24249. _this._audioBuffer = buffer;
  24250. _this._isReadyToPlay = true;
  24251. if (_this.autoplay) {
  24252. _this.play();
  24253. }
  24254. if (_this._readyToPlayCallback) {
  24255. _this._readyToPlayCallback();
  24256. }
  24257. }, function (error) {
  24258. BABYLON.Tools.Error("Error while decoding audio data: " + error.err);
  24259. });
  24260. };
  24261. return Sound;
  24262. })();
  24263. BABYLON.Sound = Sound;
  24264. })(BABYLON || (BABYLON = {}));
  24265. //# sourceMappingURL=babylon.sound.js.map
  24266. var BABYLON;
  24267. (function (BABYLON) {
  24268. var SoundTrack = (function () {
  24269. function SoundTrack(scene, options) {
  24270. this.id = -1;
  24271. this._isMainTrack = false;
  24272. this._scene = scene;
  24273. this._audioEngine = scene.getEngine().getAudioEngine();
  24274. this.soundCollection = new Array();
  24275. if (this._audioEngine.canUseWebAudio) {
  24276. this._trackGain = this._audioEngine.audioContext.createGain();
  24277. //this._trackConvolver = this._audioEngine.audioContext.createConvolver();
  24278. //this._trackConvolver.connect(this._trackGain);
  24279. this._trackGain.connect(this._audioEngine.masterGain);
  24280. if (options) {
  24281. if (options.volume) {
  24282. this._trackGain.gain.value = options.volume;
  24283. }
  24284. if (options.mainTrack) {
  24285. this._isMainTrack = options.mainTrack;
  24286. }
  24287. }
  24288. }
  24289. if (!this._isMainTrack) {
  24290. this._scene.soundTracks.push(this);
  24291. this.id = this._scene.soundTracks.length - 1;
  24292. }
  24293. }
  24294. SoundTrack.prototype.AddSound = function (sound) {
  24295. sound.connectToSoundTrackAudioNode(this._trackGain);
  24296. if (sound.soundTrackId) {
  24297. if (sound.soundTrackId === -1) {
  24298. this._scene.mainSoundTrack.RemoveSound(sound);
  24299. } else {
  24300. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  24301. }
  24302. }
  24303. this.soundCollection.push(sound);
  24304. sound.soundTrackId = this.id;
  24305. };
  24306. SoundTrack.prototype.RemoveSound = function (sound) {
  24307. var index = this.soundCollection.indexOf(sound);
  24308. if (index !== -1) {
  24309. this.soundCollection.splice(index, 1);
  24310. }
  24311. };
  24312. SoundTrack.prototype.setVolume = function (newVolume) {
  24313. if (this._audioEngine.canUseWebAudio) {
  24314. this._trackGain.gain.value = newVolume;
  24315. }
  24316. };
  24317. return SoundTrack;
  24318. })();
  24319. BABYLON.SoundTrack = SoundTrack;
  24320. })(BABYLON || (BABYLON = {}));
  24321. //# sourceMappingURL=babylon.soundtrack.js.map
  24322. var BABYLON;
  24323. (function (BABYLON) {
  24324. var DebugLayer = (function () {
  24325. function DebugLayer(scene) {
  24326. var _this = this;
  24327. this._enabled = false;
  24328. this._labelsEnabled = false;
  24329. this._displayStatistics = true;
  24330. this._displayTree = false;
  24331. this._displayLogs = false;
  24332. this._identityMatrix = BABYLON.Matrix.Identity();
  24333. this.axisRatio = 0.02;
  24334. this.accentColor = "orange";
  24335. this._scene = scene;
  24336. this._syncPositions = function () {
  24337. var engine = _this._scene.getEngine();
  24338. var canvasRect = engine.getRenderingCanvasClientRect();
  24339. if (_this._showUI) {
  24340. _this._statsDiv.style.left = (canvasRect.width - 310) + "px";
  24341. _this._statsDiv.style.top = (canvasRect.height - 370) + "px";
  24342. _this._statsDiv.style.width = "300px";
  24343. _this._statsDiv.style.height = "360px";
  24344. _this._statsSubsetDiv.style.maxHeight = (canvasRect.height - 60) + "px";
  24345. _this._optionsDiv.style.left = "0px";
  24346. _this._optionsDiv.style.top = "10px";
  24347. _this._optionsDiv.style.width = "200px";
  24348. _this._optionsDiv.style.height = "auto";
  24349. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  24350. _this._logDiv.style.left = "0px";
  24351. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  24352. _this._logDiv.style.width = "600px";
  24353. _this._logDiv.style.height = "160px";
  24354. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  24355. _this._treeDiv.style.top = "10px";
  24356. _this._treeDiv.style.width = "300px";
  24357. _this._treeDiv.style.height = "auto";
  24358. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 430) + "px";
  24359. }
  24360. _this._globalDiv.style.left = canvasRect.left + "px";
  24361. _this._globalDiv.style.top = canvasRect.top + "px";
  24362. _this._drawingCanvas.style.left = "0px";
  24363. _this._drawingCanvas.style.top = "0px";
  24364. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  24365. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  24366. var devicePixelRatio = window.devicePixelRatio || 1;
  24367. var context = _this._drawingContext;
  24368. var backingStoreRatio = context.webkitBackingStorePixelRatio || context.mozBackingStorePixelRatio || context.msBackingStorePixelRatio || context.oBackingStorePixelRatio || context.backingStorePixelRatio || 1;
  24369. _this._ratio = devicePixelRatio / backingStoreRatio;
  24370. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  24371. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  24372. };
  24373. this._onCanvasClick = function (evt) {
  24374. _this._clickPosition = {
  24375. x: evt.clientX * _this._ratio,
  24376. y: evt.clientY * _this._ratio
  24377. };
  24378. };
  24379. this._syncData = function () {
  24380. if (_this._showUI) {
  24381. if (_this._displayStatistics) {
  24382. _this._displayStats();
  24383. _this._statsDiv.style.display = "";
  24384. } else {
  24385. _this._statsDiv.style.display = "none";
  24386. }
  24387. if (_this._displayLogs) {
  24388. _this._logDiv.style.display = "";
  24389. } else {
  24390. _this._logDiv.style.display = "none";
  24391. }
  24392. if (_this._displayTree) {
  24393. _this._treeDiv.style.display = "";
  24394. if (_this._needToRefreshMeshesTree) {
  24395. _this._needToRefreshMeshesTree = false;
  24396. _this._refreshMeshesTreeContent();
  24397. }
  24398. } else {
  24399. _this._treeDiv.style.display = "none";
  24400. }
  24401. }
  24402. if (_this._labelsEnabled || !_this._showUI) {
  24403. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  24404. var engine = _this._scene.getEngine();
  24405. var viewport = _this._scene.activeCamera.viewport;
  24406. var globalViewport = viewport.toGlobal(engine);
  24407. // Meshes
  24408. var meshes = _this._scene.getActiveMeshes();
  24409. for (var index = 0; index < meshes.length; index++) {
  24410. var mesh = meshes.data[index];
  24411. var position = mesh.getBoundingInfo().boundingSphere.center;
  24412. var projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._scene.getTransformMatrix(), globalViewport);
  24413. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  24414. _this._renderAxis(projectedPosition, mesh, globalViewport);
  24415. }
  24416. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  24417. _this._renderLabel(mesh.name, projectedPosition, 12, function () {
  24418. mesh.renderOverlay = !mesh.renderOverlay;
  24419. }, function () {
  24420. return mesh.renderOverlay ? 'red' : 'black';
  24421. });
  24422. }
  24423. }
  24424. // Cameras
  24425. var cameras = _this._scene.cameras;
  24426. for (index = 0; index < cameras.length; index++) {
  24427. var camera = cameras[index];
  24428. if (camera === _this._scene.activeCamera) {
  24429. continue;
  24430. }
  24431. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._scene.getTransformMatrix(), globalViewport);
  24432. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  24433. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  24434. _this._scene.activeCamera.detachControl(engine.getRenderingCanvas());
  24435. _this._scene.activeCamera = camera;
  24436. _this._scene.activeCamera.attachControl(engine.getRenderingCanvas());
  24437. }, function () {
  24438. return "purple";
  24439. });
  24440. }
  24441. }
  24442. // Lights
  24443. var lights = _this._scene.lights;
  24444. for (index = 0; index < lights.length; index++) {
  24445. var light = lights[index];
  24446. if (light.position) {
  24447. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._scene.getTransformMatrix(), globalViewport);
  24448. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  24449. _this._renderLabel(light.name, projectedPosition, -20, function () {
  24450. light.setEnabled(!light.isEnabled());
  24451. }, function () {
  24452. return light.isEnabled() ? "orange" : "gray";
  24453. });
  24454. }
  24455. }
  24456. }
  24457. }
  24458. _this._clickPosition = undefined;
  24459. };
  24460. }
  24461. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  24462. while (this._treeSubsetDiv.hasChildNodes()) {
  24463. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  24464. }
  24465. // Add meshes
  24466. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  24467. sortedArray.sort(function (a, b) {
  24468. if (a.name === b.name) {
  24469. return 0;
  24470. }
  24471. return (a.name > b.name) ? 1 : -1;
  24472. });
  24473. for (var index = 0; index < sortedArray.length; index++) {
  24474. var mesh = sortedArray[index];
  24475. if (!mesh.isEnabled()) {
  24476. continue;
  24477. }
  24478. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  24479. m.isVisible = element.checked;
  24480. }, mesh);
  24481. }
  24482. };
  24483. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  24484. this._drawingContext.beginPath();
  24485. this._drawingContext.moveTo(zero.x, zero.y);
  24486. this._drawingContext.lineTo(unit.x, unit.y);
  24487. this._drawingContext.strokeStyle = color;
  24488. this._drawingContext.lineWidth = 4;
  24489. this._drawingContext.stroke();
  24490. this._drawingContext.font = "normal 14px Segoe UI";
  24491. this._drawingContext.fillStyle = color;
  24492. this._drawingContext.fillText(label, unitText.x, unitText.y);
  24493. };
  24494. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  24495. var position = mesh.getBoundingInfo().boundingSphere.center;
  24496. var worldMatrix = mesh.getWorldMatrix();
  24497. 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());
  24498. var unit = (unprojectedVector.subtract(position)).length();
  24499. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  24500. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  24501. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  24502. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  24503. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  24504. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  24505. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  24506. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  24507. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  24508. };
  24509. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  24510. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  24511. this._drawingContext.font = "normal 12px Segoe UI";
  24512. var textMetrics = this._drawingContext.measureText(text);
  24513. var centerX = projectedPosition.x - textMetrics.width / 2;
  24514. var centerY = projectedPosition.y;
  24515. if (this._isClickInsideRect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  24516. onClick();
  24517. }
  24518. this._drawingContext.beginPath();
  24519. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  24520. this._drawingContext.fillStyle = getFillStyle();
  24521. this._drawingContext.globalAlpha = 0.5;
  24522. this._drawingContext.fill();
  24523. this._drawingContext.globalAlpha = 1.0;
  24524. this._drawingContext.strokeStyle = '#FFFFFF';
  24525. this._drawingContext.lineWidth = 1;
  24526. this._drawingContext.stroke();
  24527. this._drawingContext.fillStyle = "#FFFFFF";
  24528. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  24529. this._drawingContext.beginPath();
  24530. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  24531. this._drawingContext.fill();
  24532. }
  24533. };
  24534. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  24535. if (!this._clickPosition) {
  24536. return false;
  24537. }
  24538. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  24539. return false;
  24540. }
  24541. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  24542. return false;
  24543. }
  24544. return true;
  24545. };
  24546. DebugLayer.prototype.isVisible = function () {
  24547. return this._enabled;
  24548. };
  24549. DebugLayer.prototype.hide = function () {
  24550. if (!this._enabled) {
  24551. return;
  24552. }
  24553. this._enabled = false;
  24554. var engine = this._scene.getEngine();
  24555. this._scene.unregisterAfterRender(this._syncData);
  24556. document.body.removeChild(this._globalDiv);
  24557. window.removeEventListener("resize", this._syncPositions);
  24558. this._scene.forceShowBoundingBoxes = false;
  24559. this._scene.forceWireframe = false;
  24560. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  24561. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  24562. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  24563. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  24564. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  24565. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  24566. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  24567. this._scene.shadowsEnabled = true;
  24568. this._scene.particlesEnabled = true;
  24569. this._scene.postProcessesEnabled = true;
  24570. this._scene.collisionsEnabled = true;
  24571. this._scene.lightsEnabled = true;
  24572. this._scene.texturesEnabled = true;
  24573. this._scene.lensFlaresEnabled = true;
  24574. this._scene.proceduralTexturesEnabled = true;
  24575. this._scene.renderTargetsEnabled = true;
  24576. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  24577. };
  24578. DebugLayer.prototype.show = function (showUI) {
  24579. if (typeof showUI === "undefined") { showUI = true; }
  24580. if (this._enabled) {
  24581. return;
  24582. }
  24583. this._enabled = true;
  24584. this._showUI = showUI;
  24585. var engine = this._scene.getEngine();
  24586. this._globalDiv = document.createElement("div");
  24587. document.body.appendChild(this._globalDiv);
  24588. this._generateDOMelements();
  24589. window.addEventListener("resize", this._syncPositions);
  24590. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  24591. this._syncPositions();
  24592. this._scene.registerAfterRender(this._syncData);
  24593. };
  24594. DebugLayer.prototype._clearLabels = function () {
  24595. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  24596. for (var index = 0; index < this._scene.meshes.length; index++) {
  24597. var mesh = this._scene.meshes[index];
  24598. mesh.renderOverlay = false;
  24599. }
  24600. };
  24601. DebugLayer.prototype._generateheader = function (root, text) {
  24602. var header = document.createElement("div");
  24603. header.innerHTML = text + "&nbsp;";
  24604. header.style.textAlign = "right";
  24605. header.style.width = "100%";
  24606. header.style.color = "white";
  24607. header.style.backgroundColor = "Black";
  24608. header.style.padding = "5px 5px 4px 0px";
  24609. header.style.marginLeft = "-5px";
  24610. header.style.fontWeight = "bold";
  24611. root.appendChild(header);
  24612. };
  24613. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  24614. var label = document.createElement("label");
  24615. label.innerHTML = title;
  24616. label.style.color = color;
  24617. root.appendChild(label);
  24618. root.appendChild(document.createElement("br"));
  24619. };
  24620. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  24621. if (typeof tag === "undefined") { tag = null; }
  24622. var label = document.createElement("label");
  24623. var boundingBoxesCheckbox = document.createElement("input");
  24624. boundingBoxesCheckbox.type = "checkbox";
  24625. boundingBoxesCheckbox.checked = initialState;
  24626. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  24627. task(evt.target, tag);
  24628. });
  24629. label.appendChild(boundingBoxesCheckbox);
  24630. var container = document.createElement("span");
  24631. var leftPart = document.createElement("span");
  24632. var rightPart = document.createElement("span");
  24633. rightPart.style.cssFloat = "right";
  24634. leftPart.innerHTML = leftTitle;
  24635. rightPart.innerHTML = rightTitle;
  24636. rightPart.style.fontSize = "12px";
  24637. rightPart.style.maxWidth = "200px";
  24638. container.appendChild(leftPart);
  24639. container.appendChild(rightPart);
  24640. label.appendChild(container);
  24641. root.appendChild(label);
  24642. root.appendChild(document.createElement("br"));
  24643. };
  24644. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  24645. if (typeof tag === "undefined") { tag = null; }
  24646. var label = document.createElement("label");
  24647. var boundingBoxesCheckbox = document.createElement("input");
  24648. boundingBoxesCheckbox.type = "checkbox";
  24649. boundingBoxesCheckbox.checked = initialState;
  24650. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  24651. task(evt.target, tag);
  24652. });
  24653. label.appendChild(boundingBoxesCheckbox);
  24654. label.appendChild(document.createTextNode(title));
  24655. root.appendChild(label);
  24656. root.appendChild(document.createElement("br"));
  24657. };
  24658. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  24659. if (typeof tag === "undefined") { tag = null; }
  24660. var label = document.createElement("label");
  24661. var boundingBoxesRadio = document.createElement("input");
  24662. boundingBoxesRadio.type = "radio";
  24663. boundingBoxesRadio.name = name;
  24664. boundingBoxesRadio.checked = initialState;
  24665. boundingBoxesRadio.addEventListener("change", function (evt) {
  24666. task(evt.target, tag);
  24667. });
  24668. label.appendChild(boundingBoxesRadio);
  24669. label.appendChild(document.createTextNode(title));
  24670. root.appendChild(label);
  24671. root.appendChild(document.createElement("br"));
  24672. };
  24673. DebugLayer.prototype._generateDOMelements = function () {
  24674. var _this = this;
  24675. this._globalDiv.id = "DebugLayer";
  24676. this._globalDiv.style.position = "absolute";
  24677. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  24678. this._globalDiv.style.fontSize = "14px";
  24679. this._globalDiv.style.color = "white";
  24680. // Drawing canvas
  24681. this._drawingCanvas = document.createElement("canvas");
  24682. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  24683. this._drawingCanvas.style.position = "absolute";
  24684. this._drawingCanvas.style.pointerEvents = "none";
  24685. this._drawingContext = this._drawingCanvas.getContext("2d");
  24686. this._globalDiv.appendChild(this._drawingCanvas);
  24687. if (this._showUI) {
  24688. var background = "rgba(128, 128, 128, 0.4)";
  24689. var border = "rgb(180, 180, 180) solid 1px";
  24690. // Stats
  24691. this._statsDiv = document.createElement("div");
  24692. this._statsDiv.id = "DebugLayerStats";
  24693. this._statsDiv.style.border = border;
  24694. this._statsDiv.style.position = "absolute";
  24695. this._statsDiv.style.background = background;
  24696. this._statsDiv.style.padding = "0px 0px 0px 5px";
  24697. this._statsDiv.style.pointerEvents = "none";
  24698. this._statsDiv.style.overflowY = "auto";
  24699. this._generateheader(this._statsDiv, "STATISTICS");
  24700. this._statsSubsetDiv = document.createElement("div");
  24701. this._statsSubsetDiv.style.paddingTop = "5px";
  24702. this._statsSubsetDiv.style.paddingBottom = "5px";
  24703. this._statsDiv.appendChild(this._statsSubsetDiv);
  24704. // Tree
  24705. this._treeDiv = document.createElement("div");
  24706. this._treeDiv.id = "DebugLayerTree";
  24707. this._treeDiv.style.border = border;
  24708. this._treeDiv.style.position = "absolute";
  24709. this._treeDiv.style.background = background;
  24710. this._treeDiv.style.padding = "0px 0px 0px 5px";
  24711. this._treeDiv.style.display = "none";
  24712. this._generateheader(this._treeDiv, "MESHES TREE");
  24713. this._treeSubsetDiv = document.createElement("div");
  24714. this._treeSubsetDiv.style.paddingTop = "5px";
  24715. this._treeSubsetDiv.style.paddingRight = "5px";
  24716. this._treeSubsetDiv.style.overflowY = "auto";
  24717. this._treeSubsetDiv.style.maxHeight = "300px";
  24718. this._treeDiv.appendChild(this._treeSubsetDiv);
  24719. this._needToRefreshMeshesTree = true;
  24720. // Logs
  24721. this._logDiv = document.createElement("div");
  24722. this._logDiv.style.border = border;
  24723. this._logDiv.id = "DebugLayerLogs";
  24724. this._logDiv.style.position = "absolute";
  24725. this._logDiv.style.background = background;
  24726. this._logDiv.style.padding = "0px 0px 0px 5px";
  24727. this._logDiv.style.display = "none";
  24728. this._generateheader(this._logDiv, "LOGS");
  24729. this._logSubsetDiv = document.createElement("div");
  24730. this._logSubsetDiv.style.height = "127px";
  24731. this._logSubsetDiv.style.paddingTop = "5px";
  24732. this._logSubsetDiv.style.overflowY = "auto";
  24733. this._logSubsetDiv.style.fontSize = "12px";
  24734. this._logSubsetDiv.style.fontFamily = "consolas";
  24735. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  24736. this._logDiv.appendChild(this._logSubsetDiv);
  24737. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  24738. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  24739. };
  24740. // Options
  24741. this._optionsDiv = document.createElement("div");
  24742. this._optionsDiv.id = "DebugLayerOptions";
  24743. this._optionsDiv.style.border = border;
  24744. this._optionsDiv.style.position = "absolute";
  24745. this._optionsDiv.style.background = background;
  24746. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  24747. this._optionsDiv.style.overflowY = "auto";
  24748. this._generateheader(this._optionsDiv, "OPTIONS");
  24749. this._optionsSubsetDiv = document.createElement("div");
  24750. this._optionsSubsetDiv.style.paddingTop = "5px";
  24751. this._optionsSubsetDiv.style.paddingBottom = "5px";
  24752. this._optionsSubsetDiv.style.overflowY = "auto";
  24753. this._optionsSubsetDiv.style.maxHeight = "200px";
  24754. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  24755. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  24756. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) {
  24757. _this._displayStatistics = element.checked;
  24758. });
  24759. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) {
  24760. _this._displayLogs = element.checked;
  24761. });
  24762. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  24763. _this._displayTree = element.checked;
  24764. _this._needToRefreshMeshesTree = true;
  24765. });
  24766. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) {
  24767. _this._scene.forceShowBoundingBoxes = element.checked;
  24768. });
  24769. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  24770. _this._labelsEnabled = element.checked;
  24771. if (!_this._labelsEnabled) {
  24772. _this._clearLabels();
  24773. }
  24774. });
  24775. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  24776. if (element.checked) {
  24777. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  24778. } else {
  24779. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  24780. }
  24781. });
  24782. ;
  24783. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  24784. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  24785. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  24786. if (element.checked) {
  24787. _this._scene.forceWireframe = false;
  24788. _this._scene.forcePointsCloud = false;
  24789. }
  24790. });
  24791. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  24792. if (element.checked) {
  24793. _this._scene.forceWireframe = true;
  24794. _this._scene.forcePointsCloud = false;
  24795. }
  24796. });
  24797. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  24798. if (element.checked) {
  24799. _this._scene.forceWireframe = false;
  24800. _this._scene.forcePointsCloud = true;
  24801. }
  24802. });
  24803. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  24804. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  24805. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) {
  24806. BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked;
  24807. });
  24808. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) {
  24809. BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked;
  24810. });
  24811. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) {
  24812. BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked;
  24813. });
  24814. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) {
  24815. BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked;
  24816. });
  24817. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) {
  24818. BABYLON.StandardMaterial.BumpTextureEnabled = element.checked;
  24819. });
  24820. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) {
  24821. BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked;
  24822. });
  24823. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) {
  24824. BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked;
  24825. });
  24826. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) {
  24827. BABYLON.StandardMaterial.FresnelEnabled = element.checked;
  24828. });
  24829. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  24830. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  24831. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) {
  24832. _this._scene.animationsEnabled = element.checked;
  24833. });
  24834. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) {
  24835. _this._scene.collisionsEnabled = element.checked;
  24836. });
  24837. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) {
  24838. _this._scene.fogEnabled = element.checked;
  24839. });
  24840. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) {
  24841. _this._scene.lensFlaresEnabled = element.checked;
  24842. });
  24843. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) {
  24844. _this._scene.lightsEnabled = element.checked;
  24845. });
  24846. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) {
  24847. _this._scene.particlesEnabled = element.checked;
  24848. });
  24849. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) {
  24850. _this._scene.postProcessesEnabled = element.checked;
  24851. });
  24852. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) {
  24853. _this._scene.proceduralTexturesEnabled = element.checked;
  24854. });
  24855. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) {
  24856. _this._scene.renderTargetsEnabled = element.checked;
  24857. });
  24858. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) {
  24859. _this._scene.shadowsEnabled = element.checked;
  24860. });
  24861. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) {
  24862. _this._scene.skeletonsEnabled = element.checked;
  24863. });
  24864. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) {
  24865. _this._scene.texturesEnabled = element.checked;
  24866. });
  24867. this._globalDiv.appendChild(this._statsDiv);
  24868. this._globalDiv.appendChild(this._logDiv);
  24869. this._globalDiv.appendChild(this._optionsDiv);
  24870. this._globalDiv.appendChild(this._treeDiv);
  24871. }
  24872. };
  24873. DebugLayer.prototype._displayStats = function () {
  24874. var scene = this._scene;
  24875. var engine = scene.getEngine();
  24876. 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>";
  24877. };
  24878. return DebugLayer;
  24879. })();
  24880. BABYLON.DebugLayer = DebugLayer;
  24881. })(BABYLON || (BABYLON = {}));
  24882. //# sourceMappingURL=babylon.debugLayer.js.map
  24883. var BABYLON;
  24884. (function (BABYLON) {
  24885. var RawTexture = (function (_super) {
  24886. __extends(RawTexture, _super);
  24887. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  24888. if (typeof generateMipMaps === "undefined") { generateMipMaps = true; }
  24889. if (typeof invertY === "undefined") { invertY = false; }
  24890. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  24891. _super.call(this, null, scene, !generateMipMaps, invertY);
  24892. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  24893. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  24894. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  24895. }
  24896. // Statics
  24897. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  24898. if (typeof generateMipMaps === "undefined") { generateMipMaps = true; }
  24899. if (typeof invertY === "undefined") { invertY = false; }
  24900. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  24901. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  24902. };
  24903. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  24904. if (typeof generateMipMaps === "undefined") { generateMipMaps = true; }
  24905. if (typeof invertY === "undefined") { invertY = false; }
  24906. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  24907. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  24908. };
  24909. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  24910. if (typeof generateMipMaps === "undefined") { generateMipMaps = true; }
  24911. if (typeof invertY === "undefined") { invertY = false; }
  24912. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  24913. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  24914. };
  24915. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  24916. if (typeof generateMipMaps === "undefined") { generateMipMaps = true; }
  24917. if (typeof invertY === "undefined") { invertY = false; }
  24918. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  24919. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  24920. };
  24921. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  24922. if (typeof generateMipMaps === "undefined") { generateMipMaps = true; }
  24923. if (typeof invertY === "undefined") { invertY = false; }
  24924. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  24925. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  24926. };
  24927. return RawTexture;
  24928. })(BABYLON.Texture);
  24929. BABYLON.RawTexture = RawTexture;
  24930. })(BABYLON || (BABYLON = {}));
  24931. //# sourceMappingURL=babylon.rawTexture.js.map
  24932. var BABYLON;
  24933. (function (BABYLON) {
  24934. var IndexedVector2 = (function (_super) {
  24935. __extends(IndexedVector2, _super);
  24936. function IndexedVector2(original, index) {
  24937. _super.call(this, original.x, original.y);
  24938. this.index = index;
  24939. }
  24940. return IndexedVector2;
  24941. })(BABYLON.Vector2);
  24942. var PolygonPoints = (function () {
  24943. function PolygonPoints() {
  24944. this.elements = new Array();
  24945. }
  24946. PolygonPoints.prototype.add = function (originalPoints) {
  24947. var _this = this;
  24948. var result = new Array();
  24949. originalPoints.forEach(function (point) {
  24950. if (result.length === 0 || !(BABYLON.Tools.WithinEpsilon(point.x, result[0].x) && BABYLON.Tools.WithinEpsilon(point.y, result[0].y))) {
  24951. var newPoint = new IndexedVector2(point, _this.elements.length);
  24952. result.push(newPoint);
  24953. _this.elements.push(newPoint);
  24954. }
  24955. });
  24956. return result;
  24957. };
  24958. PolygonPoints.prototype.computeBounds = function () {
  24959. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  24960. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  24961. this.elements.forEach(function (point) {
  24962. // x
  24963. if (point.x < lmin.x) {
  24964. lmin.x = point.x;
  24965. } else if (point.x > lmax.x) {
  24966. lmax.x = point.x;
  24967. }
  24968. // y
  24969. if (point.y < lmin.y) {
  24970. lmin.y = point.y;
  24971. } else if (point.y > lmax.y) {
  24972. lmax.y = point.y;
  24973. }
  24974. });
  24975. return {
  24976. min: lmin,
  24977. max: lmax,
  24978. width: lmax.x - lmin.x,
  24979. height: lmax.y - lmin.y
  24980. };
  24981. };
  24982. return PolygonPoints;
  24983. })();
  24984. var Polygon = (function () {
  24985. function Polygon() {
  24986. }
  24987. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  24988. return [
  24989. new BABYLON.Vector2(xmin, ymin),
  24990. new BABYLON.Vector2(xmax, ymin),
  24991. new BABYLON.Vector2(xmax, ymax),
  24992. new BABYLON.Vector2(xmin, ymax)
  24993. ];
  24994. };
  24995. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  24996. if (typeof cx === "undefined") { cx = 0; }
  24997. if (typeof cy === "undefined") { cy = 0; }
  24998. if (typeof numberOfSides === "undefined") { numberOfSides = 32; }
  24999. var result = new Array();
  25000. var angle = 0;
  25001. var increment = (Math.PI * 2) / numberOfSides;
  25002. for (var i = 0; i < numberOfSides; i++) {
  25003. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  25004. angle -= increment;
  25005. }
  25006. return result;
  25007. };
  25008. Polygon.Parse = function (input) {
  25009. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) {
  25010. return (!isNaN(val));
  25011. });
  25012. var i, result = [];
  25013. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  25014. result.push(new poly2tri.Point(floats[i], floats[i + 1]));
  25015. }
  25016. return result;
  25017. };
  25018. Polygon.StartingAt = function (x, y) {
  25019. return BABYLON.Path2.StartingAt(x, y);
  25020. };
  25021. return Polygon;
  25022. })();
  25023. BABYLON.Polygon = Polygon;
  25024. var PolygonMeshBuilder = (function () {
  25025. function PolygonMeshBuilder(name, contours, scene) {
  25026. this.name = name;
  25027. this.scene = scene;
  25028. this._points = new PolygonPoints();
  25029. if (!("poly2tri" in window)) {
  25030. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  25031. }
  25032. this._swctx = new poly2tri.SweepContext(this._points.add(contours));
  25033. }
  25034. PolygonMeshBuilder.prototype.addHole = function (hole) {
  25035. this._swctx.addHole(this._points.add(hole));
  25036. return this;
  25037. };
  25038. PolygonMeshBuilder.prototype.build = function (updatable) {
  25039. if (typeof updatable === "undefined") { updatable = false; }
  25040. var result = new BABYLON.Mesh(this.name, this.scene);
  25041. var normals = [];
  25042. var positions = [];
  25043. var uvs = [];
  25044. var bounds = this._points.computeBounds();
  25045. this._points.elements.forEach(function (p) {
  25046. normals.push(0, 1.0, 0);
  25047. positions.push(p.x, 0, p.y);
  25048. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  25049. });
  25050. var indices = [];
  25051. this._swctx.triangulate();
  25052. this._swctx.getTriangles().forEach(function (triangle) {
  25053. triangle.getPoints().forEach(function (point) {
  25054. indices.push(point.index);
  25055. });
  25056. });
  25057. result.setVerticesData(positions, BABYLON.VertexBuffer.PositionKind, updatable);
  25058. result.setVerticesData(normals, BABYLON.VertexBuffer.NormalKind, updatable);
  25059. result.setVerticesData(uvs, BABYLON.VertexBuffer.UVKind, updatable);
  25060. result.setIndices(indices);
  25061. return result;
  25062. };
  25063. return PolygonMeshBuilder;
  25064. })();
  25065. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  25066. })(BABYLON || (BABYLON = {}));
  25067. //# sourceMappingURL=babylon.polygonMesh.js.map