babylon.2.1-alpha.debug.js 1.4 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024
  1. var __extends = this.__extends || function (d, b) {
  2. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  3. function __() { this.constructor = d; }
  4. __.prototype = b.prototype;
  5. d.prototype = new __();
  6. };var BABYLON;
  7. (function (BABYLON) {
  8. var Color3 = (function () {
  9. function Color3(r, g, b) {
  10. if (r === void 0) { r = 0; }
  11. if (g === void 0) { g = 0; }
  12. if (b === void 0) { b = 0; }
  13. this.r = r;
  14. this.g = g;
  15. this.b = b;
  16. }
  17. Color3.prototype.toString = function () {
  18. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  19. };
  20. // Operators
  21. Color3.prototype.toArray = function (array, index) {
  22. if (index === undefined) {
  23. index = 0;
  24. }
  25. array[index] = this.r;
  26. array[index + 1] = this.g;
  27. array[index + 2] = this.b;
  28. return this;
  29. };
  30. Color3.prototype.toColor4 = function (alpha) {
  31. if (alpha === void 0) { alpha = 1; }
  32. return new Color4(this.r, this.g, this.b, alpha);
  33. };
  34. Color3.prototype.asArray = function () {
  35. var result = [];
  36. this.toArray(result, 0);
  37. return result;
  38. };
  39. Color3.prototype.toLuminance = function () {
  40. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  41. };
  42. Color3.prototype.multiply = function (otherColor) {
  43. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  44. };
  45. Color3.prototype.multiplyToRef = function (otherColor, result) {
  46. result.r = this.r * otherColor.r;
  47. result.g = this.g * otherColor.g;
  48. result.b = this.b * otherColor.b;
  49. return this;
  50. };
  51. Color3.prototype.equals = function (otherColor) {
  52. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  53. };
  54. Color3.prototype.scale = function (scale) {
  55. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  56. };
  57. Color3.prototype.scaleToRef = function (scale, result) {
  58. result.r = this.r * scale;
  59. result.g = this.g * scale;
  60. result.b = this.b * scale;
  61. return this;
  62. };
  63. Color3.prototype.add = function (otherColor) {
  64. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  65. };
  66. Color3.prototype.addToRef = function (otherColor, result) {
  67. result.r = this.r + otherColor.r;
  68. result.g = this.g + otherColor.g;
  69. result.b = this.b + otherColor.b;
  70. return this;
  71. };
  72. Color3.prototype.subtract = function (otherColor) {
  73. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  74. };
  75. Color3.prototype.subtractToRef = function (otherColor, result) {
  76. result.r = this.r - otherColor.r;
  77. result.g = this.g - otherColor.g;
  78. result.b = this.b - otherColor.b;
  79. return this;
  80. };
  81. Color3.prototype.clone = function () {
  82. return new Color3(this.r, this.g, this.b);
  83. };
  84. Color3.prototype.copyFrom = function (source) {
  85. this.r = source.r;
  86. this.g = source.g;
  87. this.b = source.b;
  88. return this;
  89. };
  90. Color3.prototype.copyFromFloats = function (r, g, b) {
  91. this.r = r;
  92. this.g = g;
  93. this.b = b;
  94. return this;
  95. };
  96. // Statics
  97. Color3.FromArray = function (array, offset) {
  98. if (offset === void 0) { offset = 0; }
  99. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  100. };
  101. Color3.FromInts = function (r, g, b) {
  102. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  103. };
  104. Color3.Lerp = function (start, end, amount) {
  105. var r = start.r + ((end.r - start.r) * amount);
  106. var g = start.g + ((end.g - start.g) * amount);
  107. var b = start.b + ((end.b - start.b) * amount);
  108. return new Color3(r, g, b);
  109. };
  110. Color3.Red = function () {
  111. return new Color3(1, 0, 0);
  112. };
  113. Color3.Green = function () {
  114. return new Color3(0, 1, 0);
  115. };
  116. Color3.Blue = function () {
  117. return new Color3(0, 0, 1);
  118. };
  119. Color3.Black = function () {
  120. return new Color3(0, 0, 0);
  121. };
  122. Color3.White = function () {
  123. return new Color3(1, 1, 1);
  124. };
  125. Color3.Purple = function () {
  126. return new Color3(0.5, 0, 0.5);
  127. };
  128. Color3.Magenta = function () {
  129. return new Color3(1, 0, 1);
  130. };
  131. Color3.Yellow = function () {
  132. return new Color3(1, 1, 0);
  133. };
  134. Color3.Gray = function () {
  135. return new Color3(0.5, 0.5, 0.5);
  136. };
  137. return Color3;
  138. })();
  139. BABYLON.Color3 = Color3;
  140. var Color4 = (function () {
  141. function Color4(r, g, b, a) {
  142. this.r = r;
  143. this.g = g;
  144. this.b = b;
  145. this.a = a;
  146. }
  147. // Operators
  148. Color4.prototype.addInPlace = function (right) {
  149. this.r += right.r;
  150. this.g += right.g;
  151. this.b += right.b;
  152. this.a += right.a;
  153. return this;
  154. };
  155. Color4.prototype.asArray = function () {
  156. var result = [];
  157. this.toArray(result, 0);
  158. return result;
  159. };
  160. Color4.prototype.toArray = function (array, index) {
  161. if (index === undefined) {
  162. index = 0;
  163. }
  164. array[index] = this.r;
  165. array[index + 1] = this.g;
  166. array[index + 2] = this.b;
  167. array[index + 3] = this.a;
  168. return this;
  169. };
  170. Color4.prototype.add = function (right) {
  171. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  172. };
  173. Color4.prototype.subtract = function (right) {
  174. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  175. };
  176. Color4.prototype.subtractToRef = function (right, result) {
  177. result.r = this.r - right.r;
  178. result.g = this.g - right.g;
  179. result.b = this.b - right.b;
  180. result.a = this.a - right.a;
  181. return this;
  182. };
  183. Color4.prototype.scale = function (scale) {
  184. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  185. };
  186. Color4.prototype.scaleToRef = function (scale, result) {
  187. result.r = this.r * scale;
  188. result.g = this.g * scale;
  189. result.b = this.b * scale;
  190. result.a = this.a * scale;
  191. return this;
  192. };
  193. Color4.prototype.toString = function () {
  194. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  195. };
  196. Color4.prototype.clone = function () {
  197. return new Color4(this.r, this.g, this.b, this.a);
  198. };
  199. Color4.prototype.copyFrom = function (source) {
  200. this.r = source.r;
  201. this.g = source.g;
  202. this.b = source.b;
  203. this.a = source.a;
  204. return this;
  205. };
  206. // Statics
  207. Color4.Lerp = function (left, right, amount) {
  208. var result = new Color4(0, 0, 0, 0);
  209. Color4.LerpToRef(left, right, amount, result);
  210. return result;
  211. };
  212. Color4.LerpToRef = function (left, right, amount, result) {
  213. result.r = left.r + (right.r - left.r) * amount;
  214. result.g = left.g + (right.g - left.g) * amount;
  215. result.b = left.b + (right.b - left.b) * amount;
  216. result.a = left.a + (right.a - left.a) * amount;
  217. };
  218. Color4.FromArray = function (array, offset) {
  219. if (offset === void 0) { offset = 0; }
  220. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  221. };
  222. Color4.FromInts = function (r, g, b, a) {
  223. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  224. };
  225. return Color4;
  226. })();
  227. BABYLON.Color4 = Color4;
  228. var Vector2 = (function () {
  229. function Vector2(x, y) {
  230. this.x = x;
  231. this.y = y;
  232. }
  233. Vector2.prototype.toString = function () {
  234. return "{X: " + this.x + " Y:" + this.y + "}";
  235. };
  236. // Operators
  237. Vector2.prototype.toArray = function (array, index) {
  238. if (index === void 0) { index = 0; }
  239. array[index] = this.x;
  240. array[index + 1] = this.y;
  241. return this;
  242. };
  243. Vector2.prototype.asArray = function () {
  244. var result = [];
  245. this.toArray(result, 0);
  246. return result;
  247. };
  248. Vector2.prototype.copyFrom = function (source) {
  249. this.x = source.x;
  250. this.y = source.y;
  251. return this;
  252. };
  253. Vector2.prototype.copyFromFloats = function (x, y) {
  254. this.x = x;
  255. this.y = y;
  256. return this;
  257. };
  258. Vector2.prototype.add = function (otherVector) {
  259. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  260. };
  261. Vector2.prototype.addVector3 = function (otherVector) {
  262. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  263. };
  264. Vector2.prototype.subtract = function (otherVector) {
  265. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  266. };
  267. Vector2.prototype.subtractInPlace = function (otherVector) {
  268. this.x -= otherVector.x;
  269. this.y -= otherVector.y;
  270. return this;
  271. };
  272. Vector2.prototype.multiplyInPlace = function (otherVector) {
  273. this.x *= otherVector.x;
  274. this.y *= otherVector.y;
  275. return this;
  276. };
  277. Vector2.prototype.multiply = function (otherVector) {
  278. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  279. };
  280. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  281. result.x = this.x * otherVector.x;
  282. result.y = this.y * otherVector.y;
  283. return this;
  284. };
  285. Vector2.prototype.multiplyByFloats = function (x, y) {
  286. return new Vector2(this.x * x, this.y * y);
  287. };
  288. Vector2.prototype.divide = function (otherVector) {
  289. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  290. };
  291. Vector2.prototype.divideToRef = function (otherVector, result) {
  292. result.x = this.x / otherVector.x;
  293. result.y = this.y / otherVector.y;
  294. return this;
  295. };
  296. Vector2.prototype.negate = function () {
  297. return new Vector2(-this.x, -this.y);
  298. };
  299. Vector2.prototype.scaleInPlace = function (scale) {
  300. this.x *= scale;
  301. this.y *= scale;
  302. return this;
  303. };
  304. Vector2.prototype.scale = function (scale) {
  305. return new Vector2(this.x * scale, this.y * scale);
  306. };
  307. Vector2.prototype.equals = function (otherVector) {
  308. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  309. };
  310. // Properties
  311. Vector2.prototype.length = function () {
  312. return Math.sqrt(this.x * this.x + this.y * this.y);
  313. };
  314. Vector2.prototype.lengthSquared = function () {
  315. return (this.x * this.x + this.y * this.y);
  316. };
  317. // Methods
  318. Vector2.prototype.normalize = function () {
  319. var len = this.length();
  320. if (len === 0)
  321. return this;
  322. var num = 1.0 / len;
  323. this.x *= num;
  324. this.y *= num;
  325. return this;
  326. };
  327. Vector2.prototype.clone = function () {
  328. return new Vector2(this.x, this.y);
  329. };
  330. // Statics
  331. Vector2.Zero = function () {
  332. return new Vector2(0, 0);
  333. };
  334. Vector2.FromArray = function (array, offset) {
  335. if (offset === void 0) { offset = 0; }
  336. return new Vector2(array[offset], array[offset + 1]);
  337. };
  338. Vector2.FromArrayToRef = function (array, offset, result) {
  339. result.x = array[offset];
  340. result.y = array[offset + 1];
  341. };
  342. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  343. var squared = amount * amount;
  344. var cubed = amount * squared;
  345. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) + (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) + ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  346. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) + (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) + ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  347. return new Vector2(x, y);
  348. };
  349. Vector2.Clamp = function (value, min, max) {
  350. var x = value.x;
  351. x = (x > max.x) ? max.x : x;
  352. x = (x < min.x) ? min.x : x;
  353. var y = value.y;
  354. y = (y > max.y) ? max.y : y;
  355. y = (y < min.y) ? min.y : y;
  356. return new Vector2(x, y);
  357. };
  358. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  359. var squared = amount * amount;
  360. var cubed = amount * squared;
  361. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  362. var part2 = (-2.0 * cubed) + (3.0 * squared);
  363. var part3 = (cubed - (2.0 * squared)) + amount;
  364. var part4 = cubed - squared;
  365. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  366. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  367. return new Vector2(x, y);
  368. };
  369. Vector2.Lerp = function (start, end, amount) {
  370. var x = start.x + ((end.x - start.x) * amount);
  371. var y = start.y + ((end.y - start.y) * amount);
  372. return new Vector2(x, y);
  373. };
  374. Vector2.Dot = function (left, right) {
  375. return left.x * right.x + left.y * right.y;
  376. };
  377. Vector2.Normalize = function (vector) {
  378. var newVector = vector.clone();
  379. newVector.normalize();
  380. return newVector;
  381. };
  382. Vector2.Minimize = function (left, right) {
  383. var x = (left.x < right.x) ? left.x : right.x;
  384. var y = (left.y < right.y) ? left.y : right.y;
  385. return new Vector2(x, y);
  386. };
  387. Vector2.Maximize = function (left, right) {
  388. var x = (left.x > right.x) ? left.x : right.x;
  389. var y = (left.y > right.y) ? left.y : right.y;
  390. return new Vector2(x, y);
  391. };
  392. Vector2.Transform = function (vector, transformation) {
  393. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]);
  394. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]);
  395. return new Vector2(x, y);
  396. };
  397. Vector2.Distance = function (value1, value2) {
  398. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  399. };
  400. Vector2.DistanceSquared = function (value1, value2) {
  401. var x = value1.x - value2.x;
  402. var y = value1.y - value2.y;
  403. return (x * x) + (y * y);
  404. };
  405. return Vector2;
  406. })();
  407. BABYLON.Vector2 = Vector2;
  408. var Vector3 = (function () {
  409. function Vector3(x, y, z) {
  410. this.x = x;
  411. this.y = y;
  412. this.z = z;
  413. }
  414. Vector3.prototype.toString = function () {
  415. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  416. };
  417. // Operators
  418. Vector3.prototype.asArray = function () {
  419. var result = [];
  420. this.toArray(result, 0);
  421. return result;
  422. };
  423. Vector3.prototype.toArray = function (array, index) {
  424. if (index === void 0) { index = 0; }
  425. array[index] = this.x;
  426. array[index + 1] = this.y;
  427. array[index + 2] = this.z;
  428. return this;
  429. };
  430. Vector3.prototype.toQuaternion = function () {
  431. var result = new Quaternion(0, 0, 0, 1);
  432. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  433. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  434. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  435. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  436. var cosy = Math.cos(this.y * 0.5);
  437. var siny = Math.sin(this.y * 0.5);
  438. result.x = coszMinusx * siny;
  439. result.y = -sinzMinusx * siny;
  440. result.z = sinxPlusz * cosy;
  441. result.w = cosxPlusz * cosy;
  442. return result;
  443. };
  444. Vector3.prototype.addInPlace = function (otherVector) {
  445. this.x += otherVector.x;
  446. this.y += otherVector.y;
  447. this.z += otherVector.z;
  448. return this;
  449. };
  450. Vector3.prototype.add = function (otherVector) {
  451. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  452. };
  453. Vector3.prototype.addToRef = function (otherVector, result) {
  454. result.x = this.x + otherVector.x;
  455. result.y = this.y + otherVector.y;
  456. result.z = this.z + otherVector.z;
  457. return this;
  458. };
  459. Vector3.prototype.subtractInPlace = function (otherVector) {
  460. this.x -= otherVector.x;
  461. this.y -= otherVector.y;
  462. this.z -= otherVector.z;
  463. return this;
  464. };
  465. Vector3.prototype.subtract = function (otherVector) {
  466. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  467. };
  468. Vector3.prototype.subtractToRef = function (otherVector, result) {
  469. result.x = this.x - otherVector.x;
  470. result.y = this.y - otherVector.y;
  471. result.z = this.z - otherVector.z;
  472. return this;
  473. };
  474. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  475. return new Vector3(this.x - x, this.y - y, this.z - z);
  476. };
  477. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  478. result.x = this.x - x;
  479. result.y = this.y - y;
  480. result.z = this.z - z;
  481. return this;
  482. };
  483. Vector3.prototype.negate = function () {
  484. return new Vector3(-this.x, -this.y, -this.z);
  485. };
  486. Vector3.prototype.scaleInPlace = function (scale) {
  487. this.x *= scale;
  488. this.y *= scale;
  489. this.z *= scale;
  490. return this;
  491. };
  492. Vector3.prototype.scale = function (scale) {
  493. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  494. };
  495. Vector3.prototype.scaleToRef = function (scale, result) {
  496. result.x = this.x * scale;
  497. result.y = this.y * scale;
  498. result.z = this.z * scale;
  499. };
  500. Vector3.prototype.equals = function (otherVector) {
  501. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  502. };
  503. Vector3.prototype.equalsWithEpsilon = function (otherVector) {
  504. return Math.abs(this.x - otherVector.x) < BABYLON.Engine.Epsilon && Math.abs(this.y - otherVector.y) < BABYLON.Engine.Epsilon && Math.abs(this.z - otherVector.z) < BABYLON.Engine.Epsilon;
  505. };
  506. Vector3.prototype.equalsToFloats = function (x, y, z) {
  507. return this.x === x && this.y === y && this.z === z;
  508. };
  509. Vector3.prototype.multiplyInPlace = function (otherVector) {
  510. this.x *= otherVector.x;
  511. this.y *= otherVector.y;
  512. this.z *= otherVector.z;
  513. return this;
  514. };
  515. Vector3.prototype.multiply = function (otherVector) {
  516. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  517. };
  518. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  519. result.x = this.x * otherVector.x;
  520. result.y = this.y * otherVector.y;
  521. result.z = this.z * otherVector.z;
  522. return this;
  523. };
  524. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  525. return new Vector3(this.x * x, this.y * y, this.z * z);
  526. };
  527. Vector3.prototype.divide = function (otherVector) {
  528. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  529. };
  530. Vector3.prototype.divideToRef = function (otherVector, result) {
  531. result.x = this.x / otherVector.x;
  532. result.y = this.y / otherVector.y;
  533. result.z = this.z / otherVector.z;
  534. return this;
  535. };
  536. Vector3.prototype.MinimizeInPlace = function (other) {
  537. if (other.x < this.x)
  538. this.x = other.x;
  539. if (other.y < this.y)
  540. this.y = other.y;
  541. if (other.z < this.z)
  542. this.z = other.z;
  543. return this;
  544. };
  545. Vector3.prototype.MaximizeInPlace = function (other) {
  546. if (other.x > this.x)
  547. this.x = other.x;
  548. if (other.y > this.y)
  549. this.y = other.y;
  550. if (other.z > this.z)
  551. this.z = other.z;
  552. return this;
  553. };
  554. // Properties
  555. Vector3.prototype.length = function () {
  556. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  557. };
  558. Vector3.prototype.lengthSquared = function () {
  559. return (this.x * this.x + this.y * this.y + this.z * this.z);
  560. };
  561. // Methods
  562. Vector3.prototype.normalize = function () {
  563. var len = this.length();
  564. if (len === 0)
  565. return this;
  566. var num = 1.0 / len;
  567. this.x *= num;
  568. this.y *= num;
  569. this.z *= num;
  570. return this;
  571. };
  572. Vector3.prototype.clone = function () {
  573. return new Vector3(this.x, this.y, this.z);
  574. };
  575. Vector3.prototype.copyFrom = function (source) {
  576. this.x = source.x;
  577. this.y = source.y;
  578. this.z = source.z;
  579. return this;
  580. };
  581. Vector3.prototype.copyFromFloats = function (x, y, z) {
  582. this.x = x;
  583. this.y = y;
  584. this.z = z;
  585. return this;
  586. };
  587. // Statics
  588. Vector3.FromArray = function (array, offset) {
  589. if (!offset) {
  590. offset = 0;
  591. }
  592. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  593. };
  594. Vector3.FromArrayToRef = function (array, offset, result) {
  595. result.x = array[offset];
  596. result.y = array[offset + 1];
  597. result.z = array[offset + 2];
  598. };
  599. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  600. result.x = array[offset];
  601. result.y = array[offset + 1];
  602. result.z = array[offset + 2];
  603. };
  604. Vector3.FromFloatsToRef = function (x, y, z, result) {
  605. result.x = x;
  606. result.y = y;
  607. result.z = z;
  608. };
  609. Vector3.Zero = function () {
  610. return new Vector3(0, 0, 0);
  611. };
  612. Vector3.Up = function () {
  613. return new Vector3(0, 1.0, 0);
  614. };
  615. Vector3.TransformCoordinates = function (vector, transformation) {
  616. var result = Vector3.Zero();
  617. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  618. return result;
  619. };
  620. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  621. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  622. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  623. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  624. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  625. result.x = x / w;
  626. result.y = y / w;
  627. result.z = z / w;
  628. };
  629. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  630. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  631. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  632. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  633. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  634. result.x = rx / rw;
  635. result.y = ry / rw;
  636. result.z = rz / rw;
  637. };
  638. Vector3.TransformNormal = function (vector, transformation) {
  639. var result = Vector3.Zero();
  640. Vector3.TransformNormalToRef(vector, transformation, result);
  641. return result;
  642. };
  643. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  644. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  645. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  646. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  647. };
  648. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  649. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  650. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  651. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  652. };
  653. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  654. var squared = amount * amount;
  655. var cubed = amount * squared;
  656. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) + (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) + ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  657. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) + (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) + ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  658. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) + (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) + ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  659. return new Vector3(x, y, z);
  660. };
  661. Vector3.Clamp = function (value, min, max) {
  662. var x = value.x;
  663. x = (x > max.x) ? max.x : x;
  664. x = (x < min.x) ? min.x : x;
  665. var y = value.y;
  666. y = (y > max.y) ? max.y : y;
  667. y = (y < min.y) ? min.y : y;
  668. var z = value.z;
  669. z = (z > max.z) ? max.z : z;
  670. z = (z < min.z) ? min.z : z;
  671. return new Vector3(x, y, z);
  672. };
  673. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  674. var squared = amount * amount;
  675. var cubed = amount * squared;
  676. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  677. var part2 = (-2.0 * cubed) + (3.0 * squared);
  678. var part3 = (cubed - (2.0 * squared)) + amount;
  679. var part4 = cubed - squared;
  680. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  681. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  682. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  683. return new Vector3(x, y, z);
  684. };
  685. Vector3.Lerp = function (start, end, amount) {
  686. var x = start.x + ((end.x - start.x) * amount);
  687. var y = start.y + ((end.y - start.y) * amount);
  688. var z = start.z + ((end.z - start.z) * amount);
  689. return new Vector3(x, y, z);
  690. };
  691. Vector3.Dot = function (left, right) {
  692. return (left.x * right.x + left.y * right.y + left.z * right.z);
  693. };
  694. Vector3.Cross = function (left, right) {
  695. var result = Vector3.Zero();
  696. Vector3.CrossToRef(left, right, result);
  697. return result;
  698. };
  699. Vector3.CrossToRef = function (left, right, result) {
  700. result.x = left.y * right.z - left.z * right.y;
  701. result.y = left.z * right.x - left.x * right.z;
  702. result.z = left.x * right.y - left.y * right.x;
  703. };
  704. Vector3.Normalize = function (vector) {
  705. var result = Vector3.Zero();
  706. Vector3.NormalizeToRef(vector, result);
  707. return result;
  708. };
  709. Vector3.NormalizeToRef = function (vector, result) {
  710. result.copyFrom(vector);
  711. result.normalize();
  712. };
  713. Vector3.Project = function (vector, world, transform, viewport) {
  714. var cw = viewport.width;
  715. var ch = viewport.height;
  716. var cx = viewport.x;
  717. var cy = viewport.y;
  718. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 1, 0, cx + cw / 2.0, ch / 2.0 + cy, 0, 1);
  719. var finalMatrix = world.multiply(transform).multiply(viewportMatrix);
  720. return Vector3.TransformCoordinates(vector, finalMatrix);
  721. };
  722. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  723. var matrix = world.multiply(transform);
  724. matrix.invert();
  725. source.x = source.x / viewportWidth * 2 - 1;
  726. source.y = -(source.y / viewportHeight * 2 - 1);
  727. var vector = Vector3.TransformCoordinates(source, matrix);
  728. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  729. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  730. vector = vector.scale(1.0 / num);
  731. }
  732. return vector;
  733. };
  734. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  735. var matrix = world.multiply(view).multiply(projection);
  736. matrix.invert();
  737. source.x = source.x / viewportWidth * 2 - 1;
  738. source.y = -(source.y / viewportHeight * 2 - 1);
  739. var vector = Vector3.TransformCoordinates(source, matrix);
  740. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  741. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  742. vector = vector.scale(1.0 / num);
  743. }
  744. return vector;
  745. };
  746. Vector3.Minimize = function (left, right) {
  747. var min = left.clone();
  748. min.MinimizeInPlace(right);
  749. return min;
  750. };
  751. Vector3.Maximize = function (left, right) {
  752. var max = left.clone();
  753. max.MaximizeInPlace(right);
  754. return max;
  755. };
  756. Vector3.Distance = function (value1, value2) {
  757. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  758. };
  759. Vector3.DistanceSquared = function (value1, value2) {
  760. var x = value1.x - value2.x;
  761. var y = value1.y - value2.y;
  762. var z = value1.z - value2.z;
  763. return (x * x) + (y * y) + (z * z);
  764. };
  765. Vector3.Center = function (value1, value2) {
  766. var center = value1.add(value2);
  767. center.scaleInPlace(0.5);
  768. return center;
  769. };
  770. return Vector3;
  771. })();
  772. BABYLON.Vector3 = Vector3;
  773. //Vector4 class created for EulerAngle class conversion to Quaternion
  774. var Vector4 = (function () {
  775. function Vector4(x, y, z, w) {
  776. this.x = x;
  777. this.y = y;
  778. this.z = z;
  779. this.w = w;
  780. }
  781. Vector4.prototype.toString = function () {
  782. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  783. };
  784. // Operators
  785. Vector4.prototype.asArray = function () {
  786. var result = [];
  787. this.toArray(result, 0);
  788. return result;
  789. };
  790. Vector4.prototype.toArray = function (array, index) {
  791. if (index === undefined) {
  792. index = 0;
  793. }
  794. array[index] = this.x;
  795. array[index + 1] = this.y;
  796. array[index + 2] = this.z;
  797. array[index + 3] = this.w;
  798. return this;
  799. };
  800. Vector4.prototype.addInPlace = function (otherVector) {
  801. this.x += otherVector.x;
  802. this.y += otherVector.y;
  803. this.z += otherVector.z;
  804. this.w += otherVector.w;
  805. return this;
  806. };
  807. Vector4.prototype.add = function (otherVector) {
  808. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  809. };
  810. Vector4.prototype.addToRef = function (otherVector, result) {
  811. result.x = this.x + otherVector.x;
  812. result.y = this.y + otherVector.y;
  813. result.z = this.z + otherVector.z;
  814. result.w = this.w + otherVector.w;
  815. return this;
  816. };
  817. Vector4.prototype.subtractInPlace = function (otherVector) {
  818. this.x -= otherVector.x;
  819. this.y -= otherVector.y;
  820. this.z -= otherVector.z;
  821. this.w -= otherVector.w;
  822. return this;
  823. };
  824. Vector4.prototype.subtract = function (otherVector) {
  825. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  826. };
  827. Vector4.prototype.subtractToRef = function (otherVector, result) {
  828. result.x = this.x - otherVector.x;
  829. result.y = this.y - otherVector.y;
  830. result.z = this.z - otherVector.z;
  831. result.w = this.w - otherVector.w;
  832. return this;
  833. };
  834. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  835. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  836. };
  837. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  838. result.x = this.x - x;
  839. result.y = this.y - y;
  840. result.z = this.z - z;
  841. result.w = this.w - w;
  842. return this;
  843. };
  844. Vector4.prototype.negate = function () {
  845. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  846. };
  847. Vector4.prototype.scaleInPlace = function (scale) {
  848. this.x *= scale;
  849. this.y *= scale;
  850. this.z *= scale;
  851. this.w *= scale;
  852. return this;
  853. };
  854. Vector4.prototype.scale = function (scale) {
  855. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  856. };
  857. Vector4.prototype.scaleToRef = function (scale, result) {
  858. result.x = this.x * scale;
  859. result.y = this.y * scale;
  860. result.z = this.z * scale;
  861. result.w = this.w * scale;
  862. };
  863. Vector4.prototype.equals = function (otherVector) {
  864. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  865. };
  866. Vector4.prototype.equalsWithEpsilon = function (otherVector) {
  867. return Math.abs(this.x - otherVector.x) < BABYLON.Engine.Epsilon && Math.abs(this.y - otherVector.y) < BABYLON.Engine.Epsilon && Math.abs(this.z - otherVector.z) < BABYLON.Engine.Epsilon && Math.abs(this.w - otherVector.w) < BABYLON.Engine.Epsilon;
  868. };
  869. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  870. return this.x === x && this.y === y && this.z === z && this.w === w;
  871. };
  872. Vector4.prototype.multiplyInPlace = function (otherVector) {
  873. this.x *= otherVector.x;
  874. this.y *= otherVector.y;
  875. this.z *= otherVector.z;
  876. this.w *= otherVector.w;
  877. return this;
  878. };
  879. Vector4.prototype.multiply = function (otherVector) {
  880. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  881. };
  882. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  883. result.x = this.x * otherVector.x;
  884. result.y = this.y * otherVector.y;
  885. result.z = this.z * otherVector.z;
  886. result.w = this.w * otherVector.w;
  887. return this;
  888. };
  889. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  890. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  891. };
  892. Vector4.prototype.divide = function (otherVector) {
  893. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  894. };
  895. Vector4.prototype.divideToRef = function (otherVector, result) {
  896. result.x = this.x / otherVector.x;
  897. result.y = this.y / otherVector.y;
  898. result.z = this.z / otherVector.z;
  899. result.w = this.w / otherVector.w;
  900. return this;
  901. };
  902. Vector4.prototype.MinimizeInPlace = function (other) {
  903. if (other.x < this.x)
  904. this.x = other.x;
  905. if (other.y < this.y)
  906. this.y = other.y;
  907. if (other.z < this.z)
  908. this.z = other.z;
  909. if (other.w < this.w)
  910. this.w = other.w;
  911. return this;
  912. };
  913. Vector4.prototype.MaximizeInPlace = function (other) {
  914. if (other.x > this.x)
  915. this.x = other.x;
  916. if (other.y > this.y)
  917. this.y = other.y;
  918. if (other.z > this.z)
  919. this.z = other.z;
  920. if (other.w > this.w)
  921. this.w = other.w;
  922. return this;
  923. };
  924. // Properties
  925. Vector4.prototype.length = function () {
  926. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  927. };
  928. Vector4.prototype.lengthSquared = function () {
  929. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  930. };
  931. // Methods
  932. Vector4.prototype.normalize = function () {
  933. var len = this.length();
  934. if (len === 0)
  935. return this;
  936. var num = 1.0 / len;
  937. this.x *= num;
  938. this.y *= num;
  939. this.z *= num;
  940. this.w *= num;
  941. return this;
  942. };
  943. Vector4.prototype.clone = function () {
  944. return new Vector4(this.x, this.y, this.z, this.w);
  945. };
  946. Vector4.prototype.copyFrom = function (source) {
  947. this.x = source.x;
  948. this.y = source.y;
  949. this.z = source.z;
  950. this.w = source.w;
  951. return this;
  952. };
  953. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  954. this.x = x;
  955. this.y = y;
  956. this.z = z;
  957. this.w = w;
  958. return this;
  959. };
  960. // Statics
  961. Vector4.FromArray = function (array, offset) {
  962. if (!offset) {
  963. offset = 0;
  964. }
  965. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  966. };
  967. Vector4.FromArrayToRef = function (array, offset, result) {
  968. result.x = array[offset];
  969. result.y = array[offset + 1];
  970. result.z = array[offset + 2];
  971. result.w = array[offset + 3];
  972. };
  973. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  974. result.x = array[offset];
  975. result.y = array[offset + 1];
  976. result.z = array[offset + 2];
  977. result.w = array[offset + 3];
  978. };
  979. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  980. result.x = x;
  981. result.y = y;
  982. result.z = z;
  983. result.w = w;
  984. };
  985. Vector4.Zero = function () {
  986. return new Vector4(0, 0, 0, 0);
  987. };
  988. Vector4.Normalize = function (vector) {
  989. var result = Vector4.Zero();
  990. Vector4.NormalizeToRef(vector, result);
  991. return result;
  992. };
  993. Vector4.NormalizeToRef = function (vector, result) {
  994. result.copyFrom(vector);
  995. result.normalize();
  996. };
  997. Vector4.Minimize = function (left, right) {
  998. var min = left.clone();
  999. min.MinimizeInPlace(right);
  1000. return min;
  1001. };
  1002. Vector4.Maximize = function (left, right) {
  1003. var max = left.clone();
  1004. max.MaximizeInPlace(right);
  1005. return max;
  1006. };
  1007. Vector4.Distance = function (value1, value2) {
  1008. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  1009. };
  1010. Vector4.DistanceSquared = function (value1, value2) {
  1011. var x = value1.x - value2.x;
  1012. var y = value1.y - value2.y;
  1013. var z = value1.z - value2.z;
  1014. var w = value1.w - value2.w;
  1015. return (x * x) + (y * y) + (z * z) + (w * w);
  1016. };
  1017. Vector4.Center = function (value1, value2) {
  1018. var center = value1.add(value2);
  1019. center.scaleInPlace(0.5);
  1020. return center;
  1021. };
  1022. return Vector4;
  1023. })();
  1024. BABYLON.Vector4 = Vector4;
  1025. var Quaternion = (function () {
  1026. function Quaternion(x, y, z, w) {
  1027. if (x === void 0) { x = 0; }
  1028. if (y === void 0) { y = 0; }
  1029. if (z === void 0) { z = 0; }
  1030. if (w === void 0) { w = 1; }
  1031. this.x = x;
  1032. this.y = y;
  1033. this.z = z;
  1034. this.w = w;
  1035. }
  1036. Quaternion.prototype.toString = function () {
  1037. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1038. };
  1039. Quaternion.prototype.asArray = function () {
  1040. return [this.x, this.y, this.z, this.w];
  1041. };
  1042. Quaternion.prototype.equals = function (otherQuaternion) {
  1043. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1044. };
  1045. Quaternion.prototype.clone = function () {
  1046. return new Quaternion(this.x, this.y, this.z, this.w);
  1047. };
  1048. Quaternion.prototype.copyFrom = function (other) {
  1049. this.x = other.x;
  1050. this.y = other.y;
  1051. this.z = other.z;
  1052. this.w = other.w;
  1053. return this;
  1054. };
  1055. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1056. this.x = x;
  1057. this.y = y;
  1058. this.z = z;
  1059. this.w = w;
  1060. return this;
  1061. };
  1062. Quaternion.prototype.add = function (other) {
  1063. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1064. };
  1065. Quaternion.prototype.subtract = function (other) {
  1066. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1067. };
  1068. Quaternion.prototype.scale = function (value) {
  1069. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1070. };
  1071. Quaternion.prototype.multiply = function (q1) {
  1072. var result = new Quaternion(0, 0, 0, 1.0);
  1073. this.multiplyToRef(q1, result);
  1074. return result;
  1075. };
  1076. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1077. result.x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1078. result.y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1079. result.z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1080. result.w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1081. return this;
  1082. };
  1083. Quaternion.prototype.length = function () {
  1084. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1085. };
  1086. Quaternion.prototype.normalize = function () {
  1087. var length = 1.0 / this.length();
  1088. this.x *= length;
  1089. this.y *= length;
  1090. this.z *= length;
  1091. this.w *= length;
  1092. return this;
  1093. };
  1094. Quaternion.prototype.toEulerAngles = function () {
  1095. var result = Vector3.Zero();
  1096. this.toEulerAnglesToRef(result);
  1097. return result;
  1098. };
  1099. Quaternion.prototype.toEulerAnglesToRef = function (result) {
  1100. //result is an EulerAngles in the in the z-x-z convention
  1101. var qx = this.x;
  1102. var qy = this.y;
  1103. var qz = this.z;
  1104. var qw = this.w;
  1105. var qxy = qx * qy;
  1106. var qxz = qx * qz;
  1107. var qwy = qw * qy;
  1108. var qwz = qw * qz;
  1109. var qwx = qw * qx;
  1110. var qyz = qy * qz;
  1111. var sqx = qx * qx;
  1112. var sqy = qy * qy;
  1113. var determinant = sqx + sqy;
  1114. if (determinant !== 0.000 && determinant !== 1.000) {
  1115. result.x = Math.atan2(qxz + qwy, qwx - qyz);
  1116. result.y = Math.acos(1 - 2 * determinant);
  1117. result.z = Math.atan2(qxz - qwy, qwx + qyz);
  1118. }
  1119. else {
  1120. if (determinant === 0.0) {
  1121. result.x = 0.0;
  1122. result.y = 0.0;
  1123. result.z = Math.atan2(qxy - qwz, 0.5 - sqy - qz * qz); //actually, degeneracy gives us choice with x+z=Math.atan2(qxy-qwz,0.5-sqy-qz*qz)
  1124. }
  1125. else {
  1126. result.x = Math.atan2(qxy - qwz, 0.5 - sqy - qz * qz); //actually, degeneracy gives us choice with x-z=Math.atan2(qxy-qwz,0.5-sqy-qz*qz)
  1127. result.y = Math.PI;
  1128. result.z = 0.0;
  1129. }
  1130. }
  1131. return this;
  1132. };
  1133. Quaternion.prototype.toRotationMatrix = function (result) {
  1134. var xx = this.x * this.x;
  1135. var yy = this.y * this.y;
  1136. var zz = this.z * this.z;
  1137. var xy = this.x * this.y;
  1138. var zw = this.z * this.w;
  1139. var zx = this.z * this.x;
  1140. var yw = this.y * this.w;
  1141. var yz = this.y * this.z;
  1142. var xw = this.x * this.w;
  1143. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1144. result.m[1] = 2.0 * (xy + zw);
  1145. result.m[2] = 2.0 * (zx - yw);
  1146. result.m[3] = 0;
  1147. result.m[4] = 2.0 * (xy - zw);
  1148. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1149. result.m[6] = 2.0 * (yz + xw);
  1150. result.m[7] = 0;
  1151. result.m[8] = 2.0 * (zx + yw);
  1152. result.m[9] = 2.0 * (yz - xw);
  1153. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1154. result.m[11] = 0;
  1155. result.m[12] = 0;
  1156. result.m[13] = 0;
  1157. result.m[14] = 0;
  1158. result.m[15] = 1.0;
  1159. return this;
  1160. };
  1161. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1162. Quaternion.FromRotationMatrixToRef(matrix, this);
  1163. return this;
  1164. };
  1165. // Statics
  1166. Quaternion.FromRotationMatrix = function (matrix) {
  1167. var result = new Quaternion();
  1168. Quaternion.FromRotationMatrixToRef(matrix, result);
  1169. return result;
  1170. };
  1171. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1172. var data = matrix.m;
  1173. var m11 = data[0], m12 = data[4], m13 = data[8];
  1174. var m21 = data[1], m22 = data[5], m23 = data[9];
  1175. var m31 = data[2], m32 = data[6], m33 = data[10];
  1176. var trace = m11 + m22 + m33;
  1177. var s;
  1178. if (trace > 0) {
  1179. s = 0.5 / Math.sqrt(trace + 1.0);
  1180. result.w = 0.25 / s;
  1181. result.x = (m32 - m23) * s;
  1182. result.y = (m13 - m31) * s;
  1183. result.z = (m21 - m12) * s;
  1184. }
  1185. else if (m11 > m22 && m11 > m33) {
  1186. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1187. result.w = (m32 - m23) / s;
  1188. result.x = 0.25 * s;
  1189. result.y = (m12 + m21) / s;
  1190. result.z = (m13 + m31) / s;
  1191. }
  1192. else if (m22 > m33) {
  1193. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1194. result.w = (m13 - m31) / s;
  1195. result.x = (m12 + m21) / s;
  1196. result.y = 0.25 * s;
  1197. result.z = (m23 + m32) / s;
  1198. }
  1199. else {
  1200. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1201. result.w = (m21 - m12) / s;
  1202. result.x = (m13 + m31) / s;
  1203. result.y = (m23 + m32) / s;
  1204. result.z = 0.25 * s;
  1205. }
  1206. };
  1207. Quaternion.Inverse = function (q) {
  1208. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1209. };
  1210. Quaternion.Identity = function () {
  1211. return new Quaternion(0, 0, 0, 1);
  1212. };
  1213. Quaternion.RotationAxis = function (axis, angle) {
  1214. var result = new Quaternion();
  1215. var sin = Math.sin(angle / 2);
  1216. result.w = Math.cos(angle / 2);
  1217. result.x = axis.x * sin;
  1218. result.y = axis.y * sin;
  1219. result.z = axis.z * sin;
  1220. return result;
  1221. };
  1222. Quaternion.FromArray = function (array, offset) {
  1223. if (!offset) {
  1224. offset = 0;
  1225. }
  1226. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1227. };
  1228. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1229. var result = new Quaternion();
  1230. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1231. return result;
  1232. };
  1233. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1234. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1235. var halfRoll = roll * 0.5;
  1236. var halfPitch = pitch * 0.5;
  1237. var halfYaw = yaw * 0.5;
  1238. var sinRoll = Math.sin(halfRoll);
  1239. var cosRoll = Math.cos(halfRoll);
  1240. var sinPitch = Math.sin(halfPitch);
  1241. var cosPitch = Math.cos(halfPitch);
  1242. var sinYaw = Math.sin(halfYaw);
  1243. var cosYaw = Math.cos(halfYaw);
  1244. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1245. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1246. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1247. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1248. };
  1249. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1250. var result = new Quaternion();
  1251. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1252. return result;
  1253. };
  1254. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1255. // Produces a quaternion from Euler angles in the z-x-z orientation
  1256. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1257. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1258. var halfBeta = beta * 0.5;
  1259. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1260. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1261. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1262. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1263. };
  1264. Quaternion.Slerp = function (left, right, amount) {
  1265. var num2;
  1266. var num3;
  1267. var num = amount;
  1268. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1269. var flag = false;
  1270. if (num4 < 0) {
  1271. flag = true;
  1272. num4 = -num4;
  1273. }
  1274. if (num4 > 0.999999) {
  1275. num3 = 1 - num;
  1276. num2 = flag ? -num : num;
  1277. }
  1278. else {
  1279. var num5 = Math.acos(num4);
  1280. var num6 = (1.0 / Math.sin(num5));
  1281. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1282. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1283. }
  1284. return new Quaternion((num3 * left.x) + (num2 * right.x), (num3 * left.y) + (num2 * right.y), (num3 * left.z) + (num2 * right.z), (num3 * left.w) + (num2 * right.w));
  1285. };
  1286. return Quaternion;
  1287. })();
  1288. BABYLON.Quaternion = Quaternion;
  1289. var Matrix = (function () {
  1290. function Matrix() {
  1291. this.m = new Float32Array(16);
  1292. }
  1293. // Properties
  1294. Matrix.prototype.isIdentity = function () {
  1295. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1296. return false;
  1297. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 || this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 || this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 || this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  1298. return false;
  1299. return true;
  1300. };
  1301. Matrix.prototype.determinant = function () {
  1302. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1303. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1304. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1305. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1306. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1307. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1308. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) - (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) - (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  1309. };
  1310. // Methods
  1311. Matrix.prototype.toArray = function () {
  1312. return this.m;
  1313. };
  1314. Matrix.prototype.asArray = function () {
  1315. return this.toArray();
  1316. };
  1317. Matrix.prototype.invert = function () {
  1318. this.invertToRef(this);
  1319. return this;
  1320. };
  1321. Matrix.prototype.invertToRef = function (other) {
  1322. var l1 = this.m[0];
  1323. var l2 = this.m[1];
  1324. var l3 = this.m[2];
  1325. var l4 = this.m[3];
  1326. var l5 = this.m[4];
  1327. var l6 = this.m[5];
  1328. var l7 = this.m[6];
  1329. var l8 = this.m[7];
  1330. var l9 = this.m[8];
  1331. var l10 = this.m[9];
  1332. var l11 = this.m[10];
  1333. var l12 = this.m[11];
  1334. var l13 = this.m[12];
  1335. var l14 = this.m[13];
  1336. var l15 = this.m[14];
  1337. var l16 = this.m[15];
  1338. var l17 = (l11 * l16) - (l12 * l15);
  1339. var l18 = (l10 * l16) - (l12 * l14);
  1340. var l19 = (l10 * l15) - (l11 * l14);
  1341. var l20 = (l9 * l16) - (l12 * l13);
  1342. var l21 = (l9 * l15) - (l11 * l13);
  1343. var l22 = (l9 * l14) - (l10 * l13);
  1344. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1345. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1346. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1347. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1348. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1349. var l28 = (l7 * l16) - (l8 * l15);
  1350. var l29 = (l6 * l16) - (l8 * l14);
  1351. var l30 = (l6 * l15) - (l7 * l14);
  1352. var l31 = (l5 * l16) - (l8 * l13);
  1353. var l32 = (l5 * l15) - (l7 * l13);
  1354. var l33 = (l5 * l14) - (l6 * l13);
  1355. var l34 = (l7 * l12) - (l8 * l11);
  1356. var l35 = (l6 * l12) - (l8 * l10);
  1357. var l36 = (l6 * l11) - (l7 * l10);
  1358. var l37 = (l5 * l12) - (l8 * l9);
  1359. var l38 = (l5 * l11) - (l7 * l9);
  1360. var l39 = (l5 * l10) - (l6 * l9);
  1361. other.m[0] = l23 * l27;
  1362. other.m[4] = l24 * l27;
  1363. other.m[8] = l25 * l27;
  1364. other.m[12] = l26 * l27;
  1365. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1366. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1367. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1368. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1369. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1370. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1371. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1372. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1373. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1374. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1375. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1376. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1377. return this;
  1378. };
  1379. Matrix.prototype.setTranslation = function (vector3) {
  1380. this.m[12] = vector3.x;
  1381. this.m[13] = vector3.y;
  1382. this.m[14] = vector3.z;
  1383. return this;
  1384. };
  1385. Matrix.prototype.multiply = function (other) {
  1386. var result = new Matrix();
  1387. this.multiplyToRef(other, result);
  1388. return result;
  1389. };
  1390. Matrix.prototype.copyFrom = function (other) {
  1391. for (var index = 0; index < 16; index++) {
  1392. this.m[index] = other.m[index];
  1393. }
  1394. return this;
  1395. };
  1396. Matrix.prototype.copyToArray = function (array, offset) {
  1397. if (offset === void 0) { offset = 0; }
  1398. for (var index = 0; index < 16; index++) {
  1399. array[offset + index] = this.m[index];
  1400. }
  1401. return this;
  1402. };
  1403. Matrix.prototype.multiplyToRef = function (other, result) {
  1404. this.multiplyToArray(other, result.m, 0);
  1405. return this;
  1406. };
  1407. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1408. var tm0 = this.m[0];
  1409. var tm1 = this.m[1];
  1410. var tm2 = this.m[2];
  1411. var tm3 = this.m[3];
  1412. var tm4 = this.m[4];
  1413. var tm5 = this.m[5];
  1414. var tm6 = this.m[6];
  1415. var tm7 = this.m[7];
  1416. var tm8 = this.m[8];
  1417. var tm9 = this.m[9];
  1418. var tm10 = this.m[10];
  1419. var tm11 = this.m[11];
  1420. var tm12 = this.m[12];
  1421. var tm13 = this.m[13];
  1422. var tm14 = this.m[14];
  1423. var tm15 = this.m[15];
  1424. var om0 = other.m[0];
  1425. var om1 = other.m[1];
  1426. var om2 = other.m[2];
  1427. var om3 = other.m[3];
  1428. var om4 = other.m[4];
  1429. var om5 = other.m[5];
  1430. var om6 = other.m[6];
  1431. var om7 = other.m[7];
  1432. var om8 = other.m[8];
  1433. var om9 = other.m[9];
  1434. var om10 = other.m[10];
  1435. var om11 = other.m[11];
  1436. var om12 = other.m[12];
  1437. var om13 = other.m[13];
  1438. var om14 = other.m[14];
  1439. var om15 = other.m[15];
  1440. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1441. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1442. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1443. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1444. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1445. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1446. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1447. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1448. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1449. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1450. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1451. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1452. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1453. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1454. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1455. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1456. return this;
  1457. };
  1458. Matrix.prototype.equals = function (value) {
  1459. return value && (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] && this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] && this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] && this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1460. };
  1461. Matrix.prototype.clone = function () {
  1462. return Matrix.FromValues(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5], this.m[6], this.m[7], this.m[8], this.m[9], this.m[10], this.m[11], this.m[12], this.m[13], this.m[14], this.m[15]);
  1463. };
  1464. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1465. translation.x = this.m[12];
  1466. translation.y = this.m[13];
  1467. translation.z = this.m[14];
  1468. var xs = BABYLON.Tools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1469. var ys = BABYLON.Tools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1470. var zs = BABYLON.Tools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1471. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1472. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1473. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1474. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1475. rotation.x = 0;
  1476. rotation.y = 0;
  1477. rotation.z = 0;
  1478. rotation.w = 1;
  1479. return false;
  1480. }
  1481. var rotationMatrix = Matrix.FromValues(this.m[0] / scale.x, this.m[1] / scale.x, this.m[2] / scale.x, 0, this.m[4] / scale.y, this.m[5] / scale.y, this.m[6] / scale.y, 0, this.m[8] / scale.z, this.m[9] / scale.z, this.m[10] / scale.z, 0, 0, 0, 0, 1);
  1482. Quaternion.FromRotationMatrixToRef(rotationMatrix, rotation);
  1483. return true;
  1484. };
  1485. // Statics
  1486. Matrix.FromArray = function (array, offset) {
  1487. var result = new Matrix();
  1488. if (!offset) {
  1489. offset = 0;
  1490. }
  1491. Matrix.FromArrayToRef(array, offset, result);
  1492. return result;
  1493. };
  1494. Matrix.FromArrayToRef = function (array, offset, result) {
  1495. for (var index = 0; index < 16; index++) {
  1496. result.m[index] = array[index + offset];
  1497. }
  1498. };
  1499. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1500. result.m[0] = initialM11;
  1501. result.m[1] = initialM12;
  1502. result.m[2] = initialM13;
  1503. result.m[3] = initialM14;
  1504. result.m[4] = initialM21;
  1505. result.m[5] = initialM22;
  1506. result.m[6] = initialM23;
  1507. result.m[7] = initialM24;
  1508. result.m[8] = initialM31;
  1509. result.m[9] = initialM32;
  1510. result.m[10] = initialM33;
  1511. result.m[11] = initialM34;
  1512. result.m[12] = initialM41;
  1513. result.m[13] = initialM42;
  1514. result.m[14] = initialM43;
  1515. result.m[15] = initialM44;
  1516. };
  1517. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1518. var result = new Matrix();
  1519. result.m[0] = initialM11;
  1520. result.m[1] = initialM12;
  1521. result.m[2] = initialM13;
  1522. result.m[3] = initialM14;
  1523. result.m[4] = initialM21;
  1524. result.m[5] = initialM22;
  1525. result.m[6] = initialM23;
  1526. result.m[7] = initialM24;
  1527. result.m[8] = initialM31;
  1528. result.m[9] = initialM32;
  1529. result.m[10] = initialM33;
  1530. result.m[11] = initialM34;
  1531. result.m[12] = initialM41;
  1532. result.m[13] = initialM42;
  1533. result.m[14] = initialM43;
  1534. result.m[15] = initialM44;
  1535. return result;
  1536. };
  1537. Matrix.Compose = function (scale, rotation, translation) {
  1538. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  1539. var rotationMatrix = Matrix.Identity();
  1540. rotation.toRotationMatrix(rotationMatrix);
  1541. result = result.multiply(rotationMatrix);
  1542. result.setTranslation(translation);
  1543. return result;
  1544. };
  1545. Matrix.Identity = function () {
  1546. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1547. };
  1548. Matrix.IdentityToRef = function (result) {
  1549. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1550. };
  1551. Matrix.Zero = function () {
  1552. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1553. };
  1554. Matrix.RotationX = function (angle) {
  1555. var result = new Matrix();
  1556. Matrix.RotationXToRef(angle, result);
  1557. return result;
  1558. };
  1559. Matrix.Invert = function (source) {
  1560. var result = new Matrix();
  1561. source.invertToRef(result);
  1562. return result;
  1563. };
  1564. Matrix.RotationXToRef = function (angle, result) {
  1565. var s = Math.sin(angle);
  1566. var c = Math.cos(angle);
  1567. result.m[0] = 1.0;
  1568. result.m[15] = 1.0;
  1569. result.m[5] = c;
  1570. result.m[10] = c;
  1571. result.m[9] = -s;
  1572. result.m[6] = s;
  1573. result.m[1] = 0;
  1574. result.m[2] = 0;
  1575. result.m[3] = 0;
  1576. result.m[4] = 0;
  1577. result.m[7] = 0;
  1578. result.m[8] = 0;
  1579. result.m[11] = 0;
  1580. result.m[12] = 0;
  1581. result.m[13] = 0;
  1582. result.m[14] = 0;
  1583. };
  1584. Matrix.RotationY = function (angle) {
  1585. var result = new Matrix();
  1586. Matrix.RotationYToRef(angle, result);
  1587. return result;
  1588. };
  1589. Matrix.RotationYToRef = function (angle, result) {
  1590. var s = Math.sin(angle);
  1591. var c = Math.cos(angle);
  1592. result.m[5] = 1.0;
  1593. result.m[15] = 1.0;
  1594. result.m[0] = c;
  1595. result.m[2] = -s;
  1596. result.m[8] = s;
  1597. result.m[10] = c;
  1598. result.m[1] = 0;
  1599. result.m[3] = 0;
  1600. result.m[4] = 0;
  1601. result.m[6] = 0;
  1602. result.m[7] = 0;
  1603. result.m[9] = 0;
  1604. result.m[11] = 0;
  1605. result.m[12] = 0;
  1606. result.m[13] = 0;
  1607. result.m[14] = 0;
  1608. };
  1609. Matrix.RotationZ = function (angle) {
  1610. var result = new Matrix();
  1611. Matrix.RotationZToRef(angle, result);
  1612. return result;
  1613. };
  1614. Matrix.RotationZToRef = function (angle, result) {
  1615. var s = Math.sin(angle);
  1616. var c = Math.cos(angle);
  1617. result.m[10] = 1.0;
  1618. result.m[15] = 1.0;
  1619. result.m[0] = c;
  1620. result.m[1] = s;
  1621. result.m[4] = -s;
  1622. result.m[5] = c;
  1623. result.m[2] = 0;
  1624. result.m[3] = 0;
  1625. result.m[6] = 0;
  1626. result.m[7] = 0;
  1627. result.m[8] = 0;
  1628. result.m[9] = 0;
  1629. result.m[11] = 0;
  1630. result.m[12] = 0;
  1631. result.m[13] = 0;
  1632. result.m[14] = 0;
  1633. };
  1634. Matrix.RotationAxis = function (axis, angle) {
  1635. var s = Math.sin(-angle);
  1636. var c = Math.cos(-angle);
  1637. var c1 = 1 - c;
  1638. axis.normalize();
  1639. var result = Matrix.Zero();
  1640. result.m[0] = (axis.x * axis.x) * c1 + c;
  1641. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1642. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1643. result.m[3] = 0.0;
  1644. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1645. result.m[5] = (axis.y * axis.y) * c1 + c;
  1646. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  1647. result.m[7] = 0.0;
  1648. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  1649. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  1650. result.m[10] = (axis.z * axis.z) * c1 + c;
  1651. result.m[11] = 0.0;
  1652. result.m[15] = 1.0;
  1653. return result;
  1654. };
  1655. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1656. var result = new Matrix();
  1657. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1658. return result;
  1659. };
  1660. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1661. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  1662. this._tempQuaternion.toRotationMatrix(result);
  1663. };
  1664. Matrix.Scaling = function (x, y, z) {
  1665. var result = Matrix.Zero();
  1666. Matrix.ScalingToRef(x, y, z, result);
  1667. return result;
  1668. };
  1669. Matrix.ScalingToRef = function (x, y, z, result) {
  1670. result.m[0] = x;
  1671. result.m[1] = 0;
  1672. result.m[2] = 0;
  1673. result.m[3] = 0;
  1674. result.m[4] = 0;
  1675. result.m[5] = y;
  1676. result.m[6] = 0;
  1677. result.m[7] = 0;
  1678. result.m[8] = 0;
  1679. result.m[9] = 0;
  1680. result.m[10] = z;
  1681. result.m[11] = 0;
  1682. result.m[12] = 0;
  1683. result.m[13] = 0;
  1684. result.m[14] = 0;
  1685. result.m[15] = 1.0;
  1686. };
  1687. Matrix.Translation = function (x, y, z) {
  1688. var result = Matrix.Identity();
  1689. Matrix.TranslationToRef(x, y, z, result);
  1690. return result;
  1691. };
  1692. Matrix.TranslationToRef = function (x, y, z, result) {
  1693. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  1694. };
  1695. Matrix.LookAtLH = function (eye, target, up) {
  1696. var result = Matrix.Zero();
  1697. Matrix.LookAtLHToRef(eye, target, up, result);
  1698. return result;
  1699. };
  1700. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  1701. // Z axis
  1702. target.subtractToRef(eye, this._zAxis);
  1703. this._zAxis.normalize();
  1704. // X axis
  1705. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  1706. this._xAxis.normalize();
  1707. // Y axis
  1708. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  1709. this._yAxis.normalize();
  1710. // Eye angles
  1711. var ex = -Vector3.Dot(this._xAxis, eye);
  1712. var ey = -Vector3.Dot(this._yAxis, eye);
  1713. var ez = -Vector3.Dot(this._zAxis, eye);
  1714. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  1715. };
  1716. Matrix.OrthoLH = function (width, height, znear, zfar) {
  1717. var matrix = Matrix.Zero();
  1718. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  1719. return matrix;
  1720. };
  1721. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  1722. var hw = 2.0 / width;
  1723. var hh = 2.0 / height;
  1724. var id = 1.0 / (zfar - znear);
  1725. var nid = znear / (znear - zfar);
  1726. Matrix.FromValuesToRef(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1, result);
  1727. };
  1728. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  1729. var matrix = Matrix.Zero();
  1730. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  1731. return matrix;
  1732. };
  1733. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  1734. result.m[0] = 2.0 / (right - left);
  1735. result.m[1] = result.m[2] = result.m[3] = 0;
  1736. result.m[5] = 2.0 / (top - bottom);
  1737. result.m[4] = result.m[6] = result.m[7] = 0;
  1738. result.m[10] = -1.0 / (znear - zfar);
  1739. result.m[8] = result.m[9] = result.m[11] = 0;
  1740. result.m[12] = (left + right) / (left - right);
  1741. result.m[13] = (top + bottom) / (bottom - top);
  1742. result.m[14] = znear / (znear - zfar);
  1743. result.m[15] = 1.0;
  1744. };
  1745. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  1746. var matrix = Matrix.Zero();
  1747. matrix.m[0] = (2.0 * znear) / width;
  1748. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  1749. matrix.m[5] = (2.0 * znear) / height;
  1750. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  1751. matrix.m[10] = -zfar / (znear - zfar);
  1752. matrix.m[8] = matrix.m[9] = 0.0;
  1753. matrix.m[11] = 1.0;
  1754. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  1755. matrix.m[14] = (znear * zfar) / (znear - zfar);
  1756. return matrix;
  1757. };
  1758. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  1759. var matrix = Matrix.Zero();
  1760. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  1761. return matrix;
  1762. };
  1763. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, fovMode) {
  1764. if (fovMode === void 0) { fovMode = BABYLON.Camera.FOVMODE_VERTICAL_FIXED; }
  1765. var tan = 1.0 / (Math.tan(fov * 0.5));
  1766. var v_fixed = (fovMode === BABYLON.Camera.FOVMODE_VERTICAL_FIXED);
  1767. if (v_fixed) {
  1768. result.m[0] = tan / aspect;
  1769. }
  1770. else {
  1771. result.m[0] = tan;
  1772. }
  1773. result.m[1] = result.m[2] = result.m[3] = 0.0;
  1774. if (v_fixed) {
  1775. result.m[5] = tan;
  1776. }
  1777. else {
  1778. result.m[5] = tan * aspect;
  1779. }
  1780. result.m[4] = result.m[6] = result.m[7] = 0.0;
  1781. result.m[8] = result.m[9] = 0.0;
  1782. result.m[10] = -zfar / (znear - zfar);
  1783. result.m[11] = 1.0;
  1784. result.m[12] = result.m[13] = result.m[15] = 0.0;
  1785. result.m[14] = (znear * zfar) / (znear - zfar);
  1786. };
  1787. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  1788. var cw = viewport.width;
  1789. var ch = viewport.height;
  1790. var cx = viewport.x;
  1791. var cy = viewport.y;
  1792. 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);
  1793. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  1794. };
  1795. Matrix.Transpose = function (matrix) {
  1796. var result = new Matrix();
  1797. result.m[0] = matrix.m[0];
  1798. result.m[1] = matrix.m[4];
  1799. result.m[2] = matrix.m[8];
  1800. result.m[3] = matrix.m[12];
  1801. result.m[4] = matrix.m[1];
  1802. result.m[5] = matrix.m[5];
  1803. result.m[6] = matrix.m[9];
  1804. result.m[7] = matrix.m[13];
  1805. result.m[8] = matrix.m[2];
  1806. result.m[9] = matrix.m[6];
  1807. result.m[10] = matrix.m[10];
  1808. result.m[11] = matrix.m[14];
  1809. result.m[12] = matrix.m[3];
  1810. result.m[13] = matrix.m[7];
  1811. result.m[14] = matrix.m[11];
  1812. result.m[15] = matrix.m[15];
  1813. return result;
  1814. };
  1815. Matrix.Reflection = function (plane) {
  1816. var matrix = new Matrix();
  1817. Matrix.ReflectionToRef(plane, matrix);
  1818. return matrix;
  1819. };
  1820. Matrix.ReflectionToRef = function (plane, result) {
  1821. plane.normalize();
  1822. var x = plane.normal.x;
  1823. var y = plane.normal.y;
  1824. var z = plane.normal.z;
  1825. var temp = -2 * x;
  1826. var temp2 = -2 * y;
  1827. var temp3 = -2 * z;
  1828. result.m[0] = (temp * x) + 1;
  1829. result.m[1] = temp2 * x;
  1830. result.m[2] = temp3 * x;
  1831. result.m[3] = 0.0;
  1832. result.m[4] = temp * y;
  1833. result.m[5] = (temp2 * y) + 1;
  1834. result.m[6] = temp3 * y;
  1835. result.m[7] = 0.0;
  1836. result.m[8] = temp * z;
  1837. result.m[9] = temp2 * z;
  1838. result.m[10] = (temp3 * z) + 1;
  1839. result.m[11] = 0.0;
  1840. result.m[12] = temp * plane.d;
  1841. result.m[13] = temp2 * plane.d;
  1842. result.m[14] = temp3 * plane.d;
  1843. result.m[15] = 1.0;
  1844. };
  1845. Matrix._tempQuaternion = new Quaternion();
  1846. Matrix._xAxis = Vector3.Zero();
  1847. Matrix._yAxis = Vector3.Zero();
  1848. Matrix._zAxis = Vector3.Zero();
  1849. return Matrix;
  1850. })();
  1851. BABYLON.Matrix = Matrix;
  1852. var Plane = (function () {
  1853. function Plane(a, b, c, d) {
  1854. this.normal = new Vector3(a, b, c);
  1855. this.d = d;
  1856. }
  1857. Plane.prototype.asArray = function () {
  1858. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  1859. };
  1860. // Methods
  1861. Plane.prototype.clone = function () {
  1862. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  1863. };
  1864. Plane.prototype.normalize = function () {
  1865. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  1866. var magnitude = 0;
  1867. if (norm !== 0) {
  1868. magnitude = 1.0 / norm;
  1869. }
  1870. this.normal.x *= magnitude;
  1871. this.normal.y *= magnitude;
  1872. this.normal.z *= magnitude;
  1873. this.d *= magnitude;
  1874. return this;
  1875. };
  1876. Plane.prototype.transform = function (transformation) {
  1877. var transposedMatrix = Matrix.Transpose(transformation);
  1878. var x = this.normal.x;
  1879. var y = this.normal.y;
  1880. var z = this.normal.z;
  1881. var d = this.d;
  1882. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  1883. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  1884. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  1885. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  1886. return new Plane(normalX, normalY, normalZ, finalD);
  1887. };
  1888. Plane.prototype.dotCoordinate = function (point) {
  1889. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  1890. };
  1891. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  1892. var x1 = point2.x - point1.x;
  1893. var y1 = point2.y - point1.y;
  1894. var z1 = point2.z - point1.z;
  1895. var x2 = point3.x - point1.x;
  1896. var y2 = point3.y - point1.y;
  1897. var z2 = point3.z - point1.z;
  1898. var yz = (y1 * z2) - (z1 * y2);
  1899. var xz = (z1 * x2) - (x1 * z2);
  1900. var xy = (x1 * y2) - (y1 * x2);
  1901. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  1902. var invPyth;
  1903. if (pyth !== 0) {
  1904. invPyth = 1.0 / pyth;
  1905. }
  1906. else {
  1907. invPyth = 0;
  1908. }
  1909. this.normal.x = yz * invPyth;
  1910. this.normal.y = xz * invPyth;
  1911. this.normal.z = xy * invPyth;
  1912. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  1913. return this;
  1914. };
  1915. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  1916. var dot = Vector3.Dot(this.normal, direction);
  1917. return (dot <= epsilon);
  1918. };
  1919. Plane.prototype.signedDistanceTo = function (point) {
  1920. return Vector3.Dot(point, this.normal) + this.d;
  1921. };
  1922. // Statics
  1923. Plane.FromArray = function (array) {
  1924. return new Plane(array[0], array[1], array[2], array[3]);
  1925. };
  1926. Plane.FromPoints = function (point1, point2, point3) {
  1927. var result = new Plane(0, 0, 0, 0);
  1928. result.copyFromPoints(point1, point2, point3);
  1929. return result;
  1930. };
  1931. Plane.FromPositionAndNormal = function (origin, normal) {
  1932. var result = new Plane(0, 0, 0, 0);
  1933. normal.normalize();
  1934. result.normal = normal;
  1935. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  1936. return result;
  1937. };
  1938. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  1939. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  1940. return Vector3.Dot(point, normal) + d;
  1941. };
  1942. return Plane;
  1943. })();
  1944. BABYLON.Plane = Plane;
  1945. var Viewport = (function () {
  1946. function Viewport(x, y, width, height) {
  1947. this.x = x;
  1948. this.y = y;
  1949. this.width = width;
  1950. this.height = height;
  1951. }
  1952. Viewport.prototype.toGlobal = function (engine) {
  1953. var width = engine.getRenderWidth();
  1954. var height = engine.getRenderHeight();
  1955. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  1956. };
  1957. return Viewport;
  1958. })();
  1959. BABYLON.Viewport = Viewport;
  1960. var Frustum = (function () {
  1961. function Frustum() {
  1962. }
  1963. Frustum.GetPlanes = function (transform) {
  1964. var frustumPlanes = [];
  1965. for (var index = 0; index < 6; index++) {
  1966. frustumPlanes.push(new Plane(0, 0, 0, 0));
  1967. }
  1968. Frustum.GetPlanesToRef(transform, frustumPlanes);
  1969. return frustumPlanes;
  1970. };
  1971. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  1972. // Near
  1973. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  1974. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  1975. frustumPlanes[0].normal.z = transform.m[10] + transform.m[10];
  1976. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  1977. frustumPlanes[0].normalize();
  1978. // Far
  1979. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  1980. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  1981. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  1982. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  1983. frustumPlanes[1].normalize();
  1984. // Left
  1985. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  1986. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  1987. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  1988. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  1989. frustumPlanes[2].normalize();
  1990. // Right
  1991. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  1992. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  1993. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  1994. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  1995. frustumPlanes[3].normalize();
  1996. // Top
  1997. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  1998. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  1999. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2000. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2001. frustumPlanes[4].normalize();
  2002. // Bottom
  2003. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2004. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2005. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2006. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2007. frustumPlanes[5].normalize();
  2008. };
  2009. return Frustum;
  2010. })();
  2011. BABYLON.Frustum = Frustum;
  2012. var Ray = (function () {
  2013. function Ray(origin, direction, length) {
  2014. if (length === void 0) { length = Number.MAX_VALUE; }
  2015. this.origin = origin;
  2016. this.direction = direction;
  2017. this.length = length;
  2018. }
  2019. // Methods
  2020. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  2021. var d = 0.0;
  2022. var maxValue = Number.MAX_VALUE;
  2023. if (Math.abs(this.direction.x) < 0.0000001) {
  2024. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  2025. return false;
  2026. }
  2027. }
  2028. else {
  2029. var inv = 1.0 / this.direction.x;
  2030. var min = (minimum.x - this.origin.x) * inv;
  2031. var max = (maximum.x - this.origin.x) * inv;
  2032. if (max === -Infinity) {
  2033. max = Infinity;
  2034. }
  2035. if (min > max) {
  2036. var temp = min;
  2037. min = max;
  2038. max = temp;
  2039. }
  2040. d = Math.max(min, d);
  2041. maxValue = Math.min(max, maxValue);
  2042. if (d > maxValue) {
  2043. return false;
  2044. }
  2045. }
  2046. if (Math.abs(this.direction.y) < 0.0000001) {
  2047. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  2048. return false;
  2049. }
  2050. }
  2051. else {
  2052. inv = 1.0 / this.direction.y;
  2053. min = (minimum.y - this.origin.y) * inv;
  2054. max = (maximum.y - this.origin.y) * inv;
  2055. if (max === -Infinity) {
  2056. max = Infinity;
  2057. }
  2058. if (min > max) {
  2059. temp = min;
  2060. min = max;
  2061. max = temp;
  2062. }
  2063. d = Math.max(min, d);
  2064. maxValue = Math.min(max, maxValue);
  2065. if (d > maxValue) {
  2066. return false;
  2067. }
  2068. }
  2069. if (Math.abs(this.direction.z) < 0.0000001) {
  2070. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  2071. return false;
  2072. }
  2073. }
  2074. else {
  2075. inv = 1.0 / this.direction.z;
  2076. min = (minimum.z - this.origin.z) * inv;
  2077. max = (maximum.z - this.origin.z) * inv;
  2078. if (max === -Infinity) {
  2079. max = Infinity;
  2080. }
  2081. if (min > max) {
  2082. temp = min;
  2083. min = max;
  2084. max = temp;
  2085. }
  2086. d = Math.max(min, d);
  2087. maxValue = Math.min(max, maxValue);
  2088. if (d > maxValue) {
  2089. return false;
  2090. }
  2091. }
  2092. return true;
  2093. };
  2094. Ray.prototype.intersectsBox = function (box) {
  2095. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  2096. };
  2097. Ray.prototype.intersectsSphere = function (sphere) {
  2098. var x = sphere.center.x - this.origin.x;
  2099. var y = sphere.center.y - this.origin.y;
  2100. var z = sphere.center.z - this.origin.z;
  2101. var pyth = (x * x) + (y * y) + (z * z);
  2102. var rr = sphere.radius * sphere.radius;
  2103. if (pyth <= rr) {
  2104. return true;
  2105. }
  2106. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  2107. if (dot < 0.0) {
  2108. return false;
  2109. }
  2110. var temp = pyth - (dot * dot);
  2111. return temp <= rr;
  2112. };
  2113. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  2114. if (!this._edge1) {
  2115. this._edge1 = Vector3.Zero();
  2116. this._edge2 = Vector3.Zero();
  2117. this._pvec = Vector3.Zero();
  2118. this._tvec = Vector3.Zero();
  2119. this._qvec = Vector3.Zero();
  2120. }
  2121. vertex1.subtractToRef(vertex0, this._edge1);
  2122. vertex2.subtractToRef(vertex0, this._edge2);
  2123. Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  2124. var det = Vector3.Dot(this._edge1, this._pvec);
  2125. if (det === 0) {
  2126. return null;
  2127. }
  2128. var invdet = 1 / det;
  2129. this.origin.subtractToRef(vertex0, this._tvec);
  2130. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  2131. if (bu < 0 || bu > 1.0) {
  2132. return null;
  2133. }
  2134. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  2135. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  2136. if (bv < 0 || bu + bv > 1.0) {
  2137. return null;
  2138. }
  2139. //check if the distance is longer than the predefined length.
  2140. var distance = Vector3.Dot(this._edge2, this._qvec) * invdet;
  2141. if (distance > this.length) {
  2142. return null;
  2143. }
  2144. return new BABYLON.IntersectionInfo(bu, bv, distance);
  2145. };
  2146. // Statics
  2147. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  2148. var start = Vector3.Unproject(new Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  2149. var end = Vector3.Unproject(new Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  2150. var direction = end.subtract(start);
  2151. direction.normalize();
  2152. return new Ray(start, direction);
  2153. };
  2154. /**
  2155. * 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
  2156. * transformed to the given world matrix.
  2157. * @param origin The origin point
  2158. * @param end The end point
  2159. * @param world a matrix to transform the ray to. Default is the identity matrix.
  2160. */
  2161. Ray.CreateNewFromTo = function (origin, end, world) {
  2162. if (world === void 0) { world = Matrix.Identity(); }
  2163. var direction = end.subtract(origin);
  2164. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  2165. direction.normalize();
  2166. return Ray.Transform(new Ray(origin, direction, length), world);
  2167. };
  2168. Ray.Transform = function (ray, matrix) {
  2169. var newOrigin = Vector3.TransformCoordinates(ray.origin, matrix);
  2170. var newDirection = Vector3.TransformNormal(ray.direction, matrix);
  2171. return new Ray(newOrigin, newDirection, ray.length);
  2172. };
  2173. return Ray;
  2174. })();
  2175. BABYLON.Ray = Ray;
  2176. (function (Space) {
  2177. Space[Space["LOCAL"] = 0] = "LOCAL";
  2178. Space[Space["WORLD"] = 1] = "WORLD";
  2179. })(BABYLON.Space || (BABYLON.Space = {}));
  2180. var Space = BABYLON.Space;
  2181. var Axis = (function () {
  2182. function Axis() {
  2183. }
  2184. Axis.X = new Vector3(1, 0, 0);
  2185. Axis.Y = new Vector3(0, 1, 0);
  2186. Axis.Z = new Vector3(0, 0, 1);
  2187. return Axis;
  2188. })();
  2189. BABYLON.Axis = Axis;
  2190. ;
  2191. var BezierCurve = (function () {
  2192. function BezierCurve() {
  2193. }
  2194. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2195. // Extract X (which is equal to time here)
  2196. var f0 = 1 - 3 * x2 + 3 * x1;
  2197. var f1 = 3 * x2 - 6 * x1;
  2198. var f2 = 3 * x1;
  2199. var refinedT = t;
  2200. for (var i = 0; i < 5; i++) {
  2201. var refinedT2 = refinedT * refinedT;
  2202. var refinedT3 = refinedT2 * refinedT;
  2203. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2204. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2205. refinedT -= (x - t) * slope;
  2206. refinedT = Math.min(1, Math.max(0, refinedT));
  2207. }
  2208. // Resolve cubic bezier for the given x
  2209. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 + 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 + Math.pow(refinedT, 3);
  2210. };
  2211. return BezierCurve;
  2212. })();
  2213. BABYLON.BezierCurve = BezierCurve;
  2214. (function (Orientation) {
  2215. Orientation[Orientation["CW"] = 0] = "CW";
  2216. Orientation[Orientation["CCW"] = 1] = "CCW";
  2217. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2218. var Orientation = BABYLON.Orientation;
  2219. var Angle = (function () {
  2220. function Angle(radians) {
  2221. var _this = this;
  2222. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2223. this.radians = function () { return _this._radians; };
  2224. this._radians = radians;
  2225. if (this._radians < 0)
  2226. this._radians += (2 * Math.PI);
  2227. }
  2228. Angle.BetweenTwoPoints = function (a, b) {
  2229. var delta = b.subtract(a);
  2230. var theta = Math.atan2(delta.y, delta.x);
  2231. return new Angle(theta);
  2232. };
  2233. Angle.FromRadians = function (radians) {
  2234. return new Angle(radians);
  2235. };
  2236. Angle.FromDegrees = function (degrees) {
  2237. return new Angle(degrees * Math.PI / 180);
  2238. };
  2239. return Angle;
  2240. })();
  2241. BABYLON.Angle = Angle;
  2242. var Arc2 = (function () {
  2243. function Arc2(startPoint, midPoint, endPoint) {
  2244. this.startPoint = startPoint;
  2245. this.midPoint = midPoint;
  2246. this.endPoint = endPoint;
  2247. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2248. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2249. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2250. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2251. 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);
  2252. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2253. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2254. var a1 = this.startAngle.degrees();
  2255. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2256. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2257. // angles correction
  2258. if (a2 - a1 > +180.0)
  2259. a2 -= 360.0;
  2260. if (a2 - a1 < -180.0)
  2261. a2 += 360.0;
  2262. if (a3 - a2 > +180.0)
  2263. a3 -= 360.0;
  2264. if (a3 - a2 < -180.0)
  2265. a3 += 360.0;
  2266. this.orientation = (a2 - a1) < 0 ? 0 /* CW */ : 1 /* CCW */;
  2267. this.angle = Angle.FromDegrees(this.orientation === 0 /* CW */ ? a1 - a3 : a3 - a1);
  2268. }
  2269. return Arc2;
  2270. })();
  2271. BABYLON.Arc2 = Arc2;
  2272. var PathCursor = (function () {
  2273. function PathCursor(path) {
  2274. this.path = path;
  2275. this._onchange = new Array();
  2276. this.value = 0;
  2277. this.animations = new Array();
  2278. }
  2279. PathCursor.prototype.getPoint = function () {
  2280. var point = this.path.getPointAtLengthPosition(this.value);
  2281. return new Vector3(point.x, 0, point.y);
  2282. };
  2283. PathCursor.prototype.moveAhead = function (step) {
  2284. if (step === void 0) { step = 0.002; }
  2285. this.move(step);
  2286. return this;
  2287. };
  2288. PathCursor.prototype.moveBack = function (step) {
  2289. if (step === void 0) { step = 0.002; }
  2290. this.move(-step);
  2291. return this;
  2292. };
  2293. PathCursor.prototype.move = function (step) {
  2294. if (Math.abs(step) > 1) {
  2295. throw "step size should be less than 1.";
  2296. }
  2297. this.value += step;
  2298. this.ensureLimits();
  2299. this.raiseOnChange();
  2300. return this;
  2301. };
  2302. PathCursor.prototype.ensureLimits = function () {
  2303. while (this.value > 1) {
  2304. this.value -= 1;
  2305. }
  2306. while (this.value < 0) {
  2307. this.value += 1;
  2308. }
  2309. return this;
  2310. };
  2311. // used by animation engine
  2312. PathCursor.prototype.markAsDirty = function (propertyName) {
  2313. this.ensureLimits();
  2314. this.raiseOnChange();
  2315. return this;
  2316. };
  2317. PathCursor.prototype.raiseOnChange = function () {
  2318. var _this = this;
  2319. this._onchange.forEach(function (f) { return f(_this); });
  2320. return this;
  2321. };
  2322. PathCursor.prototype.onchange = function (f) {
  2323. this._onchange.push(f);
  2324. return this;
  2325. };
  2326. return PathCursor;
  2327. })();
  2328. BABYLON.PathCursor = PathCursor;
  2329. var Path2 = (function () {
  2330. function Path2(x, y) {
  2331. this._points = [];
  2332. this._length = 0;
  2333. this.closed = false;
  2334. this._points.push(new Vector2(x, y));
  2335. }
  2336. Path2.prototype.addLineTo = function (x, y) {
  2337. if (closed) {
  2338. BABYLON.Tools.Error("cannot add lines to closed paths");
  2339. return this;
  2340. }
  2341. var newPoint = new Vector2(x, y);
  2342. var previousPoint = this._points[this._points.length - 1];
  2343. this._points.push(newPoint);
  2344. this._length += newPoint.subtract(previousPoint).length();
  2345. return this;
  2346. };
  2347. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2348. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2349. if (closed) {
  2350. BABYLON.Tools.Error("cannot add arcs to closed paths");
  2351. return this;
  2352. }
  2353. var startPoint = this._points[this._points.length - 1];
  2354. var midPoint = new Vector2(midX, midY);
  2355. var endPoint = new Vector2(endX, endY);
  2356. var arc = new Arc2(startPoint, midPoint, endPoint);
  2357. var increment = arc.angle.radians() / numberOfSegments;
  2358. if (arc.orientation === 0 /* CW */)
  2359. increment *= -1;
  2360. var currentAngle = arc.startAngle.radians() + increment;
  2361. for (var i = 0; i < numberOfSegments; i++) {
  2362. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2363. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2364. this.addLineTo(x, y);
  2365. currentAngle += increment;
  2366. }
  2367. return this;
  2368. };
  2369. Path2.prototype.close = function () {
  2370. this.closed = true;
  2371. return this;
  2372. };
  2373. Path2.prototype.length = function () {
  2374. var result = this._length;
  2375. if (!this.closed) {
  2376. var lastPoint = this._points[this._points.length - 1];
  2377. var firstPoint = this._points[0];
  2378. result += (firstPoint.subtract(lastPoint).length());
  2379. }
  2380. return result;
  2381. };
  2382. Path2.prototype.getPoints = function () {
  2383. return this._points;
  2384. };
  2385. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2386. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2387. BABYLON.Tools.Error("normalized length position should be between 0 and 1.");
  2388. return Vector2.Zero();
  2389. }
  2390. var lengthPosition = normalizedLengthPosition * this.length();
  2391. var previousOffset = 0;
  2392. for (var i = 0; i < this._points.length; i++) {
  2393. var j = (i + 1) % this._points.length;
  2394. var a = this._points[i];
  2395. var b = this._points[j];
  2396. var bToA = b.subtract(a);
  2397. var nextOffset = (bToA.length() + previousOffset);
  2398. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2399. var dir = bToA.normalize();
  2400. var localOffset = lengthPosition - previousOffset;
  2401. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2402. }
  2403. previousOffset = nextOffset;
  2404. }
  2405. BABYLON.Tools.Error("internal error");
  2406. return Vector2.Zero();
  2407. };
  2408. Path2.StartingAt = function (x, y) {
  2409. return new Path2(x, y);
  2410. };
  2411. return Path2;
  2412. })();
  2413. BABYLON.Path2 = Path2;
  2414. var Path3D = (function () {
  2415. function Path3D(path) {
  2416. this.path = path;
  2417. this._curve = [];
  2418. this._distances = [];
  2419. this._tangents = [];
  2420. this._normals = [];
  2421. this._binormals = [];
  2422. this._curve = path.slice(); // copy array
  2423. var l = this._curve.length;
  2424. // first and last tangents
  2425. this._tangents[0] = this._curve[1].subtract(this._curve[0]);
  2426. this._tangents[0].normalize();
  2427. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2428. this._tangents[l - 1].normalize();
  2429. // normals and binormals at first point : arbitrary vector with _normalVector()
  2430. var tg0 = this._tangents[0];
  2431. var pp0 = this._normalVector(this._curve[0], tg0);
  2432. this._normals[0] = pp0;
  2433. this._normals[0].normalize();
  2434. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2435. this._normals[0].normalize();
  2436. this._distances[0] = 0;
  2437. // normals and binormals : next points
  2438. var prev; // previous vector (segment)
  2439. var cur; // current vector (segment)
  2440. var curTang; // current tangent
  2441. var prevNorm; // previous normal
  2442. var prevBinor; // previous binormal
  2443. for (var i = 1; i < l; i++) {
  2444. // tangents
  2445. prev = this._curve[i].subtract(this._curve[i - 1]);
  2446. if (i < l - 1) {
  2447. cur = this._curve[i + 1].subtract(this._curve[i]);
  2448. this._tangents[i] = prev.add(cur);
  2449. this._tangents[i].normalize();
  2450. }
  2451. this._distances[i] = this._distances[i - 1] + prev.length();
  2452. // normals and binormals
  2453. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  2454. curTang = this._tangents[i];
  2455. prevNorm = this._normals[i - 1];
  2456. prevBinor = this._binormals[i - 1];
  2457. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  2458. this._normals[i].normalize();
  2459. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  2460. this._binormals[i].normalize();
  2461. }
  2462. }
  2463. Path3D.prototype.getCurve = function () {
  2464. return this._curve;
  2465. };
  2466. Path3D.prototype.getTangents = function () {
  2467. return this._tangents;
  2468. };
  2469. Path3D.prototype.getNormals = function () {
  2470. return this._normals;
  2471. };
  2472. Path3D.prototype.getBinormals = function () {
  2473. return this._binormals;
  2474. };
  2475. Path3D.prototype.getDistances = function () {
  2476. return this._distances;
  2477. };
  2478. // private function normalVector(v0, vt) :
  2479. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  2480. Path3D.prototype._normalVector = function (v0, vt) {
  2481. var point;
  2482. if (vt.x !== 1) {
  2483. point = new Vector3(1, 0, 0);
  2484. }
  2485. else if (vt.y !== 1) {
  2486. point = new Vector3(0, 1, 0);
  2487. }
  2488. else if (vt.z !== 1) {
  2489. point = new Vector3(0, 0, 1);
  2490. }
  2491. var normal0 = Vector3.Cross(vt, point);
  2492. normal0.normalize();
  2493. return normal0;
  2494. };
  2495. return Path3D;
  2496. })();
  2497. BABYLON.Path3D = Path3D;
  2498. })(BABYLON || (BABYLON = {}));
  2499. //# sourceMappingURL=babylon.math.js.mapvar BABYLON;
  2500. (function (BABYLON) {
  2501. // Screenshots
  2502. var screenshotCanvas;
  2503. var cloneValue = function (source, destinationObject) {
  2504. if (!source)
  2505. return null;
  2506. if (source instanceof BABYLON.Mesh) {
  2507. return null;
  2508. }
  2509. if (source instanceof BABYLON.SubMesh) {
  2510. return source.clone(destinationObject);
  2511. }
  2512. else if (source.clone) {
  2513. return source.clone();
  2514. }
  2515. return null;
  2516. };
  2517. var Tools = (function () {
  2518. function Tools() {
  2519. }
  2520. Tools.GetFilename = function (path) {
  2521. var index = path.lastIndexOf("/");
  2522. if (index < 0)
  2523. return path;
  2524. return path.substring(index + 1);
  2525. };
  2526. Tools.GetDOMTextContent = function (element) {
  2527. var result = "";
  2528. var child = element.firstChild;
  2529. while (child) {
  2530. if (child.nodeType === 3) {
  2531. result += child.textContent;
  2532. }
  2533. child = child.nextSibling;
  2534. }
  2535. return result;
  2536. };
  2537. Tools.ToDegrees = function (angle) {
  2538. return angle * 180 / Math.PI;
  2539. };
  2540. Tools.ToRadians = function (angle) {
  2541. return angle * Math.PI / 180;
  2542. };
  2543. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  2544. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  2545. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  2546. for (var index = indexStart; index < indexStart + indexCount; index++) {
  2547. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  2548. minimum = BABYLON.Vector3.Minimize(current, minimum);
  2549. maximum = BABYLON.Vector3.Maximize(current, maximum);
  2550. }
  2551. return {
  2552. minimum: minimum,
  2553. maximum: maximum
  2554. };
  2555. };
  2556. Tools.ExtractMinAndMax = function (positions, start, count) {
  2557. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  2558. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  2559. for (var index = start; index < start + count; index++) {
  2560. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  2561. minimum = BABYLON.Vector3.Minimize(current, minimum);
  2562. maximum = BABYLON.Vector3.Maximize(current, maximum);
  2563. }
  2564. return {
  2565. minimum: minimum,
  2566. maximum: maximum
  2567. };
  2568. };
  2569. Tools.MakeArray = function (obj, allowsNullUndefined) {
  2570. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  2571. return undefined;
  2572. return Array.isArray(obj) ? obj : [obj];
  2573. };
  2574. // Misc.
  2575. Tools.GetPointerPrefix = function () {
  2576. var eventPrefix = "pointer";
  2577. // Check if hand.js is referenced or if the browser natively supports pointer events
  2578. if (!navigator.pointerEnabled) {
  2579. eventPrefix = "mouse";
  2580. }
  2581. return eventPrefix;
  2582. };
  2583. Tools.QueueNewFrame = function (func) {
  2584. if (window.requestAnimationFrame)
  2585. window.requestAnimationFrame(func);
  2586. else if (window.msRequestAnimationFrame)
  2587. window.msRequestAnimationFrame(func);
  2588. else if (window.webkitRequestAnimationFrame)
  2589. window.webkitRequestAnimationFrame(func);
  2590. else if (window.mozRequestAnimationFrame)
  2591. window.mozRequestAnimationFrame(func);
  2592. else if (window.oRequestAnimationFrame)
  2593. window.oRequestAnimationFrame(func);
  2594. else {
  2595. window.setTimeout(func, 16);
  2596. }
  2597. };
  2598. Tools.RequestFullscreen = function (element) {
  2599. if (element.requestFullscreen)
  2600. element.requestFullscreen();
  2601. else if (element.msRequestFullscreen)
  2602. element.msRequestFullscreen();
  2603. else if (element.webkitRequestFullscreen)
  2604. element.webkitRequestFullscreen();
  2605. else if (element.mozRequestFullScreen)
  2606. element.mozRequestFullScreen();
  2607. };
  2608. Tools.ExitFullscreen = function () {
  2609. if (document.exitFullscreen) {
  2610. document.exitFullscreen();
  2611. }
  2612. else if (document.mozCancelFullScreen) {
  2613. document.mozCancelFullScreen();
  2614. }
  2615. else if (document.webkitCancelFullScreen) {
  2616. document.webkitCancelFullScreen();
  2617. }
  2618. else if (document.msCancelFullScreen) {
  2619. document.msCancelFullScreen();
  2620. }
  2621. };
  2622. // External files
  2623. Tools.CleanUrl = function (url) {
  2624. url = url.replace(/#/mg, "%23");
  2625. return url;
  2626. };
  2627. Tools.LoadImage = function (url, onload, onerror, database) {
  2628. url = Tools.CleanUrl(url);
  2629. var img = new Image();
  2630. if (url.substr(0, 5) !== "data:")
  2631. img.crossOrigin = 'anonymous';
  2632. img.onload = function () {
  2633. onload(img);
  2634. };
  2635. img.onerror = function (err) {
  2636. onerror(img, err);
  2637. };
  2638. var noIndexedDB = function () {
  2639. img.src = url;
  2640. };
  2641. var loadFromIndexedDB = function () {
  2642. database.loadImageFromDB(url, img);
  2643. };
  2644. //ANY database to do!
  2645. if (database && database.enableTexturesOffline && BABYLON.Database.isUASupportingBlobStorage) {
  2646. database.openAsync(loadFromIndexedDB, noIndexedDB);
  2647. }
  2648. else {
  2649. if (url.indexOf("file:") === -1) {
  2650. noIndexedDB();
  2651. }
  2652. else {
  2653. try {
  2654. var textureName = url.substring(5);
  2655. var blobURL;
  2656. try {
  2657. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  2658. }
  2659. catch (ex) {
  2660. // Chrome doesn't support oneTimeOnly parameter
  2661. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  2662. }
  2663. img.src = blobURL;
  2664. }
  2665. catch (e) {
  2666. Tools.Log("Error while trying to load texture: " + textureName);
  2667. img.src = null;
  2668. }
  2669. }
  2670. }
  2671. return img;
  2672. };
  2673. //ANY
  2674. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  2675. url = Tools.CleanUrl(url);
  2676. var noIndexedDB = function () {
  2677. var request = new XMLHttpRequest();
  2678. var loadUrl = Tools.BaseUrl + url;
  2679. request.open('GET', loadUrl, true);
  2680. if (useArrayBuffer) {
  2681. request.responseType = "arraybuffer";
  2682. }
  2683. request.onprogress = progressCallBack;
  2684. request.onreadystatechange = function () {
  2685. if (request.readyState === 4) {
  2686. if (request.status === 200 || Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  2687. callback(!useArrayBuffer ? request.responseText : request.response);
  2688. }
  2689. else {
  2690. if (onError) {
  2691. onError();
  2692. }
  2693. else {
  2694. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  2695. }
  2696. }
  2697. }
  2698. };
  2699. request.send(null);
  2700. };
  2701. var loadFromIndexedDB = function () {
  2702. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  2703. };
  2704. if (url.indexOf("file:") !== -1) {
  2705. var fileName = url.substring(5);
  2706. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  2707. }
  2708. else {
  2709. // Caching all files
  2710. if (database && database.enableSceneOffline) {
  2711. database.openAsync(loadFromIndexedDB, noIndexedDB);
  2712. }
  2713. else {
  2714. noIndexedDB();
  2715. }
  2716. }
  2717. };
  2718. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  2719. var reader = new FileReader();
  2720. reader.onload = function (e) {
  2721. //target doesn't have result from ts 1.3
  2722. callback(e.target['result']);
  2723. };
  2724. reader.onprogress = progressCallback;
  2725. reader.readAsDataURL(fileToLoad);
  2726. };
  2727. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  2728. var reader = new FileReader();
  2729. reader.onerror = function (e) {
  2730. Tools.Log("Error while reading file: " + fileToLoad.name);
  2731. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.81, 0], meshes: [], cameras: [], lights: [] }));
  2732. };
  2733. reader.onload = function (e) {
  2734. //target doesn't have result from ts 1.3
  2735. callback(e.target['result']);
  2736. };
  2737. reader.onprogress = progressCallBack;
  2738. if (!useArrayBuffer) {
  2739. // Asynchronous read
  2740. reader.readAsText(fileToLoad);
  2741. }
  2742. else {
  2743. reader.readAsArrayBuffer(fileToLoad);
  2744. }
  2745. };
  2746. // Misc.
  2747. Tools.Clamp = function (value, min, max) {
  2748. if (min === void 0) { min = 0; }
  2749. if (max === void 0) { max = 1; }
  2750. return Math.min(max, Math.max(min, value));
  2751. };
  2752. // Returns -1 when value is a negative number and
  2753. // +1 when value is a positive number.
  2754. Tools.Sign = function (value) {
  2755. value = +value; // convert to a number
  2756. if (value === 0 || isNaN(value))
  2757. return value;
  2758. return value > 0 ? 1 : -1;
  2759. };
  2760. Tools.Format = function (value, decimals) {
  2761. if (decimals === void 0) { decimals = 2; }
  2762. return value.toFixed(decimals);
  2763. };
  2764. Tools.CheckExtends = function (v, min, max) {
  2765. if (v.x < min.x)
  2766. min.x = v.x;
  2767. if (v.y < min.y)
  2768. min.y = v.y;
  2769. if (v.z < min.z)
  2770. min.z = v.z;
  2771. if (v.x > max.x)
  2772. max.x = v.x;
  2773. if (v.y > max.y)
  2774. max.y = v.y;
  2775. if (v.z > max.z)
  2776. max.z = v.z;
  2777. };
  2778. Tools.WithinEpsilon = function (a, b, epsilon) {
  2779. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  2780. var num = a - b;
  2781. return -epsilon <= num && num <= epsilon;
  2782. };
  2783. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  2784. for (var prop in source) {
  2785. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  2786. continue;
  2787. }
  2788. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  2789. continue;
  2790. }
  2791. var sourceValue = source[prop];
  2792. var typeOfSourceValue = typeof sourceValue;
  2793. if (typeOfSourceValue === "function") {
  2794. continue;
  2795. }
  2796. if (typeOfSourceValue === "object") {
  2797. if (sourceValue instanceof Array) {
  2798. destination[prop] = [];
  2799. if (sourceValue.length > 0) {
  2800. if (typeof sourceValue[0] == "object") {
  2801. for (var index = 0; index < sourceValue.length; index++) {
  2802. var clonedValue = cloneValue(sourceValue[index], destination);
  2803. if (destination[prop].indexOf(clonedValue) === -1) {
  2804. destination[prop].push(clonedValue);
  2805. }
  2806. }
  2807. }
  2808. else {
  2809. destination[prop] = sourceValue.slice(0);
  2810. }
  2811. }
  2812. }
  2813. else {
  2814. destination[prop] = cloneValue(sourceValue, destination);
  2815. }
  2816. }
  2817. else {
  2818. destination[prop] = sourceValue;
  2819. }
  2820. }
  2821. };
  2822. Tools.IsEmpty = function (obj) {
  2823. for (var i in obj) {
  2824. return false;
  2825. }
  2826. return true;
  2827. };
  2828. Tools.RegisterTopRootEvents = function (events) {
  2829. for (var index = 0; index < events.length; index++) {
  2830. var event = events[index];
  2831. window.addEventListener(event.name, event.handler, false);
  2832. try {
  2833. if (window.parent) {
  2834. window.parent.addEventListener(event.name, event.handler, false);
  2835. }
  2836. }
  2837. catch (e) {
  2838. }
  2839. }
  2840. };
  2841. Tools.UnregisterTopRootEvents = function (events) {
  2842. for (var index = 0; index < events.length; index++) {
  2843. var event = events[index];
  2844. window.removeEventListener(event.name, event.handler);
  2845. try {
  2846. if (window.parent) {
  2847. window.parent.removeEventListener(event.name, event.handler);
  2848. }
  2849. }
  2850. catch (e) {
  2851. }
  2852. }
  2853. };
  2854. Tools.DumpFramebuffer = function (width, height, engine) {
  2855. // Read the contents of the framebuffer
  2856. var numberOfChannelsByLine = width * 4;
  2857. var halfHeight = height / 2;
  2858. //Reading datas from WebGL
  2859. var data = engine.readPixels(0, 0, width, height);
  2860. for (var i = 0; i < halfHeight; i++) {
  2861. for (var j = 0; j < numberOfChannelsByLine; j++) {
  2862. var currentCell = j + i * numberOfChannelsByLine;
  2863. var targetLine = height - i - 1;
  2864. var targetCell = j + targetLine * numberOfChannelsByLine;
  2865. var temp = data[currentCell];
  2866. data[currentCell] = data[targetCell];
  2867. data[targetCell] = temp;
  2868. }
  2869. }
  2870. // Create a 2D canvas to store the result
  2871. if (!screenshotCanvas) {
  2872. screenshotCanvas = document.createElement('canvas');
  2873. }
  2874. screenshotCanvas.width = width;
  2875. screenshotCanvas.height = height;
  2876. var context = screenshotCanvas.getContext('2d');
  2877. // Copy the pixels to a 2D canvas
  2878. var imageData = context.createImageData(width, height);
  2879. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  2880. var castData = imageData.data;
  2881. castData.set(data);
  2882. context.putImageData(imageData, 0, 0);
  2883. var base64Image = screenshotCanvas.toDataURL();
  2884. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  2885. if (("download" in document.createElement("a"))) {
  2886. var a = window.document.createElement("a");
  2887. a.href = base64Image;
  2888. var date = new Date();
  2889. var stringDate = date.getFullYear() + "/" + date.getMonth() + "/" + date.getDate() + "-" + date.getHours() + ":" + date.getMinutes();
  2890. a.setAttribute("download", "screenshot-" + stringDate + ".png");
  2891. window.document.body.appendChild(a);
  2892. a.addEventListener("click", function () {
  2893. a.parentElement.removeChild(a);
  2894. });
  2895. a.click();
  2896. }
  2897. else {
  2898. var newWindow = window.open("");
  2899. var img = newWindow.document.createElement("img");
  2900. img.src = base64Image;
  2901. newWindow.document.body.appendChild(img);
  2902. }
  2903. };
  2904. Tools.CreateScreenshot = function (engine, camera, size) {
  2905. var width;
  2906. var height;
  2907. var scene = camera.getScene();
  2908. var previousCamera = null;
  2909. if (scene.activeCamera !== camera) {
  2910. previousCamera = scene.activeCamera;
  2911. scene.activeCamera = camera;
  2912. }
  2913. //If a precision value is specified
  2914. if (size.precision) {
  2915. width = Math.round(engine.getRenderWidth() * size.precision);
  2916. height = Math.round(width / engine.getAspectRatio(camera));
  2917. size = { width: width, height: height };
  2918. }
  2919. else if (size.width && size.height) {
  2920. width = size.width;
  2921. height = size.height;
  2922. }
  2923. else if (size.width && !size.height) {
  2924. width = size.width;
  2925. height = Math.round(width / engine.getAspectRatio(camera));
  2926. size = { width: width, height: height };
  2927. }
  2928. else if (size.height && !size.width) {
  2929. height = size.height;
  2930. width = Math.round(height * engine.getAspectRatio(camera));
  2931. size = { width: width, height: height };
  2932. }
  2933. else if (!isNaN(size)) {
  2934. height = size;
  2935. width = size;
  2936. }
  2937. else {
  2938. Tools.Error("Invalid 'size' parameter !");
  2939. return;
  2940. }
  2941. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  2942. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  2943. texture.renderList = scene.meshes;
  2944. texture.onAfterRender = function () {
  2945. Tools.DumpFramebuffer(width, height, engine);
  2946. };
  2947. scene.incrementRenderId();
  2948. texture.render(true);
  2949. texture.dispose();
  2950. if (previousCamera) {
  2951. scene.activeCamera = previousCamera;
  2952. }
  2953. };
  2954. // XHR response validator for local file scenario
  2955. Tools.ValidateXHRData = function (xhr, dataType) {
  2956. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  2957. if (dataType === void 0) { dataType = 7; }
  2958. try {
  2959. if (dataType & 1) {
  2960. if (xhr.responseText && xhr.responseText.length > 0) {
  2961. return true;
  2962. }
  2963. else if (dataType === 1) {
  2964. return false;
  2965. }
  2966. }
  2967. if (dataType & 2) {
  2968. // Check header width and height since there is no "TGA" magic number
  2969. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  2970. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  2971. return true;
  2972. }
  2973. else if (dataType === 2) {
  2974. return false;
  2975. }
  2976. }
  2977. if (dataType & 4) {
  2978. // Check for the "DDS" magic number
  2979. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  2980. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  2981. return true;
  2982. }
  2983. else {
  2984. return false;
  2985. }
  2986. }
  2987. }
  2988. catch (e) {
  2989. }
  2990. return false;
  2991. };
  2992. Object.defineProperty(Tools, "NoneLogLevel", {
  2993. get: function () {
  2994. return Tools._NoneLogLevel;
  2995. },
  2996. enumerable: true,
  2997. configurable: true
  2998. });
  2999. Object.defineProperty(Tools, "MessageLogLevel", {
  3000. get: function () {
  3001. return Tools._MessageLogLevel;
  3002. },
  3003. enumerable: true,
  3004. configurable: true
  3005. });
  3006. Object.defineProperty(Tools, "WarningLogLevel", {
  3007. get: function () {
  3008. return Tools._WarningLogLevel;
  3009. },
  3010. enumerable: true,
  3011. configurable: true
  3012. });
  3013. Object.defineProperty(Tools, "ErrorLogLevel", {
  3014. get: function () {
  3015. return Tools._ErrorLogLevel;
  3016. },
  3017. enumerable: true,
  3018. configurable: true
  3019. });
  3020. Object.defineProperty(Tools, "AllLogLevel", {
  3021. get: function () {
  3022. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  3023. },
  3024. enumerable: true,
  3025. configurable: true
  3026. });
  3027. Tools._AddLogEntry = function (entry) {
  3028. Tools._LogCache = entry + Tools._LogCache;
  3029. if (Tools.OnNewCacheEntry) {
  3030. Tools.OnNewCacheEntry(entry);
  3031. }
  3032. };
  3033. Tools._FormatMessage = function (message) {
  3034. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  3035. var date = new Date();
  3036. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  3037. };
  3038. Tools._LogDisabled = function (message) {
  3039. // nothing to do
  3040. };
  3041. Tools._LogEnabled = function (message) {
  3042. var formattedMessage = Tools._FormatMessage(message);
  3043. console.log("BJS - " + formattedMessage);
  3044. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  3045. Tools._AddLogEntry(entry);
  3046. };
  3047. Tools._WarnDisabled = function (message) {
  3048. // nothing to do
  3049. };
  3050. Tools._WarnEnabled = function (message) {
  3051. var formattedMessage = Tools._FormatMessage(message);
  3052. console.warn("BJS - " + formattedMessage);
  3053. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  3054. Tools._AddLogEntry(entry);
  3055. };
  3056. Tools._ErrorDisabled = function (message) {
  3057. // nothing to do
  3058. };
  3059. Tools._ErrorEnabled = function (message) {
  3060. var formattedMessage = Tools._FormatMessage(message);
  3061. console.error("BJS - " + formattedMessage);
  3062. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  3063. Tools._AddLogEntry(entry);
  3064. };
  3065. Object.defineProperty(Tools, "LogCache", {
  3066. get: function () {
  3067. return Tools._LogCache;
  3068. },
  3069. enumerable: true,
  3070. configurable: true
  3071. });
  3072. Object.defineProperty(Tools, "LogLevels", {
  3073. set: function (level) {
  3074. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  3075. Tools.Log = Tools._LogEnabled;
  3076. }
  3077. else {
  3078. Tools.Log = Tools._LogDisabled;
  3079. }
  3080. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  3081. Tools.Warn = Tools._WarnEnabled;
  3082. }
  3083. else {
  3084. Tools.Warn = Tools._WarnDisabled;
  3085. }
  3086. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  3087. Tools.Error = Tools._ErrorEnabled;
  3088. }
  3089. else {
  3090. Tools.Error = Tools._ErrorDisabled;
  3091. }
  3092. },
  3093. enumerable: true,
  3094. configurable: true
  3095. });
  3096. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  3097. get: function () {
  3098. return Tools._PerformanceNoneLogLevel;
  3099. },
  3100. enumerable: true,
  3101. configurable: true
  3102. });
  3103. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  3104. get: function () {
  3105. return Tools._PerformanceUserMarkLogLevel;
  3106. },
  3107. enumerable: true,
  3108. configurable: true
  3109. });
  3110. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  3111. get: function () {
  3112. return Tools._PerformanceConsoleLogLevel;
  3113. },
  3114. enumerable: true,
  3115. configurable: true
  3116. });
  3117. Object.defineProperty(Tools, "PerformanceLogLevel", {
  3118. set: function (level) {
  3119. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  3120. Tools.StartPerformanceCounter = Tools._StartUserMark;
  3121. Tools.EndPerformanceCounter = Tools._EndUserMark;
  3122. return;
  3123. }
  3124. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  3125. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  3126. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  3127. return;
  3128. }
  3129. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  3130. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  3131. },
  3132. enumerable: true,
  3133. configurable: true
  3134. });
  3135. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  3136. };
  3137. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  3138. };
  3139. Tools._StartUserMark = function (counterName, condition) {
  3140. if (condition === void 0) { condition = true; }
  3141. if (!condition || !Tools._performance.mark) {
  3142. return;
  3143. }
  3144. Tools._performance.mark(counterName + "-Begin");
  3145. };
  3146. Tools._EndUserMark = function (counterName, condition) {
  3147. if (condition === void 0) { condition = true; }
  3148. if (!condition || !Tools._performance.mark) {
  3149. return;
  3150. }
  3151. Tools._performance.mark(counterName + "-End");
  3152. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  3153. };
  3154. Tools._StartPerformanceConsole = function (counterName, condition) {
  3155. if (condition === void 0) { condition = true; }
  3156. if (!condition) {
  3157. return;
  3158. }
  3159. Tools._StartUserMark(counterName, condition);
  3160. if (console.time) {
  3161. console.time(counterName);
  3162. }
  3163. };
  3164. Tools._EndPerformanceConsole = function (counterName, condition) {
  3165. if (condition === void 0) { condition = true; }
  3166. if (!condition) {
  3167. return;
  3168. }
  3169. Tools._EndUserMark(counterName, condition);
  3170. if (console.time) {
  3171. console.timeEnd(counterName);
  3172. }
  3173. };
  3174. Object.defineProperty(Tools, "Now", {
  3175. get: function () {
  3176. if (window.performance && window.performance.now) {
  3177. return window.performance.now();
  3178. }
  3179. return new Date().getTime();
  3180. },
  3181. enumerable: true,
  3182. configurable: true
  3183. });
  3184. // Deprecated
  3185. Tools.GetFps = function () {
  3186. Tools.Warn("Tools.GetFps() is deprecated. Please use engine.getFps() instead");
  3187. return 0;
  3188. };
  3189. Tools.BaseUrl = "";
  3190. Tools.GetExponantOfTwo = function (value, max) {
  3191. var count = 1;
  3192. do {
  3193. count *= 2;
  3194. } while (count < value);
  3195. if (count > max)
  3196. count = max;
  3197. return count;
  3198. };
  3199. // Logs
  3200. Tools._NoneLogLevel = 0;
  3201. Tools._MessageLogLevel = 1;
  3202. Tools._WarningLogLevel = 2;
  3203. Tools._ErrorLogLevel = 4;
  3204. Tools._LogCache = "";
  3205. Tools.Log = Tools._LogEnabled;
  3206. Tools.Warn = Tools._WarnEnabled;
  3207. Tools.Error = Tools._ErrorEnabled;
  3208. // Performances
  3209. Tools._PerformanceNoneLogLevel = 0;
  3210. Tools._PerformanceUserMarkLogLevel = 1;
  3211. Tools._PerformanceConsoleLogLevel = 2;
  3212. Tools._performance = window.performance;
  3213. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  3214. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  3215. return Tools;
  3216. })();
  3217. BABYLON.Tools = Tools;
  3218. /**
  3219. * An implementation of a loop for asynchronous functions.
  3220. */
  3221. var AsyncLoop = (function () {
  3222. /**
  3223. * Constroctor.
  3224. * @param iterations the number of iterations.
  3225. * @param _fn the function to run each iteration
  3226. * @param _successCallback the callback that will be called upon succesful execution
  3227. * @param offset starting offset.
  3228. */
  3229. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  3230. if (offset === void 0) { offset = 0; }
  3231. this.iterations = iterations;
  3232. this._fn = _fn;
  3233. this._successCallback = _successCallback;
  3234. this.index = offset - 1;
  3235. this._done = false;
  3236. }
  3237. /**
  3238. * Execute the next iteration. Must be called after the last iteration was finished.
  3239. */
  3240. AsyncLoop.prototype.executeNext = function () {
  3241. if (!this._done) {
  3242. if (this.index + 1 < this.iterations) {
  3243. ++this.index;
  3244. this._fn(this);
  3245. }
  3246. else {
  3247. this.breakLoop();
  3248. }
  3249. }
  3250. };
  3251. /**
  3252. * Break the loop and run the success callback.
  3253. */
  3254. AsyncLoop.prototype.breakLoop = function () {
  3255. this._done = true;
  3256. this._successCallback();
  3257. };
  3258. /**
  3259. * Helper function
  3260. */
  3261. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  3262. if (offset === void 0) { offset = 0; }
  3263. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  3264. loop.executeNext();
  3265. return loop;
  3266. };
  3267. /**
  3268. * A for-loop that will run a given number of iterations synchronous and the rest async.
  3269. * @param iterations total number of iterations
  3270. * @param syncedIterations number of synchronous iterations in each async iteration.
  3271. * @param fn the function to call each iteration.
  3272. * @param callback a success call back that will be called when iterating stops.
  3273. * @param breakFunction a break condition (optional)
  3274. * @param timeout timeout settings for the setTimeout function. default - 0.
  3275. * @constructor
  3276. */
  3277. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  3278. if (timeout === void 0) { timeout = 0; }
  3279. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  3280. if (breakFunction && breakFunction())
  3281. loop.breakLoop();
  3282. else {
  3283. setTimeout(function () {
  3284. for (var i = 0; i < syncedIterations; ++i) {
  3285. var iteration = (loop.index * syncedIterations) + i;
  3286. if (iteration >= iterations)
  3287. break;
  3288. fn(iteration);
  3289. if (breakFunction && breakFunction()) {
  3290. loop.breakLoop();
  3291. break;
  3292. }
  3293. }
  3294. loop.executeNext();
  3295. }, timeout);
  3296. }
  3297. }, callback);
  3298. };
  3299. return AsyncLoop;
  3300. })();
  3301. BABYLON.AsyncLoop = AsyncLoop;
  3302. })(BABYLON || (BABYLON = {}));
  3303. //# sourceMappingURL=babylon.tools.js.mapvar BABYLON;
  3304. (function (BABYLON) {
  3305. var _DepthCullingState = (function () {
  3306. function _DepthCullingState() {
  3307. this._isDepthTestDirty = false;
  3308. this._isDepthMaskDirty = false;
  3309. this._isDepthFuncDirty = false;
  3310. this._isCullFaceDirty = false;
  3311. this._isCullDirty = false;
  3312. }
  3313. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  3314. get: function () {
  3315. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty;
  3316. },
  3317. enumerable: true,
  3318. configurable: true
  3319. });
  3320. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  3321. get: function () {
  3322. return this._cullFace;
  3323. },
  3324. set: function (value) {
  3325. if (this._cullFace === value) {
  3326. return;
  3327. }
  3328. this._cullFace = value;
  3329. this._isCullFaceDirty = true;
  3330. },
  3331. enumerable: true,
  3332. configurable: true
  3333. });
  3334. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  3335. get: function () {
  3336. return this._cull;
  3337. },
  3338. set: function (value) {
  3339. if (this._cull === value) {
  3340. return;
  3341. }
  3342. this._cull = value;
  3343. this._isCullDirty = true;
  3344. },
  3345. enumerable: true,
  3346. configurable: true
  3347. });
  3348. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  3349. get: function () {
  3350. return this._depthFunc;
  3351. },
  3352. set: function (value) {
  3353. if (this._depthFunc === value) {
  3354. return;
  3355. }
  3356. this._depthFunc = value;
  3357. this._isDepthFuncDirty = true;
  3358. },
  3359. enumerable: true,
  3360. configurable: true
  3361. });
  3362. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  3363. get: function () {
  3364. return this._depthMask;
  3365. },
  3366. set: function (value) {
  3367. if (this._depthMask === value) {
  3368. return;
  3369. }
  3370. this._depthMask = value;
  3371. this._isDepthMaskDirty = true;
  3372. },
  3373. enumerable: true,
  3374. configurable: true
  3375. });
  3376. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  3377. get: function () {
  3378. return this._depthTest;
  3379. },
  3380. set: function (value) {
  3381. if (this._depthTest === value) {
  3382. return;
  3383. }
  3384. this._depthTest = value;
  3385. this._isDepthTestDirty = true;
  3386. },
  3387. enumerable: true,
  3388. configurable: true
  3389. });
  3390. _DepthCullingState.prototype.reset = function () {
  3391. this._depthMask = true;
  3392. this._depthTest = true;
  3393. this._depthFunc = null;
  3394. this._cull = null;
  3395. this._cullFace = null;
  3396. this._isDepthTestDirty = true;
  3397. this._isDepthMaskDirty = true;
  3398. this._isDepthFuncDirty = false;
  3399. this._isCullFaceDirty = false;
  3400. this._isCullDirty = false;
  3401. };
  3402. _DepthCullingState.prototype.apply = function (gl) {
  3403. if (!this.isDirty) {
  3404. return;
  3405. }
  3406. // Cull
  3407. if (this._isCullDirty) {
  3408. if (this.cull) {
  3409. gl.enable(gl.CULL_FACE);
  3410. }
  3411. else {
  3412. gl.disable(gl.CULL_FACE);
  3413. }
  3414. this._isCullDirty = false;
  3415. }
  3416. // Cull face
  3417. if (this._isCullFaceDirty) {
  3418. gl.cullFace(this.cullFace);
  3419. this._isCullFaceDirty = false;
  3420. }
  3421. // Depth mask
  3422. if (this._isDepthMaskDirty) {
  3423. gl.depthMask(this.depthMask);
  3424. this._isDepthMaskDirty = false;
  3425. }
  3426. // Depth test
  3427. if (this._isDepthTestDirty) {
  3428. if (this.depthTest) {
  3429. gl.enable(gl.DEPTH_TEST);
  3430. }
  3431. else {
  3432. gl.disable(gl.DEPTH_TEST);
  3433. }
  3434. this._isDepthTestDirty = false;
  3435. }
  3436. // Depth func
  3437. if (this._isDepthFuncDirty) {
  3438. gl.depthFunc(this.depthFunc);
  3439. this._isDepthFuncDirty = false;
  3440. }
  3441. };
  3442. return _DepthCullingState;
  3443. })();
  3444. BABYLON._DepthCullingState = _DepthCullingState;
  3445. var _AlphaState = (function () {
  3446. function _AlphaState() {
  3447. this._isAlphaBlendDirty = false;
  3448. this._isBlendFunctionParametersDirty = false;
  3449. this._alphaBlend = false;
  3450. this._blendFunctionParameters = new Array(4);
  3451. }
  3452. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  3453. get: function () {
  3454. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  3455. },
  3456. enumerable: true,
  3457. configurable: true
  3458. });
  3459. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  3460. get: function () {
  3461. return this._alphaBlend;
  3462. },
  3463. set: function (value) {
  3464. if (this._alphaBlend === value) {
  3465. return;
  3466. }
  3467. this._alphaBlend = value;
  3468. this._isAlphaBlendDirty = true;
  3469. },
  3470. enumerable: true,
  3471. configurable: true
  3472. });
  3473. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  3474. if (this._blendFunctionParameters[0] === value0 && this._blendFunctionParameters[1] === value1 && this._blendFunctionParameters[2] === value2 && this._blendFunctionParameters[3] === value3) {
  3475. return;
  3476. }
  3477. this._blendFunctionParameters[0] = value0;
  3478. this._blendFunctionParameters[1] = value1;
  3479. this._blendFunctionParameters[2] = value2;
  3480. this._blendFunctionParameters[3] = value3;
  3481. this._isBlendFunctionParametersDirty = true;
  3482. };
  3483. _AlphaState.prototype.reset = function () {
  3484. this._alphaBlend = false;
  3485. this._blendFunctionParameters[0] = null;
  3486. this._blendFunctionParameters[1] = null;
  3487. this._blendFunctionParameters[2] = null;
  3488. this._blendFunctionParameters[3] = null;
  3489. this._isAlphaBlendDirty = true;
  3490. this._isBlendFunctionParametersDirty = false;
  3491. };
  3492. _AlphaState.prototype.apply = function (gl) {
  3493. if (!this.isDirty) {
  3494. return;
  3495. }
  3496. // Alpha blend
  3497. if (this._isAlphaBlendDirty) {
  3498. if (this._alphaBlend) {
  3499. gl.enable(gl.BLEND);
  3500. }
  3501. else {
  3502. gl.disable(gl.BLEND);
  3503. }
  3504. this._isAlphaBlendDirty = false;
  3505. }
  3506. // Alpha function
  3507. if (this._isBlendFunctionParametersDirty) {
  3508. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  3509. this._isBlendFunctionParametersDirty = false;
  3510. }
  3511. };
  3512. return _AlphaState;
  3513. })();
  3514. BABYLON._AlphaState = _AlphaState;
  3515. var compileShader = function (gl, source, type, defines) {
  3516. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  3517. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  3518. gl.compileShader(shader);
  3519. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  3520. throw new Error(gl.getShaderInfoLog(shader));
  3521. }
  3522. return shader;
  3523. };
  3524. var getWebGLTextureType = function (gl, type) {
  3525. var textureType = gl.UNSIGNED_BYTE;
  3526. if (type === Engine.TEXTURETYPE_FLOAT)
  3527. textureType = gl.FLOAT;
  3528. return textureType;
  3529. };
  3530. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  3531. var magFilter = gl.NEAREST;
  3532. var minFilter = gl.NEAREST;
  3533. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  3534. magFilter = gl.LINEAR;
  3535. if (generateMipMaps) {
  3536. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  3537. }
  3538. else {
  3539. minFilter = gl.LINEAR;
  3540. }
  3541. }
  3542. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  3543. magFilter = gl.LINEAR;
  3544. if (generateMipMaps) {
  3545. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  3546. }
  3547. else {
  3548. minFilter = gl.LINEAR;
  3549. }
  3550. }
  3551. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  3552. magFilter = gl.NEAREST;
  3553. if (generateMipMaps) {
  3554. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  3555. }
  3556. else {
  3557. minFilter = gl.NEAREST;
  3558. }
  3559. }
  3560. return {
  3561. min: minFilter,
  3562. mag: magFilter
  3563. };
  3564. };
  3565. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  3566. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  3567. var engine = scene.getEngine();
  3568. var potWidth = BABYLON.Tools.GetExponantOfTwo(width, engine.getCaps().maxTextureSize);
  3569. var potHeight = BABYLON.Tools.GetExponantOfTwo(height, engine.getCaps().maxTextureSize);
  3570. gl.bindTexture(gl.TEXTURE_2D, texture);
  3571. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  3572. processFunction(potWidth, potHeight);
  3573. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  3574. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  3575. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  3576. if (!noMipmap && !isCompressed) {
  3577. gl.generateMipmap(gl.TEXTURE_2D);
  3578. }
  3579. gl.bindTexture(gl.TEXTURE_2D, null);
  3580. engine._activeTexturesCache = [];
  3581. texture._baseWidth = width;
  3582. texture._baseHeight = height;
  3583. texture._width = potWidth;
  3584. texture._height = potHeight;
  3585. texture.isReady = true;
  3586. texture.samplingMode = samplingMode;
  3587. scene._removePendingData(texture);
  3588. };
  3589. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  3590. var onload = function () {
  3591. loadedImages[index] = img;
  3592. loadedImages._internalCount++;
  3593. scene._removePendingData(img);
  3594. if (loadedImages._internalCount === 6) {
  3595. onfinish(loadedImages);
  3596. }
  3597. };
  3598. var onerror = function () {
  3599. scene._removePendingData(img);
  3600. };
  3601. var img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  3602. scene._addPendingData(img);
  3603. };
  3604. var cascadeLoad = function (rootUrl, scene, onfinish, extensions) {
  3605. var loadedImages = [];
  3606. loadedImages._internalCount = 0;
  3607. for (var index = 0; index < 6; index++) {
  3608. partialLoad(rootUrl + extensions[index], index, loadedImages, scene, onfinish);
  3609. }
  3610. };
  3611. var EngineCapabilities = (function () {
  3612. function EngineCapabilities() {
  3613. }
  3614. return EngineCapabilities;
  3615. })();
  3616. BABYLON.EngineCapabilities = EngineCapabilities;
  3617. /**
  3618. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  3619. */
  3620. var Engine = (function () {
  3621. /**
  3622. * @constructor
  3623. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  3624. * @param {boolean} [antialias] - enable antialias
  3625. * @param options - further options to be sent to the getContext function
  3626. */
  3627. function Engine(canvas, antialias, options) {
  3628. var _this = this;
  3629. // Public members
  3630. this.isFullscreen = false;
  3631. this.isPointerLock = false;
  3632. this.cullBackFaces = true;
  3633. this.renderEvenInBackground = true;
  3634. this.scenes = new Array();
  3635. this._windowIsBackground = false;
  3636. this._loadingDivBackgroundColor = "black";
  3637. this._drawCalls = 0;
  3638. this._renderingQueueLaunched = false;
  3639. this._activeRenderLoops = [];
  3640. // FPS
  3641. this.fpsRange = 60;
  3642. this.previousFramesDuration = [];
  3643. this.fps = 60;
  3644. this.deltaTime = 0;
  3645. // States
  3646. this._depthCullingState = new _DepthCullingState();
  3647. this._alphaState = new _AlphaState();
  3648. this._alphaMode = Engine.ALPHA_DISABLE;
  3649. // Cache
  3650. this._loadedTexturesCache = new Array();
  3651. this._activeTexturesCache = new Array();
  3652. this._compiledEffects = {};
  3653. this._uintIndicesCurrentlySet = false;
  3654. this._renderingCanvas = canvas;
  3655. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  3656. options = options || {};
  3657. options.antialias = antialias;
  3658. try {
  3659. this._gl = canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options);
  3660. }
  3661. catch (e) {
  3662. throw new Error("WebGL not supported");
  3663. }
  3664. if (!this._gl) {
  3665. throw new Error("WebGL not supported");
  3666. }
  3667. this._onBlur = function () {
  3668. _this._windowIsBackground = true;
  3669. };
  3670. this._onFocus = function () {
  3671. _this._windowIsBackground = false;
  3672. };
  3673. window.addEventListener("blur", this._onBlur);
  3674. window.addEventListener("focus", this._onFocus);
  3675. // Textures
  3676. this._workingCanvas = document.createElement("canvas");
  3677. this._workingContext = this._workingCanvas.getContext("2d");
  3678. // Viewport
  3679. this._hardwareScalingLevel = 1.0 / (window.devicePixelRatio || 1.0);
  3680. this.resize();
  3681. // Caps
  3682. this._caps = new EngineCapabilities();
  3683. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  3684. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  3685. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  3686. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  3687. // Infos
  3688. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  3689. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  3690. if (rendererInfo != null) {
  3691. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  3692. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  3693. }
  3694. if (!this._glVendor) {
  3695. this._glVendor = "Unknown vendor";
  3696. }
  3697. if (!this._glRenderer) {
  3698. this._glRenderer = "Unknown renderer";
  3699. }
  3700. // Extensions
  3701. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  3702. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  3703. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  3704. 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');
  3705. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  3706. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  3707. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  3708. // Depth buffer
  3709. this.setDepthBuffer(true);
  3710. this.setDepthFunctionToLessOrEqual();
  3711. this.setDepthWrite(true);
  3712. // Fullscreen
  3713. this._onFullscreenChange = function () {
  3714. if (document.fullscreen !== undefined) {
  3715. _this.isFullscreen = document.fullscreen;
  3716. }
  3717. else if (document.mozFullScreen !== undefined) {
  3718. _this.isFullscreen = document.mozFullScreen;
  3719. }
  3720. else if (document.webkitIsFullScreen !== undefined) {
  3721. _this.isFullscreen = document.webkitIsFullScreen;
  3722. }
  3723. else if (document.msIsFullScreen !== undefined) {
  3724. _this.isFullscreen = document.msIsFullScreen;
  3725. }
  3726. // Pointer lock
  3727. if (_this.isFullscreen && _this._pointerLockRequested) {
  3728. canvas.requestPointerLock = canvas.requestPointerLock || canvas.msRequestPointerLock || canvas.mozRequestPointerLock || canvas.webkitRequestPointerLock;
  3729. if (canvas.requestPointerLock) {
  3730. canvas.requestPointerLock();
  3731. }
  3732. }
  3733. };
  3734. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  3735. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  3736. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  3737. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  3738. // Pointer lock
  3739. this._onPointerLockChange = function () {
  3740. _this.isPointerLock = (document.mozPointerLockElement === canvas || document.webkitPointerLockElement === canvas || document.msPointerLockElement === canvas || document.pointerLockElement === canvas);
  3741. };
  3742. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  3743. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  3744. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  3745. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  3746. if (!Engine.audioEngine) {
  3747. Engine.audioEngine = new BABYLON.AudioEngine();
  3748. }
  3749. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  3750. }
  3751. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  3752. get: function () {
  3753. return Engine._ALPHA_DISABLE;
  3754. },
  3755. enumerable: true,
  3756. configurable: true
  3757. });
  3758. Object.defineProperty(Engine, "ALPHA_ADD", {
  3759. get: function () {
  3760. return Engine._ALPHA_ADD;
  3761. },
  3762. enumerable: true,
  3763. configurable: true
  3764. });
  3765. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  3766. get: function () {
  3767. return Engine._ALPHA_COMBINE;
  3768. },
  3769. enumerable: true,
  3770. configurable: true
  3771. });
  3772. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  3773. get: function () {
  3774. return Engine._DELAYLOADSTATE_NONE;
  3775. },
  3776. enumerable: true,
  3777. configurable: true
  3778. });
  3779. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  3780. get: function () {
  3781. return Engine._DELAYLOADSTATE_LOADED;
  3782. },
  3783. enumerable: true,
  3784. configurable: true
  3785. });
  3786. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  3787. get: function () {
  3788. return Engine._DELAYLOADSTATE_LOADING;
  3789. },
  3790. enumerable: true,
  3791. configurable: true
  3792. });
  3793. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  3794. get: function () {
  3795. return Engine._DELAYLOADSTATE_NOTLOADED;
  3796. },
  3797. enumerable: true,
  3798. configurable: true
  3799. });
  3800. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  3801. get: function () {
  3802. return Engine._TEXTUREFORMAT_ALPHA;
  3803. },
  3804. enumerable: true,
  3805. configurable: true
  3806. });
  3807. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  3808. get: function () {
  3809. return Engine._TEXTUREFORMAT_LUMINANCE;
  3810. },
  3811. enumerable: true,
  3812. configurable: true
  3813. });
  3814. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  3815. get: function () {
  3816. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  3817. },
  3818. enumerable: true,
  3819. configurable: true
  3820. });
  3821. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  3822. get: function () {
  3823. return Engine._TEXTUREFORMAT_RGB;
  3824. },
  3825. enumerable: true,
  3826. configurable: true
  3827. });
  3828. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  3829. get: function () {
  3830. return Engine._TEXTUREFORMAT_RGBA;
  3831. },
  3832. enumerable: true,
  3833. configurable: true
  3834. });
  3835. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  3836. get: function () {
  3837. return Engine._TEXTURETYPE_UNSIGNED_INT;
  3838. },
  3839. enumerable: true,
  3840. configurable: true
  3841. });
  3842. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  3843. get: function () {
  3844. return Engine._TEXTURETYPE_FLOAT;
  3845. },
  3846. enumerable: true,
  3847. configurable: true
  3848. });
  3849. Object.defineProperty(Engine, "Version", {
  3850. get: function () {
  3851. return "2.0.0";
  3852. },
  3853. enumerable: true,
  3854. configurable: true
  3855. });
  3856. Engine.prototype.getGlInfo = function () {
  3857. return {
  3858. vendor: this._glVendor,
  3859. renderer: this._glRenderer,
  3860. version: this._glVersion
  3861. };
  3862. };
  3863. Engine.prototype.getAspectRatio = function (camera) {
  3864. var viewport = camera.viewport;
  3865. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  3866. };
  3867. Engine.prototype.getRenderWidth = function () {
  3868. if (this._currentRenderTarget) {
  3869. return this._currentRenderTarget._width;
  3870. }
  3871. return this._renderingCanvas.width;
  3872. };
  3873. Engine.prototype.getRenderHeight = function () {
  3874. if (this._currentRenderTarget) {
  3875. return this._currentRenderTarget._height;
  3876. }
  3877. return this._renderingCanvas.height;
  3878. };
  3879. Engine.prototype.getRenderingCanvas = function () {
  3880. return this._renderingCanvas;
  3881. };
  3882. Engine.prototype.getRenderingCanvasClientRect = function () {
  3883. return this._renderingCanvas.getBoundingClientRect();
  3884. };
  3885. Engine.prototype.setHardwareScalingLevel = function (level) {
  3886. this._hardwareScalingLevel = level;
  3887. this.resize();
  3888. };
  3889. Engine.prototype.getHardwareScalingLevel = function () {
  3890. return this._hardwareScalingLevel;
  3891. };
  3892. Engine.prototype.getLoadedTexturesCache = function () {
  3893. return this._loadedTexturesCache;
  3894. };
  3895. Engine.prototype.getCaps = function () {
  3896. return this._caps;
  3897. };
  3898. Object.defineProperty(Engine.prototype, "drawCalls", {
  3899. get: function () {
  3900. return this._drawCalls;
  3901. },
  3902. enumerable: true,
  3903. configurable: true
  3904. });
  3905. // Methods
  3906. Engine.prototype.resetDrawCalls = function () {
  3907. this._drawCalls = 0;
  3908. };
  3909. Engine.prototype.setDepthFunctionToGreater = function () {
  3910. this._depthCullingState.depthFunc = this._gl.GREATER;
  3911. };
  3912. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  3913. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  3914. };
  3915. Engine.prototype.setDepthFunctionToLess = function () {
  3916. this._depthCullingState.depthFunc = this._gl.LESS;
  3917. };
  3918. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  3919. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  3920. };
  3921. /**
  3922. * stop executing a render loop function and remove it from the execution array
  3923. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  3924. */
  3925. Engine.prototype.stopRenderLoop = function (renderFunction) {
  3926. if (!renderFunction) {
  3927. this._activeRenderLoops = [];
  3928. return;
  3929. }
  3930. var index = this._activeRenderLoops.indexOf(renderFunction);
  3931. if (index >= 0) {
  3932. this._activeRenderLoops.splice(index, 1);
  3933. }
  3934. };
  3935. Engine.prototype._renderLoop = function () {
  3936. var _this = this;
  3937. var shouldRender = true;
  3938. if (!this.renderEvenInBackground && this._windowIsBackground) {
  3939. shouldRender = false;
  3940. }
  3941. if (shouldRender) {
  3942. // Start new frame
  3943. this.beginFrame();
  3944. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  3945. var renderFunction = this._activeRenderLoops[index];
  3946. renderFunction();
  3947. }
  3948. // Present
  3949. this.endFrame();
  3950. }
  3951. if (this._activeRenderLoops.length > 0) {
  3952. // Register new frame
  3953. BABYLON.Tools.QueueNewFrame(function () {
  3954. _this._renderLoop();
  3955. });
  3956. }
  3957. else {
  3958. this._renderingQueueLaunched = false;
  3959. }
  3960. };
  3961. /**
  3962. * Register and execute a render loop. The engine can have more than one render function.
  3963. * @param {Function} renderFunction - the function to continuesly execute starting the next render loop.
  3964. * @example
  3965. * engine.runRenderLoop(function () {
  3966. * scene.render()
  3967. * })
  3968. */
  3969. Engine.prototype.runRenderLoop = function (renderFunction) {
  3970. var _this = this;
  3971. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  3972. return;
  3973. }
  3974. this._activeRenderLoops.push(renderFunction);
  3975. if (!this._renderingQueueLaunched) {
  3976. this._renderingQueueLaunched = true;
  3977. BABYLON.Tools.QueueNewFrame(function () {
  3978. _this._renderLoop();
  3979. });
  3980. }
  3981. };
  3982. /**
  3983. * Toggle full screen mode.
  3984. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  3985. */
  3986. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  3987. if (this.isFullscreen) {
  3988. BABYLON.Tools.ExitFullscreen();
  3989. }
  3990. else {
  3991. this._pointerLockRequested = requestPointerLock;
  3992. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  3993. }
  3994. };
  3995. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  3996. this.applyStates();
  3997. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  3998. if (this._depthCullingState.depthMask) {
  3999. this._gl.clearDepth(1.0);
  4000. }
  4001. var mode = 0;
  4002. if (backBuffer)
  4003. mode |= this._gl.COLOR_BUFFER_BIT;
  4004. if (depthStencil && this._depthCullingState.depthMask)
  4005. mode |= this._gl.DEPTH_BUFFER_BIT;
  4006. this._gl.clear(mode);
  4007. };
  4008. /**
  4009. * Set the WebGL's viewport
  4010. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  4011. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  4012. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  4013. */
  4014. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  4015. var width = requiredWidth || this._renderingCanvas.width;
  4016. var height = requiredHeight || this._renderingCanvas.height;
  4017. var x = viewport.x || 0;
  4018. var y = viewport.y || 0;
  4019. this._cachedViewport = viewport;
  4020. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  4021. };
  4022. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  4023. this._cachedViewport = null;
  4024. this._gl.viewport(x, y, width, height);
  4025. };
  4026. Engine.prototype.beginFrame = function () {
  4027. this._measureFps();
  4028. };
  4029. Engine.prototype.endFrame = function () {
  4030. //this.flushFramebuffer();
  4031. };
  4032. /**
  4033. * resize the view according to the canvas' size.
  4034. * @example
  4035. * window.addEventListener("resize", function () {
  4036. * engine.resize();
  4037. * });
  4038. */
  4039. Engine.prototype.resize = function () {
  4040. this.setSize(this._renderingCanvas.clientWidth / this._hardwareScalingLevel, this._renderingCanvas.clientHeight / this._hardwareScalingLevel);
  4041. };
  4042. /**
  4043. * force a specific size of the canvas
  4044. * @param {number} width - the new canvas' width
  4045. * @param {number} height - the new canvas' height
  4046. */
  4047. Engine.prototype.setSize = function (width, height) {
  4048. this._renderingCanvas.width = width;
  4049. this._renderingCanvas.height = height;
  4050. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  4051. };
  4052. Engine.prototype.bindFramebuffer = function (texture) {
  4053. this._currentRenderTarget = texture;
  4054. var gl = this._gl;
  4055. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  4056. this._gl.viewport(0, 0, texture._width, texture._height);
  4057. this.wipeCaches();
  4058. };
  4059. Engine.prototype.unBindFramebuffer = function (texture) {
  4060. this._currentRenderTarget = null;
  4061. if (texture.generateMipMaps) {
  4062. var gl = this._gl;
  4063. gl.bindTexture(gl.TEXTURE_2D, texture);
  4064. gl.generateMipmap(gl.TEXTURE_2D);
  4065. gl.bindTexture(gl.TEXTURE_2D, null);
  4066. }
  4067. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  4068. };
  4069. Engine.prototype.flushFramebuffer = function () {
  4070. this._gl.flush();
  4071. };
  4072. Engine.prototype.restoreDefaultFramebuffer = function () {
  4073. this._currentRenderTarget = null;
  4074. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  4075. this.setViewport(this._cachedViewport);
  4076. this.wipeCaches();
  4077. };
  4078. // VBOs
  4079. Engine.prototype._resetVertexBufferBinding = function () {
  4080. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  4081. this._cachedVertexBuffers = null;
  4082. };
  4083. Engine.prototype.createVertexBuffer = function (vertices) {
  4084. var vbo = this._gl.createBuffer();
  4085. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  4086. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  4087. this._resetVertexBufferBinding();
  4088. vbo.references = 1;
  4089. return vbo;
  4090. };
  4091. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  4092. var vbo = this._gl.createBuffer();
  4093. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  4094. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  4095. this._resetVertexBufferBinding();
  4096. vbo.references = 1;
  4097. return vbo;
  4098. };
  4099. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  4100. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  4101. if (offset === undefined) {
  4102. offset = 0;
  4103. }
  4104. if (vertices instanceof Float32Array) {
  4105. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  4106. }
  4107. else {
  4108. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  4109. }
  4110. this._resetVertexBufferBinding();
  4111. };
  4112. Engine.prototype._resetIndexBufferBinding = function () {
  4113. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  4114. this._cachedIndexBuffer = null;
  4115. };
  4116. Engine.prototype.createIndexBuffer = function (indices) {
  4117. var vbo = this._gl.createBuffer();
  4118. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  4119. // Check for 32 bits indices
  4120. var arrayBuffer;
  4121. var need32Bits = false;
  4122. if (this._caps.uintIndices) {
  4123. for (var index = 0; index < indices.length; index++) {
  4124. if (indices[index] > 65535) {
  4125. need32Bits = true;
  4126. break;
  4127. }
  4128. }
  4129. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  4130. }
  4131. else {
  4132. arrayBuffer = new Uint16Array(indices);
  4133. }
  4134. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  4135. this._resetIndexBufferBinding();
  4136. vbo.references = 1;
  4137. vbo.is32Bits = need32Bits;
  4138. return vbo;
  4139. };
  4140. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  4141. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  4142. this._cachedVertexBuffers = vertexBuffer;
  4143. this._cachedEffectForVertexBuffers = effect;
  4144. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  4145. var offset = 0;
  4146. for (var index = 0; index < vertexDeclaration.length; index++) {
  4147. var order = effect.getAttributeLocation(index);
  4148. if (order >= 0) {
  4149. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  4150. }
  4151. offset += vertexDeclaration[index] * 4;
  4152. }
  4153. }
  4154. if (this._cachedIndexBuffer !== indexBuffer) {
  4155. this._cachedIndexBuffer = indexBuffer;
  4156. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  4157. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  4158. }
  4159. };
  4160. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  4161. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  4162. this._cachedVertexBuffers = vertexBuffers;
  4163. this._cachedEffectForVertexBuffers = effect;
  4164. var attributes = effect.getAttributesNames();
  4165. for (var index = 0; index < attributes.length; index++) {
  4166. var order = effect.getAttributeLocation(index);
  4167. if (order >= 0) {
  4168. var vertexBuffer = vertexBuffers[attributes[index]];
  4169. if (!vertexBuffer) {
  4170. continue;
  4171. }
  4172. var stride = vertexBuffer.getStrideSize();
  4173. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  4174. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  4175. }
  4176. }
  4177. }
  4178. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  4179. this._cachedIndexBuffer = indexBuffer;
  4180. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  4181. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  4182. }
  4183. };
  4184. Engine.prototype._releaseBuffer = function (buffer) {
  4185. buffer.references--;
  4186. if (buffer.references === 0) {
  4187. this._gl.deleteBuffer(buffer);
  4188. return true;
  4189. }
  4190. return false;
  4191. };
  4192. Engine.prototype.createInstancesBuffer = function (capacity) {
  4193. var buffer = this._gl.createBuffer();
  4194. buffer.capacity = capacity;
  4195. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  4196. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  4197. return buffer;
  4198. };
  4199. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  4200. this._gl.deleteBuffer(buffer);
  4201. };
  4202. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  4203. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  4204. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  4205. for (var index = 0; index < 4; index++) {
  4206. var offsetLocation = offsetLocations[index];
  4207. this._gl.enableVertexAttribArray(offsetLocation);
  4208. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  4209. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  4210. }
  4211. };
  4212. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  4213. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  4214. for (var index = 0; index < 4; index++) {
  4215. var offsetLocation = offsetLocations[index];
  4216. this._gl.disableVertexAttribArray(offsetLocation);
  4217. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  4218. }
  4219. };
  4220. Engine.prototype.applyStates = function () {
  4221. this._depthCullingState.apply(this._gl);
  4222. this._alphaState.apply(this._gl);
  4223. };
  4224. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  4225. // Apply states
  4226. this.applyStates();
  4227. this._drawCalls++;
  4228. // Render
  4229. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  4230. if (instancesCount) {
  4231. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2, instancesCount);
  4232. return;
  4233. }
  4234. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2);
  4235. };
  4236. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  4237. // Apply states
  4238. this.applyStates();
  4239. this._drawCalls++;
  4240. if (instancesCount) {
  4241. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  4242. return;
  4243. }
  4244. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  4245. };
  4246. // Shaders
  4247. Engine.prototype._releaseEffect = function (effect) {
  4248. if (this._compiledEffects[effect._key]) {
  4249. delete this._compiledEffects[effect._key];
  4250. if (effect.getProgram()) {
  4251. this._gl.deleteProgram(effect.getProgram());
  4252. }
  4253. }
  4254. };
  4255. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  4256. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  4257. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  4258. var name = vertex + "+" + fragment + "@" + defines;
  4259. if (this._compiledEffects[name]) {
  4260. return this._compiledEffects[name];
  4261. }
  4262. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  4263. effect._key = name;
  4264. this._compiledEffects[name] = effect;
  4265. return effect;
  4266. };
  4267. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  4268. if (uniformsNames === void 0) { uniformsNames = []; }
  4269. if (samplers === void 0) { samplers = []; }
  4270. if (defines === void 0) { defines = ""; }
  4271. return this.createEffect({
  4272. vertex: "particles",
  4273. fragmentElement: fragmentName
  4274. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  4275. };
  4276. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  4277. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  4278. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  4279. var shaderProgram = this._gl.createProgram();
  4280. this._gl.attachShader(shaderProgram, vertexShader);
  4281. this._gl.attachShader(shaderProgram, fragmentShader);
  4282. this._gl.linkProgram(shaderProgram);
  4283. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  4284. if (!linked) {
  4285. var error = this._gl.getProgramInfoLog(shaderProgram);
  4286. if (error) {
  4287. throw new Error(error);
  4288. }
  4289. }
  4290. this._gl.deleteShader(vertexShader);
  4291. this._gl.deleteShader(fragmentShader);
  4292. return shaderProgram;
  4293. };
  4294. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  4295. var results = [];
  4296. for (var index = 0; index < uniformsNames.length; index++) {
  4297. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  4298. }
  4299. return results;
  4300. };
  4301. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  4302. var results = [];
  4303. for (var index = 0; index < attributesNames.length; index++) {
  4304. try {
  4305. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  4306. }
  4307. catch (e) {
  4308. results.push(-1);
  4309. }
  4310. }
  4311. return results;
  4312. };
  4313. Engine.prototype.enableEffect = function (effect) {
  4314. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  4315. if (effect && effect.onBind) {
  4316. effect.onBind(effect);
  4317. }
  4318. return;
  4319. }
  4320. this._vertexAttribArrays = this._vertexAttribArrays || [];
  4321. // Use program
  4322. this._gl.useProgram(effect.getProgram());
  4323. for (var i in this._vertexAttribArrays) {
  4324. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  4325. continue;
  4326. }
  4327. this._vertexAttribArrays[i] = false;
  4328. this._gl.disableVertexAttribArray(i);
  4329. }
  4330. var attributesCount = effect.getAttributesCount();
  4331. for (var index = 0; index < attributesCount; index++) {
  4332. // Attributes
  4333. var order = effect.getAttributeLocation(index);
  4334. if (order >= 0) {
  4335. this._vertexAttribArrays[order] = true;
  4336. this._gl.enableVertexAttribArray(order);
  4337. }
  4338. }
  4339. this._currentEffect = effect;
  4340. if (effect.onBind) {
  4341. effect.onBind(effect);
  4342. }
  4343. };
  4344. Engine.prototype.setArray = function (uniform, array) {
  4345. if (!uniform)
  4346. return;
  4347. this._gl.uniform1fv(uniform, array);
  4348. };
  4349. Engine.prototype.setArray2 = function (uniform, array) {
  4350. if (!uniform || array.length % 2 !== 0)
  4351. return;
  4352. this._gl.uniform2fv(uniform, array);
  4353. };
  4354. Engine.prototype.setArray3 = function (uniform, array) {
  4355. if (!uniform || array.length % 3 !== 0)
  4356. return;
  4357. this._gl.uniform3fv(uniform, array);
  4358. };
  4359. Engine.prototype.setArray4 = function (uniform, array) {
  4360. if (!uniform || array.length % 4 !== 0)
  4361. return;
  4362. this._gl.uniform4fv(uniform, array);
  4363. };
  4364. Engine.prototype.setMatrices = function (uniform, matrices) {
  4365. if (!uniform)
  4366. return;
  4367. this._gl.uniformMatrix4fv(uniform, false, matrices);
  4368. };
  4369. Engine.prototype.setMatrix = function (uniform, matrix) {
  4370. if (!uniform)
  4371. return;
  4372. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  4373. };
  4374. Engine.prototype.setFloat = function (uniform, value) {
  4375. if (!uniform)
  4376. return;
  4377. this._gl.uniform1f(uniform, value);
  4378. };
  4379. Engine.prototype.setFloat2 = function (uniform, x, y) {
  4380. if (!uniform)
  4381. return;
  4382. this._gl.uniform2f(uniform, x, y);
  4383. };
  4384. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  4385. if (!uniform)
  4386. return;
  4387. this._gl.uniform3f(uniform, x, y, z);
  4388. };
  4389. Engine.prototype.setBool = function (uniform, bool) {
  4390. if (!uniform)
  4391. return;
  4392. this._gl.uniform1i(uniform, bool);
  4393. };
  4394. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  4395. if (!uniform)
  4396. return;
  4397. this._gl.uniform4f(uniform, x, y, z, w);
  4398. };
  4399. Engine.prototype.setColor3 = function (uniform, color3) {
  4400. if (!uniform)
  4401. return;
  4402. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  4403. };
  4404. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  4405. if (!uniform)
  4406. return;
  4407. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  4408. };
  4409. // States
  4410. Engine.prototype.setState = function (culling, force) {
  4411. // Culling
  4412. if (this._depthCullingState.cull !== culling || force) {
  4413. if (culling) {
  4414. this._depthCullingState.cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  4415. this._depthCullingState.cull = true;
  4416. }
  4417. else {
  4418. this._depthCullingState.cull = false;
  4419. }
  4420. }
  4421. };
  4422. Engine.prototype.setDepthBuffer = function (enable) {
  4423. this._depthCullingState.depthTest = enable;
  4424. };
  4425. Engine.prototype.getDepthWrite = function () {
  4426. return this._depthCullingState.depthMask;
  4427. };
  4428. Engine.prototype.setDepthWrite = function (enable) {
  4429. this._depthCullingState.depthMask = enable;
  4430. };
  4431. Engine.prototype.setColorWrite = function (enable) {
  4432. this._gl.colorMask(enable, enable, enable, enable);
  4433. };
  4434. Engine.prototype.setAlphaMode = function (mode) {
  4435. switch (mode) {
  4436. case Engine.ALPHA_DISABLE:
  4437. this.setDepthWrite(true);
  4438. this._alphaState.alphaBlend = false;
  4439. break;
  4440. case Engine.ALPHA_COMBINE:
  4441. this.setDepthWrite(false);
  4442. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  4443. this._alphaState.alphaBlend = true;
  4444. break;
  4445. case Engine.ALPHA_ADD:
  4446. this.setDepthWrite(false);
  4447. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  4448. this._alphaState.alphaBlend = true;
  4449. break;
  4450. }
  4451. this._alphaMode = mode;
  4452. };
  4453. Engine.prototype.getAlphaMode = function () {
  4454. return this._alphaMode;
  4455. };
  4456. Engine.prototype.setAlphaTesting = function (enable) {
  4457. this._alphaTest = enable;
  4458. };
  4459. Engine.prototype.getAlphaTesting = function () {
  4460. return this._alphaTest;
  4461. };
  4462. // Textures
  4463. Engine.prototype.wipeCaches = function () {
  4464. this._activeTexturesCache = [];
  4465. this._currentEffect = null;
  4466. this._depthCullingState.reset();
  4467. this._alphaState.reset();
  4468. this._cachedVertexBuffers = null;
  4469. this._cachedIndexBuffer = null;
  4470. this._cachedEffectForVertexBuffers = null;
  4471. };
  4472. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  4473. var gl = this._gl;
  4474. gl.bindTexture(gl.TEXTURE_2D, texture);
  4475. var magFilter = gl.NEAREST;
  4476. var minFilter = gl.NEAREST;
  4477. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  4478. magFilter = gl.LINEAR;
  4479. minFilter = gl.LINEAR;
  4480. }
  4481. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  4482. magFilter = gl.LINEAR;
  4483. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  4484. }
  4485. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  4486. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  4487. gl.bindTexture(gl.TEXTURE_2D, null);
  4488. texture.samplingMode = samplingMode;
  4489. };
  4490. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  4491. var _this = this;
  4492. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  4493. if (onLoad === void 0) { onLoad = null; }
  4494. if (onError === void 0) { onError = null; }
  4495. if (buffer === void 0) { buffer = null; }
  4496. var texture = this._gl.createTexture();
  4497. var extension;
  4498. var fromData = false;
  4499. if (url.substr(0, 5) === "data:") {
  4500. fromData = true;
  4501. }
  4502. if (!fromData)
  4503. extension = url.substr(url.length - 4, 4).toLowerCase();
  4504. else {
  4505. var oldUrl = url;
  4506. fromData = oldUrl.split(':');
  4507. url = oldUrl;
  4508. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  4509. }
  4510. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  4511. var isTGA = (extension === ".tga");
  4512. scene._addPendingData(texture);
  4513. texture.url = url;
  4514. texture.noMipmap = noMipmap;
  4515. texture.references = 1;
  4516. this._loadedTexturesCache.push(texture);
  4517. var onerror = function () {
  4518. scene._removePendingData(texture);
  4519. if (onError) {
  4520. onError();
  4521. }
  4522. };
  4523. if (isTGA) {
  4524. var callback = function (arrayBuffer) {
  4525. var data = new Uint8Array(arrayBuffer);
  4526. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  4527. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  4528. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  4529. if (onLoad) {
  4530. onLoad();
  4531. }
  4532. }, samplingMode);
  4533. };
  4534. if (!(fromData instanceof Array))
  4535. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  4536. callback(arrayBuffer);
  4537. }, onerror, scene.database, true);
  4538. else
  4539. callback(buffer);
  4540. }
  4541. else if (isDDS) {
  4542. callback = function (data) {
  4543. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  4544. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  4545. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  4546. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  4547. if (onLoad) {
  4548. onLoad();
  4549. }
  4550. }, samplingMode);
  4551. };
  4552. if (!(fromData instanceof Array))
  4553. BABYLON.Tools.LoadFile(url, function (data) {
  4554. callback(data);
  4555. }, onerror, scene.database, true);
  4556. else
  4557. callback(buffer);
  4558. }
  4559. else {
  4560. var onload = function (img) {
  4561. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  4562. var isPot = (img.width === potWidth && img.height === potHeight);
  4563. if (!isPot) {
  4564. _this._workingCanvas.width = potWidth;
  4565. _this._workingCanvas.height = potHeight;
  4566. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  4567. _this._workingContext.imageSmoothingEnabled = false;
  4568. _this._workingContext.mozImageSmoothingEnabled = false;
  4569. _this._workingContext.oImageSmoothingEnabled = false;
  4570. _this._workingContext.webkitImageSmoothingEnabled = false;
  4571. _this._workingContext.msImageSmoothingEnabled = false;
  4572. }
  4573. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  4574. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  4575. _this._workingContext.imageSmoothingEnabled = true;
  4576. _this._workingContext.mozImageSmoothingEnabled = true;
  4577. _this._workingContext.oImageSmoothingEnabled = true;
  4578. _this._workingContext.webkitImageSmoothingEnabled = true;
  4579. _this._workingContext.msImageSmoothingEnabled = true;
  4580. }
  4581. }
  4582. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  4583. if (onLoad) {
  4584. onLoad();
  4585. }
  4586. }, samplingMode);
  4587. };
  4588. if (!(fromData instanceof Array))
  4589. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  4590. else
  4591. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  4592. }
  4593. return texture;
  4594. };
  4595. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode) {
  4596. var texture = this._gl.createTexture();
  4597. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4598. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  4599. // Format
  4600. var internalFormat = this._gl.RGBA;
  4601. switch (format) {
  4602. case Engine.TEXTUREFORMAT_ALPHA:
  4603. internalFormat = this._gl.ALPHA;
  4604. break;
  4605. case Engine.TEXTUREFORMAT_LUMINANCE:
  4606. internalFormat = this._gl.LUMINANCE;
  4607. break;
  4608. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  4609. internalFormat = this._gl.LUMINANCE_ALPHA;
  4610. break;
  4611. case Engine.TEXTUREFORMAT_RGB:
  4612. internalFormat = this._gl.RGB;
  4613. break;
  4614. case Engine.TEXTUREFORMAT_RGBA:
  4615. internalFormat = this._gl.RGBA;
  4616. break;
  4617. }
  4618. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, width, height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  4619. if (generateMipMaps) {
  4620. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4621. }
  4622. // Filters
  4623. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  4624. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  4625. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  4626. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4627. this._activeTexturesCache = [];
  4628. texture._baseWidth = width;
  4629. texture._baseHeight = height;
  4630. texture._width = width;
  4631. texture._height = height;
  4632. texture.isReady = true;
  4633. texture.references = 1;
  4634. texture.samplingMode = samplingMode;
  4635. this._loadedTexturesCache.push(texture);
  4636. return texture;
  4637. };
  4638. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  4639. var texture = this._gl.createTexture();
  4640. width = BABYLON.Tools.GetExponantOfTwo(width, this._caps.maxTextureSize);
  4641. height = BABYLON.Tools.GetExponantOfTwo(height, this._caps.maxTextureSize);
  4642. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4643. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  4644. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  4645. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  4646. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4647. this._activeTexturesCache = [];
  4648. texture._baseWidth = width;
  4649. texture._baseHeight = height;
  4650. texture._width = width;
  4651. texture._height = height;
  4652. texture.isReady = false;
  4653. texture.generateMipMaps = generateMipMaps;
  4654. texture.references = 1;
  4655. texture.samplingMode = samplingMode;
  4656. this._loadedTexturesCache.push(texture);
  4657. return texture;
  4658. };
  4659. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  4660. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4661. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  4662. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  4663. if (texture.generateMipMaps) {
  4664. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4665. }
  4666. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4667. this._activeTexturesCache = [];
  4668. texture.isReady = true;
  4669. };
  4670. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  4671. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4672. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  4673. // Scale the video if it is a NPOT using the current working canvas
  4674. if (video.videoWidth !== texture._width || video.videoHeight !== texture._height) {
  4675. if (!texture._workingCanvas) {
  4676. texture._workingCanvas = document.createElement("canvas");
  4677. texture._workingContext = texture._workingCanvas.getContext("2d");
  4678. texture._workingCanvas.width = texture._width;
  4679. texture._workingCanvas.height = texture._height;
  4680. }
  4681. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  4682. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  4683. }
  4684. else {
  4685. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  4686. }
  4687. if (texture.generateMipMaps) {
  4688. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4689. }
  4690. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4691. this._activeTexturesCache = [];
  4692. texture.isReady = true;
  4693. };
  4694. Engine.prototype.createRenderTargetTexture = function (size, options) {
  4695. // old version had a "generateMipMaps" arg instead of options.
  4696. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  4697. // in the same way, generateDepthBuffer is defaulted to true
  4698. var generateMipMaps = false;
  4699. var generateDepthBuffer = true;
  4700. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  4701. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  4702. if (options !== undefined) {
  4703. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipmaps;
  4704. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  4705. type = options.type === undefined ? type : options.type;
  4706. if (options.samplingMode !== undefined) {
  4707. samplingMode = options.samplingMode;
  4708. }
  4709. if (type === Engine.TEXTURETYPE_FLOAT) {
  4710. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  4711. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  4712. }
  4713. }
  4714. var gl = this._gl;
  4715. var texture = gl.createTexture();
  4716. gl.bindTexture(gl.TEXTURE_2D, texture);
  4717. var width = size.width || size;
  4718. var height = size.height || size;
  4719. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  4720. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  4721. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  4722. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  4723. }
  4724. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  4725. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  4726. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4727. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4728. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  4729. var depthBuffer;
  4730. // Create the depth buffer
  4731. if (generateDepthBuffer) {
  4732. depthBuffer = gl.createRenderbuffer();
  4733. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  4734. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  4735. }
  4736. // Create the framebuffer
  4737. var framebuffer = gl.createFramebuffer();
  4738. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  4739. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  4740. if (generateDepthBuffer) {
  4741. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  4742. }
  4743. // Unbind
  4744. gl.bindTexture(gl.TEXTURE_2D, null);
  4745. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  4746. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  4747. texture._framebuffer = framebuffer;
  4748. if (generateDepthBuffer) {
  4749. texture._depthBuffer = depthBuffer;
  4750. }
  4751. texture._width = width;
  4752. texture._height = height;
  4753. texture.isReady = true;
  4754. texture.generateMipMaps = generateMipMaps;
  4755. texture.references = 1;
  4756. texture.samplingMode = samplingMode;
  4757. this._activeTexturesCache = [];
  4758. this._loadedTexturesCache.push(texture);
  4759. return texture;
  4760. };
  4761. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  4762. var _this = this;
  4763. var gl = this._gl;
  4764. var texture = gl.createTexture();
  4765. texture.isCube = true;
  4766. texture.url = rootUrl;
  4767. texture.references = 1;
  4768. this._loadedTexturesCache.push(texture);
  4769. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  4770. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  4771. if (isDDS) {
  4772. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  4773. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  4774. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  4775. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  4776. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  4777. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  4778. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  4779. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  4780. }
  4781. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  4782. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  4783. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4784. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4785. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  4786. _this._activeTexturesCache = [];
  4787. texture._width = info.width;
  4788. texture._height = info.height;
  4789. texture.isReady = true;
  4790. }, null, null, true);
  4791. }
  4792. else {
  4793. cascadeLoad(rootUrl, scene, function (imgs) {
  4794. var width = BABYLON.Tools.GetExponantOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  4795. var height = width;
  4796. _this._workingCanvas.width = width;
  4797. _this._workingCanvas.height = height;
  4798. var faces = [
  4799. gl.TEXTURE_CUBE_MAP_POSITIVE_X,
  4800. gl.TEXTURE_CUBE_MAP_POSITIVE_Y,
  4801. gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  4802. gl.TEXTURE_CUBE_MAP_NEGATIVE_X,
  4803. gl.TEXTURE_CUBE_MAP_NEGATIVE_Y,
  4804. gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  4805. ];
  4806. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  4807. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  4808. for (var index = 0; index < faces.length; index++) {
  4809. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  4810. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  4811. }
  4812. if (!noMipmap) {
  4813. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  4814. }
  4815. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  4816. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  4817. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4818. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4819. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  4820. _this._activeTexturesCache = [];
  4821. texture._width = width;
  4822. texture._height = height;
  4823. texture.isReady = true;
  4824. }, extensions);
  4825. }
  4826. return texture;
  4827. };
  4828. Engine.prototype._releaseTexture = function (texture) {
  4829. var gl = this._gl;
  4830. if (texture._framebuffer) {
  4831. gl.deleteFramebuffer(texture._framebuffer);
  4832. }
  4833. if (texture._depthBuffer) {
  4834. gl.deleteRenderbuffer(texture._depthBuffer);
  4835. }
  4836. gl.deleteTexture(texture);
  4837. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  4838. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4839. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4840. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  4841. this._activeTexturesCache[channel] = null;
  4842. }
  4843. var index = this._loadedTexturesCache.indexOf(texture);
  4844. if (index !== -1) {
  4845. this._loadedTexturesCache.splice(index, 1);
  4846. }
  4847. };
  4848. Engine.prototype.bindSamplers = function (effect) {
  4849. this._gl.useProgram(effect.getProgram());
  4850. var samplers = effect.getSamplers();
  4851. for (var index = 0; index < samplers.length; index++) {
  4852. var uniform = effect.getUniform(samplers[index]);
  4853. this._gl.uniform1i(uniform, index);
  4854. }
  4855. this._currentEffect = null;
  4856. };
  4857. Engine.prototype._bindTexture = function (channel, texture) {
  4858. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4859. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4860. this._activeTexturesCache[channel] = null;
  4861. };
  4862. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  4863. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  4864. };
  4865. Engine.prototype.setTexture = function (channel, texture) {
  4866. if (channel < 0) {
  4867. return;
  4868. }
  4869. // Not ready?
  4870. if (!texture || !texture.isReady()) {
  4871. if (this._activeTexturesCache[channel] != null) {
  4872. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4873. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4874. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  4875. this._activeTexturesCache[channel] = null;
  4876. }
  4877. return;
  4878. }
  4879. // Video
  4880. if (texture instanceof BABYLON.VideoTexture) {
  4881. if (texture.update()) {
  4882. this._activeTexturesCache[channel] = null;
  4883. }
  4884. }
  4885. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  4886. texture.delayLoad();
  4887. return;
  4888. }
  4889. if (this._activeTexturesCache[channel] === texture) {
  4890. return;
  4891. }
  4892. this._activeTexturesCache[channel] = texture;
  4893. var internalTexture = texture.getInternalTexture();
  4894. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4895. if (internalTexture.isCube) {
  4896. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  4897. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  4898. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  4899. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  4900. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  4901. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  4902. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  4903. }
  4904. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  4905. }
  4906. else {
  4907. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  4908. if (internalTexture._cachedWrapU !== texture.wrapU) {
  4909. internalTexture._cachedWrapU = texture.wrapU;
  4910. switch (texture.wrapU) {
  4911. case BABYLON.Texture.WRAP_ADDRESSMODE:
  4912. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  4913. break;
  4914. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  4915. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  4916. break;
  4917. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  4918. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  4919. break;
  4920. }
  4921. }
  4922. if (internalTexture._cachedWrapV !== texture.wrapV) {
  4923. internalTexture._cachedWrapV = texture.wrapV;
  4924. switch (texture.wrapV) {
  4925. case BABYLON.Texture.WRAP_ADDRESSMODE:
  4926. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  4927. break;
  4928. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  4929. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  4930. break;
  4931. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  4932. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  4933. break;
  4934. }
  4935. }
  4936. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  4937. }
  4938. };
  4939. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  4940. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  4941. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== texture.anisotropicFilteringLevel) {
  4942. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropicFilteringLevel, this._caps.maxAnisotropy));
  4943. texture._cachedAnisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  4944. }
  4945. };
  4946. Engine.prototype.readPixels = function (x, y, width, height) {
  4947. var data = new Uint8Array(height * width * 4);
  4948. this._gl.readPixels(0, 0, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  4949. return data;
  4950. };
  4951. // Dispose
  4952. Engine.prototype.dispose = function () {
  4953. this.hideLoadingUI();
  4954. this.stopRenderLoop();
  4955. while (this.scenes.length) {
  4956. this.scenes[0].dispose();
  4957. }
  4958. // Release audio engine
  4959. Engine.audioEngine.dispose();
  4960. for (var name in this._compiledEffects) {
  4961. this._gl.deleteProgram(this._compiledEffects[name]._program);
  4962. }
  4963. for (var i in this._vertexAttribArrays) {
  4964. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  4965. continue;
  4966. }
  4967. this._gl.disableVertexAttribArray(i);
  4968. }
  4969. // Events
  4970. window.removeEventListener("blur", this._onBlur);
  4971. window.removeEventListener("focus", this._onFocus);
  4972. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  4973. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  4974. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  4975. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  4976. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  4977. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  4978. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  4979. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  4980. };
  4981. // Loading screen
  4982. Engine.prototype.displayLoadingUI = function () {
  4983. var _this = this;
  4984. this._loadingDiv = document.createElement("div");
  4985. this._loadingDiv.style.opacity = "0";
  4986. this._loadingDiv.style.transition = "opacity 1.5s ease";
  4987. // Loading text
  4988. this._loadingTextDiv = document.createElement("div");
  4989. this._loadingTextDiv.style.position = "absolute";
  4990. this._loadingTextDiv.style.left = "0";
  4991. this._loadingTextDiv.style.top = "50%";
  4992. this._loadingTextDiv.style.marginTop = "80px";
  4993. this._loadingTextDiv.style.width = "100%";
  4994. this._loadingTextDiv.style.height = "20px";
  4995. this._loadingTextDiv.style.fontFamily = "Arial";
  4996. this._loadingTextDiv.style.fontSize = "14px";
  4997. this._loadingTextDiv.style.color = "white";
  4998. this._loadingTextDiv.style.textAlign = "center";
  4999. this._loadingTextDiv.innerHTML = "Loading";
  5000. this._loadingDiv.appendChild(this._loadingTextDiv);
  5001. // Loading img
  5002. var imgBack = new Image();
  5003. 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==";
  5004. imgBack.style.position = "absolute";
  5005. imgBack.style.left = "50%";
  5006. imgBack.style.top = "50%";
  5007. imgBack.style.marginLeft = "-50px";
  5008. imgBack.style.marginTop = "-50px";
  5009. imgBack.style.transition = "transform 1.0s ease";
  5010. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  5011. var deg = 360;
  5012. var onTransitionEnd = function () {
  5013. deg += 360;
  5014. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  5015. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  5016. };
  5017. imgBack.addEventListener("transitionend", onTransitionEnd);
  5018. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  5019. this._loadingDiv.appendChild(imgBack);
  5020. // front image
  5021. var imgFront = new Image();
  5022. 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=";
  5023. imgFront.style.position = "absolute";
  5024. imgFront.style.left = "50%";
  5025. imgFront.style.top = "50%";
  5026. imgFront.style.marginLeft = "-50px";
  5027. imgFront.style.marginTop = "-50px";
  5028. this._loadingDiv.appendChild(imgFront);
  5029. // Resize
  5030. this._resizeLoadingUI = function () {
  5031. var canvasRect = _this.getRenderingCanvasClientRect();
  5032. _this._loadingDiv.style.position = "absolute";
  5033. _this._loadingDiv.style.left = canvasRect.left + "px";
  5034. _this._loadingDiv.style.top = canvasRect.top + "px";
  5035. _this._loadingDiv.style.width = canvasRect.width + "px";
  5036. _this._loadingDiv.style.height = canvasRect.height + "px";
  5037. };
  5038. this._resizeLoadingUI();
  5039. window.addEventListener("resize", this._resizeLoadingUI);
  5040. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  5041. document.body.appendChild(this._loadingDiv);
  5042. setTimeout(function () {
  5043. _this._loadingDiv.style.opacity = "1";
  5044. imgBack.style.transform = "rotateZ(360deg)";
  5045. imgBack.style.webkitTransform = "rotateZ(360deg)";
  5046. }, 0);
  5047. };
  5048. Object.defineProperty(Engine.prototype, "loadingUIText", {
  5049. set: function (text) {
  5050. if (!this._loadingDiv) {
  5051. return;
  5052. }
  5053. this._loadingTextDiv.innerHTML = text;
  5054. },
  5055. enumerable: true,
  5056. configurable: true
  5057. });
  5058. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  5059. get: function () {
  5060. return this._loadingDivBackgroundColor;
  5061. },
  5062. set: function (color) {
  5063. this._loadingDivBackgroundColor = color;
  5064. if (!this._loadingDiv) {
  5065. return;
  5066. }
  5067. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  5068. },
  5069. enumerable: true,
  5070. configurable: true
  5071. });
  5072. Engine.prototype.hideLoadingUI = function () {
  5073. var _this = this;
  5074. if (!this._loadingDiv) {
  5075. return;
  5076. }
  5077. var onTransitionEnd = function () {
  5078. if (!_this._loadingDiv) {
  5079. return;
  5080. }
  5081. document.body.removeChild(_this._loadingDiv);
  5082. window.removeEventListener("resize", _this._resizeLoadingUI);
  5083. _this._loadingDiv = null;
  5084. };
  5085. this._loadingDiv.style.opacity = "0";
  5086. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  5087. };
  5088. // FPS
  5089. Engine.prototype.getFps = function () {
  5090. return this.fps;
  5091. };
  5092. Engine.prototype.getDeltaTime = function () {
  5093. return this.deltaTime;
  5094. };
  5095. Engine.prototype._measureFps = function () {
  5096. this.previousFramesDuration.push(BABYLON.Tools.Now);
  5097. var length = this.previousFramesDuration.length;
  5098. if (length >= 2) {
  5099. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  5100. }
  5101. if (length >= this.fpsRange) {
  5102. if (length > this.fpsRange) {
  5103. this.previousFramesDuration.splice(0, 1);
  5104. length = this.previousFramesDuration.length;
  5105. }
  5106. var sum = 0;
  5107. for (var id = 0; id < length - 1; id++) {
  5108. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  5109. }
  5110. this.fps = 1000.0 / (sum / (length - 1));
  5111. }
  5112. };
  5113. // Statics
  5114. Engine.isSupported = function () {
  5115. try {
  5116. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  5117. if (navigator.isCocoonJS) {
  5118. return true;
  5119. }
  5120. var tempcanvas = document.createElement("canvas");
  5121. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  5122. return gl != null && !!window.WebGLRenderingContext;
  5123. }
  5124. catch (e) {
  5125. return false;
  5126. }
  5127. };
  5128. // Const statics
  5129. Engine._ALPHA_DISABLE = 0;
  5130. Engine._ALPHA_ADD = 1;
  5131. Engine._ALPHA_COMBINE = 2;
  5132. Engine._DELAYLOADSTATE_NONE = 0;
  5133. Engine._DELAYLOADSTATE_LOADED = 1;
  5134. Engine._DELAYLOADSTATE_LOADING = 2;
  5135. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  5136. Engine._TEXTUREFORMAT_ALPHA = 0;
  5137. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  5138. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  5139. Engine._TEXTUREFORMAT_RGB = 4;
  5140. Engine._TEXTUREFORMAT_RGBA = 4;
  5141. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  5142. Engine._TEXTURETYPE_FLOAT = 1;
  5143. // Updatable statics so stick with vars here
  5144. Engine.Epsilon = 0.001;
  5145. Engine.CollisionsEpsilon = 0.001;
  5146. Engine.ShadersRepository = "Babylon/Shaders/";
  5147. return Engine;
  5148. })();
  5149. BABYLON.Engine = Engine;
  5150. })(BABYLON || (BABYLON = {}));
  5151. //# sourceMappingURL=babylon.engine.js.mapvar BABYLON;
  5152. (function (BABYLON) {
  5153. /**
  5154. * Node is the basic class for all scene objects (Mesh, Light Camera).
  5155. */
  5156. var Node = (function () {
  5157. /**
  5158. * @constructor
  5159. * @param {string} name - the name and id to be given to this node
  5160. * @param {BABYLON.Scene} the scene this node will be added to
  5161. */
  5162. function Node(name, scene) {
  5163. this.state = "";
  5164. this.animations = new Array();
  5165. this._childrenFlag = -1;
  5166. this._isEnabled = true;
  5167. this._isReady = true;
  5168. this._currentRenderId = -1;
  5169. this.name = name;
  5170. this.id = name;
  5171. this._scene = scene;
  5172. this._initCache();
  5173. }
  5174. Node.prototype.getScene = function () {
  5175. return this._scene;
  5176. };
  5177. Node.prototype.getEngine = function () {
  5178. return this._scene.getEngine();
  5179. };
  5180. // override it in derived class
  5181. Node.prototype.getWorldMatrix = function () {
  5182. return BABYLON.Matrix.Identity();
  5183. };
  5184. // override it in derived class if you add new variables to the cache
  5185. // and call the parent class method
  5186. Node.prototype._initCache = function () {
  5187. this._cache = {};
  5188. this._cache.parent = undefined;
  5189. };
  5190. Node.prototype.updateCache = function (force) {
  5191. if (!force && this.isSynchronized())
  5192. return;
  5193. this._cache.parent = this.parent;
  5194. this._updateCache();
  5195. };
  5196. // override it in derived class if you add new variables to the cache
  5197. // and call the parent class method if !ignoreParentClass
  5198. Node.prototype._updateCache = function (ignoreParentClass) {
  5199. };
  5200. // override it in derived class if you add new variables to the cache
  5201. Node.prototype._isSynchronized = function () {
  5202. return true;
  5203. };
  5204. Node.prototype.isSynchronizedWithParent = function () {
  5205. return this.parent ? this.parent._currentRenderId <= this._currentRenderId : true;
  5206. };
  5207. Node.prototype.isSynchronized = function (updateCache) {
  5208. var check = this.hasNewParent();
  5209. check = check || !this.isSynchronizedWithParent();
  5210. check = check || !this._isSynchronized();
  5211. if (updateCache)
  5212. this.updateCache(true);
  5213. return !check;
  5214. };
  5215. Node.prototype.hasNewParent = function (update) {
  5216. if (this._cache.parent === this.parent)
  5217. return false;
  5218. if (update)
  5219. this._cache.parent = this.parent;
  5220. return true;
  5221. };
  5222. /**
  5223. * Is this node ready to be used/rendered
  5224. * @return {boolean} is it ready
  5225. */
  5226. Node.prototype.isReady = function () {
  5227. return this._isReady;
  5228. };
  5229. /**
  5230. * Is this node enabled.
  5231. * If the node has a parent and is enabled, the parent will be inspected as well.
  5232. * @return {boolean} whether this node (and its parent) is enabled.
  5233. * @see setEnabled
  5234. */
  5235. Node.prototype.isEnabled = function () {
  5236. if (!this._isEnabled) {
  5237. return false;
  5238. }
  5239. if (this.parent) {
  5240. return this.parent.isEnabled();
  5241. }
  5242. return true;
  5243. };
  5244. /**
  5245. * Set the enabled state of this node.
  5246. * @param {boolean} value - the new enabled state
  5247. * @see isEnabled
  5248. */
  5249. Node.prototype.setEnabled = function (value) {
  5250. this._isEnabled = value;
  5251. };
  5252. /**
  5253. * Is this node a descendant of the given node.
  5254. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  5255. * @param {BABYLON.Node} ancestor - The parent node to inspect
  5256. * @see parent
  5257. */
  5258. Node.prototype.isDescendantOf = function (ancestor) {
  5259. if (this.parent) {
  5260. if (this.parent === ancestor) {
  5261. return true;
  5262. }
  5263. return this.parent.isDescendantOf(ancestor);
  5264. }
  5265. return false;
  5266. };
  5267. Node.prototype._getDescendants = function (list, results) {
  5268. for (var index = 0; index < list.length; index++) {
  5269. var item = list[index];
  5270. if (item.isDescendantOf(this)) {
  5271. results.push(item);
  5272. }
  5273. }
  5274. };
  5275. /**
  5276. * Will return all nodes that have this node as parent.
  5277. * @return {BABYLON.Node[]} all children nodes of all types.
  5278. */
  5279. Node.prototype.getDescendants = function () {
  5280. var results = [];
  5281. this._getDescendants(this._scene.meshes, results);
  5282. this._getDescendants(this._scene.lights, results);
  5283. this._getDescendants(this._scene.cameras, results);
  5284. return results;
  5285. };
  5286. Node.prototype._setReady = function (state) {
  5287. if (state == this._isReady) {
  5288. return;
  5289. }
  5290. if (!state) {
  5291. this._isReady = false;
  5292. return;
  5293. }
  5294. this._isReady = true;
  5295. if (this.onReady) {
  5296. this.onReady(this);
  5297. }
  5298. };
  5299. return Node;
  5300. })();
  5301. BABYLON.Node = Node;
  5302. })(BABYLON || (BABYLON = {}));
  5303. //# sourceMappingURL=babylon.node.js.mapvar BABYLON;
  5304. (function (BABYLON) {
  5305. var BoundingSphere = (function () {
  5306. function BoundingSphere(minimum, maximum) {
  5307. this.minimum = minimum;
  5308. this.maximum = maximum;
  5309. this._tempRadiusVector = BABYLON.Vector3.Zero();
  5310. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  5311. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  5312. this.radius = distance * 0.5;
  5313. this.centerWorld = BABYLON.Vector3.Zero();
  5314. this._update(BABYLON.Matrix.Identity());
  5315. }
  5316. // Methods
  5317. BoundingSphere.prototype._update = function (world) {
  5318. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  5319. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  5320. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  5321. };
  5322. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  5323. for (var i = 0; i < 6; i++) {
  5324. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  5325. return false;
  5326. }
  5327. return true;
  5328. };
  5329. BoundingSphere.prototype.intersectsPoint = function (point) {
  5330. var x = this.centerWorld.x - point.x;
  5331. var y = this.centerWorld.y - point.y;
  5332. var z = this.centerWorld.z - point.z;
  5333. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  5334. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  5335. return false;
  5336. return true;
  5337. };
  5338. // Statics
  5339. BoundingSphere.Intersects = function (sphere0, sphere1) {
  5340. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  5341. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  5342. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  5343. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  5344. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  5345. return false;
  5346. return true;
  5347. };
  5348. return BoundingSphere;
  5349. })();
  5350. BABYLON.BoundingSphere = BoundingSphere;
  5351. })(BABYLON || (BABYLON = {}));
  5352. //# sourceMappingURL=babylon.boundingSphere.js.mapvar BABYLON;
  5353. (function (BABYLON) {
  5354. var BoundingBox = (function () {
  5355. function BoundingBox(minimum, maximum) {
  5356. this.minimum = minimum;
  5357. this.maximum = maximum;
  5358. this.vectors = new Array();
  5359. this.vectorsWorld = new Array();
  5360. // Bounding vectors
  5361. this.vectors.push(this.minimum.clone());
  5362. this.vectors.push(this.maximum.clone());
  5363. this.vectors.push(this.minimum.clone());
  5364. this.vectors[2].x = this.maximum.x;
  5365. this.vectors.push(this.minimum.clone());
  5366. this.vectors[3].y = this.maximum.y;
  5367. this.vectors.push(this.minimum.clone());
  5368. this.vectors[4].z = this.maximum.z;
  5369. this.vectors.push(this.maximum.clone());
  5370. this.vectors[5].z = this.minimum.z;
  5371. this.vectors.push(this.maximum.clone());
  5372. this.vectors[6].x = this.minimum.x;
  5373. this.vectors.push(this.maximum.clone());
  5374. this.vectors[7].y = this.minimum.y;
  5375. // OBB
  5376. this.center = this.maximum.add(this.minimum).scale(0.5);
  5377. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  5378. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  5379. for (var index = 0; index < this.vectors.length; index++) {
  5380. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  5381. }
  5382. this.minimumWorld = BABYLON.Vector3.Zero();
  5383. this.maximumWorld = BABYLON.Vector3.Zero();
  5384. this._update(BABYLON.Matrix.Identity());
  5385. }
  5386. // Methods
  5387. BoundingBox.prototype.getWorldMatrix = function () {
  5388. return this._worldMatrix;
  5389. };
  5390. BoundingBox.prototype._update = function (world) {
  5391. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  5392. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  5393. for (var index = 0; index < this.vectors.length; index++) {
  5394. var v = this.vectorsWorld[index];
  5395. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  5396. if (v.x < this.minimumWorld.x)
  5397. this.minimumWorld.x = v.x;
  5398. if (v.y < this.minimumWorld.y)
  5399. this.minimumWorld.y = v.y;
  5400. if (v.z < this.minimumWorld.z)
  5401. this.minimumWorld.z = v.z;
  5402. if (v.x > this.maximumWorld.x)
  5403. this.maximumWorld.x = v.x;
  5404. if (v.y > this.maximumWorld.y)
  5405. this.maximumWorld.y = v.y;
  5406. if (v.z > this.maximumWorld.z)
  5407. this.maximumWorld.z = v.z;
  5408. }
  5409. // OBB
  5410. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  5411. this.center.scaleInPlace(0.5);
  5412. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  5413. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  5414. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  5415. this._worldMatrix = world;
  5416. };
  5417. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  5418. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  5419. };
  5420. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  5421. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  5422. };
  5423. BoundingBox.prototype.intersectsPoint = function (point) {
  5424. var delta = BABYLON.Engine.Epsilon;
  5425. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  5426. return false;
  5427. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  5428. return false;
  5429. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  5430. return false;
  5431. return true;
  5432. };
  5433. BoundingBox.prototype.intersectsSphere = function (sphere) {
  5434. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  5435. };
  5436. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  5437. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  5438. return false;
  5439. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  5440. return false;
  5441. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  5442. return false;
  5443. return true;
  5444. };
  5445. // Statics
  5446. BoundingBox.Intersects = function (box0, box1) {
  5447. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  5448. return false;
  5449. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  5450. return false;
  5451. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  5452. return false;
  5453. return true;
  5454. };
  5455. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  5456. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  5457. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  5458. return (num <= (sphereRadius * sphereRadius));
  5459. };
  5460. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  5461. for (var p = 0; p < 6; p++) {
  5462. for (var i = 0; i < 8; i++) {
  5463. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  5464. return false;
  5465. }
  5466. }
  5467. }
  5468. return true;
  5469. };
  5470. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  5471. for (var p = 0; p < 6; p++) {
  5472. var inCount = 8;
  5473. for (var i = 0; i < 8; i++) {
  5474. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  5475. --inCount;
  5476. }
  5477. else {
  5478. break;
  5479. }
  5480. }
  5481. if (inCount === 0)
  5482. return false;
  5483. }
  5484. return true;
  5485. };
  5486. return BoundingBox;
  5487. })();
  5488. BABYLON.BoundingBox = BoundingBox;
  5489. })(BABYLON || (BABYLON = {}));
  5490. //# sourceMappingURL=babylon.boundingBox.js.mapvar BABYLON;
  5491. (function (BABYLON) {
  5492. var computeBoxExtents = function (axis, box) {
  5493. var p = BABYLON.Vector3.Dot(box.center, axis);
  5494. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  5495. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  5496. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  5497. var r = r0 + r1 + r2;
  5498. return {
  5499. min: p - r,
  5500. max: p + r
  5501. };
  5502. };
  5503. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  5504. var axisOverlap = function (axis, box0, box1) {
  5505. var result0 = computeBoxExtents(axis, box0);
  5506. var result1 = computeBoxExtents(axis, box1);
  5507. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  5508. };
  5509. var BoundingInfo = (function () {
  5510. function BoundingInfo(minimum, maximum) {
  5511. this.minimum = minimum;
  5512. this.maximum = maximum;
  5513. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  5514. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  5515. }
  5516. // Methods
  5517. BoundingInfo.prototype._update = function (world) {
  5518. this.boundingBox._update(world);
  5519. this.boundingSphere._update(world);
  5520. };
  5521. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  5522. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  5523. return false;
  5524. return this.boundingBox.isInFrustum(frustumPlanes);
  5525. };
  5526. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  5527. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  5528. };
  5529. BoundingInfo.prototype._checkCollision = function (collider) {
  5530. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  5531. };
  5532. BoundingInfo.prototype.intersectsPoint = function (point) {
  5533. if (!this.boundingSphere.centerWorld) {
  5534. return false;
  5535. }
  5536. if (!this.boundingSphere.intersectsPoint(point)) {
  5537. return false;
  5538. }
  5539. if (!this.boundingBox.intersectsPoint(point)) {
  5540. return false;
  5541. }
  5542. return true;
  5543. };
  5544. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  5545. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  5546. return false;
  5547. }
  5548. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  5549. return false;
  5550. }
  5551. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  5552. return false;
  5553. }
  5554. if (!precise) {
  5555. return true;
  5556. }
  5557. var box0 = this.boundingBox;
  5558. var box1 = boundingInfo.boundingBox;
  5559. if (!axisOverlap(box0.directions[0], box0, box1))
  5560. return false;
  5561. if (!axisOverlap(box0.directions[1], box0, box1))
  5562. return false;
  5563. if (!axisOverlap(box0.directions[2], box0, box1))
  5564. return false;
  5565. if (!axisOverlap(box1.directions[0], box0, box1))
  5566. return false;
  5567. if (!axisOverlap(box1.directions[1], box0, box1))
  5568. return false;
  5569. if (!axisOverlap(box1.directions[2], box0, box1))
  5570. return false;
  5571. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  5572. return false;
  5573. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  5574. return false;
  5575. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  5576. return false;
  5577. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  5578. return false;
  5579. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  5580. return false;
  5581. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  5582. return false;
  5583. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  5584. return false;
  5585. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  5586. return false;
  5587. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  5588. return false;
  5589. return true;
  5590. };
  5591. return BoundingInfo;
  5592. })();
  5593. BABYLON.BoundingInfo = BoundingInfo;
  5594. })(BABYLON || (BABYLON = {}));
  5595. //# sourceMappingURL=babylon.boundingInfo.js.map
  5596. var BABYLON;
  5597. (function (BABYLON) {
  5598. var Light = (function (_super) {
  5599. __extends(Light, _super);
  5600. function Light(name, scene) {
  5601. _super.call(this, name, scene);
  5602. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  5603. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  5604. this.intensity = 1.0;
  5605. this.range = Number.MAX_VALUE;
  5606. this.includedOnlyMeshes = new Array();
  5607. this.excludedMeshes = new Array();
  5608. this._excludedMeshesIds = new Array();
  5609. this._includedOnlyMeshesIds = new Array();
  5610. scene.lights.push(this);
  5611. }
  5612. Light.prototype.getShadowGenerator = function () {
  5613. return this._shadowGenerator;
  5614. };
  5615. Light.prototype.getAbsolutePosition = function () {
  5616. return BABYLON.Vector3.Zero();
  5617. };
  5618. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  5619. };
  5620. Light.prototype._getWorldMatrix = function () {
  5621. return BABYLON.Matrix.Identity();
  5622. };
  5623. Light.prototype.canAffectMesh = function (mesh) {
  5624. if (!mesh) {
  5625. return true;
  5626. }
  5627. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  5628. return false;
  5629. }
  5630. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  5631. return false;
  5632. }
  5633. return true;
  5634. };
  5635. Light.prototype.getWorldMatrix = function () {
  5636. this._currentRenderId = this.getScene().getRenderId();
  5637. var worldMatrix = this._getWorldMatrix();
  5638. if (this.parent && this.parent.getWorldMatrix) {
  5639. if (!this._parentedWorldMatrix) {
  5640. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  5641. }
  5642. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  5643. return this._parentedWorldMatrix;
  5644. }
  5645. return worldMatrix;
  5646. };
  5647. Light.prototype.dispose = function () {
  5648. if (this._shadowGenerator) {
  5649. this._shadowGenerator.dispose();
  5650. this._shadowGenerator = null;
  5651. }
  5652. // Remove from scene
  5653. var index = this.getScene().lights.indexOf(this);
  5654. this.getScene().lights.splice(index, 1);
  5655. };
  5656. return Light;
  5657. })(BABYLON.Node);
  5658. BABYLON.Light = Light;
  5659. })(BABYLON || (BABYLON = {}));
  5660. //# sourceMappingURL=babylon.light.js.map
  5661. var BABYLON;
  5662. (function (BABYLON) {
  5663. var PointLight = (function (_super) {
  5664. __extends(PointLight, _super);
  5665. function PointLight(name, position, scene) {
  5666. _super.call(this, name, scene);
  5667. this.position = position;
  5668. }
  5669. PointLight.prototype.getAbsolutePosition = function () {
  5670. return this._transformedPosition ? this._transformedPosition : this.position;
  5671. };
  5672. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  5673. if (this.parent && this.parent.getWorldMatrix) {
  5674. if (!this._transformedPosition) {
  5675. this._transformedPosition = BABYLON.Vector3.Zero();
  5676. }
  5677. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  5678. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, 0);
  5679. return;
  5680. }
  5681. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  5682. };
  5683. PointLight.prototype.getShadowGenerator = function () {
  5684. return null;
  5685. };
  5686. PointLight.prototype._getWorldMatrix = function () {
  5687. if (!this._worldMatrix) {
  5688. this._worldMatrix = BABYLON.Matrix.Identity();
  5689. }
  5690. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  5691. return this._worldMatrix;
  5692. };
  5693. return PointLight;
  5694. })(BABYLON.Light);
  5695. BABYLON.PointLight = PointLight;
  5696. })(BABYLON || (BABYLON = {}));
  5697. //# sourceMappingURL=babylon.pointLight.js.map
  5698. var BABYLON;
  5699. (function (BABYLON) {
  5700. var SpotLight = (function (_super) {
  5701. __extends(SpotLight, _super);
  5702. function SpotLight(name, position, direction, angle, exponent, scene) {
  5703. _super.call(this, name, scene);
  5704. this.position = position;
  5705. this.direction = direction;
  5706. this.angle = angle;
  5707. this.exponent = exponent;
  5708. }
  5709. SpotLight.prototype.getAbsolutePosition = function () {
  5710. return this.transformedPosition ? this.transformedPosition : this.position;
  5711. };
  5712. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList, useVSM) {
  5713. var activeCamera = this.getScene().activeCamera;
  5714. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  5715. };
  5716. SpotLight.prototype.getVSMOffset = function () {
  5717. return 0.2;
  5718. };
  5719. SpotLight.prototype.supportsVSM = function () {
  5720. return true;
  5721. };
  5722. SpotLight.prototype.needRefreshPerFrame = function () {
  5723. return false;
  5724. };
  5725. SpotLight.prototype.setDirectionToTarget = function (target) {
  5726. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  5727. return this.direction;
  5728. };
  5729. SpotLight.prototype.computeTransformedPosition = function () {
  5730. if (this.parent && this.parent.getWorldMatrix) {
  5731. if (!this.transformedPosition) {
  5732. this.transformedPosition = BABYLON.Vector3.Zero();
  5733. }
  5734. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  5735. return true;
  5736. }
  5737. return false;
  5738. };
  5739. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  5740. var normalizeDirection;
  5741. if (this.parent && this.parent.getWorldMatrix) {
  5742. if (!this._transformedDirection) {
  5743. this._transformedDirection = BABYLON.Vector3.Zero();
  5744. }
  5745. this.computeTransformedPosition();
  5746. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  5747. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  5748. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  5749. }
  5750. else {
  5751. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  5752. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  5753. }
  5754. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  5755. };
  5756. SpotLight.prototype._getWorldMatrix = function () {
  5757. if (!this._worldMatrix) {
  5758. this._worldMatrix = BABYLON.Matrix.Identity();
  5759. }
  5760. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  5761. return this._worldMatrix;
  5762. };
  5763. return SpotLight;
  5764. })(BABYLON.Light);
  5765. BABYLON.SpotLight = SpotLight;
  5766. })(BABYLON || (BABYLON = {}));
  5767. //# sourceMappingURL=babylon.spotLight.js.map
  5768. var BABYLON;
  5769. (function (BABYLON) {
  5770. var DirectionalLight = (function (_super) {
  5771. __extends(DirectionalLight, _super);
  5772. function DirectionalLight(name, direction, scene) {
  5773. _super.call(this, name, scene);
  5774. this.direction = direction;
  5775. this.shadowOrthoScale = 1.1;
  5776. this.shadowOrthoDepthScale = 3;
  5777. this.position = direction.scale(-1);
  5778. }
  5779. DirectionalLight.prototype.getAbsolutePosition = function () {
  5780. return this.transformedPosition ? this.transformedPosition : this.position;
  5781. };
  5782. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  5783. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  5784. return this.direction;
  5785. };
  5786. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList, useVSM) {
  5787. var orthoLeft = Number.MAX_VALUE;
  5788. var orthoRight = Number.MIN_VALUE;
  5789. var orthoTop = Number.MIN_VALUE;
  5790. var orthoBottom = Number.MAX_VALUE;
  5791. var orthoNear = Number.MAX_VALUE;
  5792. var orthoFar = Number.MIN_VALUE;
  5793. var tempVector3 = BABYLON.Vector3.Zero();
  5794. var activeCamera = this.getScene().activeCamera;
  5795. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  5796. var boundingBox = renderList[meshIndex].getBoundingInfo().boundingBox;
  5797. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  5798. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  5799. if (tempVector3.x < orthoLeft)
  5800. orthoLeft = tempVector3.x;
  5801. if (tempVector3.y < orthoBottom)
  5802. orthoBottom = tempVector3.y;
  5803. if (tempVector3.x > orthoRight)
  5804. orthoRight = tempVector3.x;
  5805. if (tempVector3.y > orthoTop)
  5806. orthoTop = tempVector3.y;
  5807. if (tempVector3.z < orthoNear)
  5808. orthoNear = tempVector3.z;
  5809. if (tempVector3.z > orthoFar)
  5810. orthoFar = tempVector3.z;
  5811. }
  5812. }
  5813. var orthoWidth = Math.max(Math.abs(orthoRight), Math.abs(orthoLeft)) * this.shadowOrthoScale;
  5814. var orthoHeight = Math.max(Math.abs(orthoTop), Math.abs(orthoBottom)) * this.shadowOrthoScale;
  5815. var orthoDepth = Math.max(Math.abs(orthoNear), Math.abs(orthoFar)) * this.shadowOrthoDepthScale;
  5816. BABYLON.Matrix.OrthoOffCenterLHToRef(-orthoWidth, orthoWidth, -orthoHeight, orthoHeight, useVSM ? -orthoDepth : activeCamera.minZ, orthoDepth, matrix);
  5817. };
  5818. DirectionalLight.prototype.getVSMOffset = function () {
  5819. return 0.55;
  5820. };
  5821. DirectionalLight.prototype.supportsVSM = function () {
  5822. return true;
  5823. };
  5824. DirectionalLight.prototype.needRefreshPerFrame = function () {
  5825. return true;
  5826. };
  5827. DirectionalLight.prototype.computeTransformedPosition = function () {
  5828. if (this.parent && this.parent.getWorldMatrix) {
  5829. if (!this.transformedPosition) {
  5830. this.transformedPosition = BABYLON.Vector3.Zero();
  5831. }
  5832. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  5833. return true;
  5834. }
  5835. return false;
  5836. };
  5837. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  5838. if (this.parent && this.parent.getWorldMatrix) {
  5839. if (!this._transformedDirection) {
  5840. this._transformedDirection = BABYLON.Vector3.Zero();
  5841. }
  5842. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  5843. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  5844. return;
  5845. }
  5846. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  5847. };
  5848. DirectionalLight.prototype._getWorldMatrix = function () {
  5849. if (!this._worldMatrix) {
  5850. this._worldMatrix = BABYLON.Matrix.Identity();
  5851. }
  5852. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  5853. return this._worldMatrix;
  5854. };
  5855. return DirectionalLight;
  5856. })(BABYLON.Light);
  5857. BABYLON.DirectionalLight = DirectionalLight;
  5858. })(BABYLON || (BABYLON = {}));
  5859. //# sourceMappingURL=babylon.directionalLight.js.mapvar BABYLON;
  5860. (function (BABYLON) {
  5861. var ShadowGenerator = (function () {
  5862. function ShadowGenerator(mapSize, light) {
  5863. var _this = this;
  5864. // Members
  5865. this.filter = ShadowGenerator.FILTER_NONE;
  5866. this.blurSize = 2;
  5867. this._darkness = 0;
  5868. this._bias = 0.0001;
  5869. this._transparencyShadow = false;
  5870. this._viewMatrix = BABYLON.Matrix.Zero();
  5871. this._projectionMatrix = BABYLON.Matrix.Zero();
  5872. this._transformMatrix = BABYLON.Matrix.Zero();
  5873. this._worldViewProjection = BABYLON.Matrix.Zero();
  5874. this._light = light;
  5875. this._scene = light.getScene();
  5876. light._shadowGenerator = this;
  5877. // Render target
  5878. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false);
  5879. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  5880. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  5881. this._shadowMap.renderParticles = false;
  5882. this._shadowMap.onAfterUnbind = function () {
  5883. if (_this.filter !== ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP) {
  5884. return;
  5885. }
  5886. if (!_this._shadowMap2) {
  5887. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false);
  5888. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  5889. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  5890. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurSize, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, _this._scene.getEngine());
  5891. _this._downSamplePostprocess.onApply = function (effect) {
  5892. effect.setTexture("textureSampler", _this._shadowMap);
  5893. };
  5894. _this._boxBlurPostprocess = new BABYLON.PostProcess("DepthBoxBlur", "depthBoxBlur", ["screenSize"], [], 1.0 / _this.blurSize, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  5895. _this._boxBlurPostprocess.onApply = function (effect) {
  5896. effect.setFloat2("screenSize", mapSize / _this.blurSize, mapSize / _this.blurSize);
  5897. };
  5898. }
  5899. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  5900. };
  5901. // Custom render function
  5902. var renderSubMesh = function (subMesh) {
  5903. var mesh = subMesh.getRenderingMesh();
  5904. var scene = _this._scene;
  5905. var engine = scene.getEngine();
  5906. // Culling
  5907. engine.setState(subMesh.getMaterial().backFaceCulling);
  5908. // Managing instances
  5909. var batch = mesh._getInstancesRenderList(subMesh._id);
  5910. if (batch.mustReturn) {
  5911. return;
  5912. }
  5913. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  5914. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  5915. engine.enableEffect(_this._effect);
  5916. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  5917. var material = subMesh.getMaterial();
  5918. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  5919. // Alpha test
  5920. if (material && material.needAlphaTesting()) {
  5921. var alphaTexture = material.getAlphaTestTexture();
  5922. _this._effect.setTexture("diffuseSampler", alphaTexture);
  5923. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  5924. }
  5925. // Bones
  5926. if (mesh.useBones) {
  5927. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  5928. }
  5929. // Draw
  5930. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  5931. }
  5932. else {
  5933. // Need to reset refresh rate of the shadowMap
  5934. _this._shadowMap.resetRefreshCounter();
  5935. }
  5936. };
  5937. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  5938. var index;
  5939. for (index = 0; index < opaqueSubMeshes.length; index++) {
  5940. renderSubMesh(opaqueSubMeshes.data[index]);
  5941. }
  5942. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  5943. renderSubMesh(alphaTestSubMeshes.data[index]);
  5944. }
  5945. if (_this._transparencyShadow) {
  5946. for (index = 0; index < transparentSubMeshes.length; index++) {
  5947. renderSubMesh(transparentSubMeshes.data[index]);
  5948. }
  5949. }
  5950. };
  5951. }
  5952. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  5953. // Static
  5954. get: function () {
  5955. return ShadowGenerator._FILTER_NONE;
  5956. },
  5957. enumerable: true,
  5958. configurable: true
  5959. });
  5960. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  5961. get: function () {
  5962. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  5963. },
  5964. enumerable: true,
  5965. configurable: true
  5966. });
  5967. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  5968. get: function () {
  5969. return ShadowGenerator._FILTER_POISSONSAMPLING;
  5970. },
  5971. enumerable: true,
  5972. configurable: true
  5973. });
  5974. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  5975. get: function () {
  5976. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  5977. },
  5978. enumerable: true,
  5979. configurable: true
  5980. });
  5981. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  5982. get: function () {
  5983. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  5984. },
  5985. set: function (value) {
  5986. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  5987. },
  5988. enumerable: true,
  5989. configurable: true
  5990. });
  5991. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  5992. get: function () {
  5993. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  5994. },
  5995. set: function (value) {
  5996. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  5997. },
  5998. enumerable: true,
  5999. configurable: true
  6000. });
  6001. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  6002. get: function () {
  6003. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  6004. },
  6005. set: function (value) {
  6006. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  6007. },
  6008. enumerable: true,
  6009. configurable: true
  6010. });
  6011. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  6012. var defines = [];
  6013. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  6014. defines.push("#define VSM");
  6015. }
  6016. var attribs = [BABYLON.VertexBuffer.PositionKind];
  6017. var mesh = subMesh.getMesh();
  6018. var material = subMesh.getMaterial();
  6019. // Alpha test
  6020. if (material && material.needAlphaTesting()) {
  6021. defines.push("#define ALPHATEST");
  6022. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  6023. attribs.push(BABYLON.VertexBuffer.UVKind);
  6024. defines.push("#define UV1");
  6025. }
  6026. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  6027. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  6028. defines.push("#define UV2");
  6029. }
  6030. }
  6031. // Bones
  6032. if (mesh.useBones) {
  6033. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  6034. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  6035. defines.push("#define BONES");
  6036. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  6037. }
  6038. // Instances
  6039. if (useInstances) {
  6040. defines.push("#define INSTANCES");
  6041. attribs.push("world0");
  6042. attribs.push("world1");
  6043. attribs.push("world2");
  6044. attribs.push("world3");
  6045. }
  6046. // Get correct effect
  6047. var join = defines.join("\n");
  6048. if (this._cachedDefines !== join) {
  6049. this._cachedDefines = join;
  6050. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  6051. }
  6052. return this._effect.isReady();
  6053. };
  6054. ShadowGenerator.prototype.getShadowMap = function () {
  6055. return this._shadowMap;
  6056. };
  6057. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  6058. if (this._shadowMap2) {
  6059. return this._shadowMap2;
  6060. }
  6061. return this._shadowMap;
  6062. };
  6063. ShadowGenerator.prototype.getLight = function () {
  6064. return this._light;
  6065. };
  6066. // Methods
  6067. ShadowGenerator.prototype.getTransformMatrix = function () {
  6068. var scene = this._scene;
  6069. if (this._currentRenderID === scene.getRenderId()) {
  6070. return this._transformMatrix;
  6071. }
  6072. this._currentRenderID = scene.getRenderId();
  6073. var lightPosition = this._light.position;
  6074. var lightDirection = this._light.direction;
  6075. if (this._light.computeTransformedPosition()) {
  6076. lightPosition = this._light.transformedPosition;
  6077. }
  6078. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !lightDirection.equals(this._cachedDirection)) {
  6079. this._cachedPosition = lightPosition.clone();
  6080. this._cachedDirection = lightDirection.clone();
  6081. BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  6082. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList, this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP || this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP);
  6083. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  6084. }
  6085. return this._transformMatrix;
  6086. };
  6087. ShadowGenerator.prototype.getDarkness = function () {
  6088. return this._darkness;
  6089. };
  6090. ShadowGenerator.prototype.setDarkness = function (darkness) {
  6091. if (darkness >= 1.0)
  6092. this._darkness = 1.0;
  6093. else if (darkness <= 0.0)
  6094. this._darkness = 0.0;
  6095. else
  6096. this._darkness = darkness;
  6097. };
  6098. ShadowGenerator.prototype.getBias = function () {
  6099. return this._bias;
  6100. };
  6101. ShadowGenerator.prototype.setBias = function (bias) {
  6102. this._bias = bias;
  6103. };
  6104. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  6105. this._transparencyShadow = hasShadow;
  6106. };
  6107. ShadowGenerator.prototype.dispose = function () {
  6108. this._shadowMap.dispose();
  6109. if (this._shadowMap2) {
  6110. this._shadowMap2.dispose();
  6111. }
  6112. if (this._downSamplePostprocess) {
  6113. this._downSamplePostprocess.dispose();
  6114. }
  6115. if (this._boxBlurPostprocess) {
  6116. this._boxBlurPostprocess.dispose();
  6117. }
  6118. };
  6119. ShadowGenerator._FILTER_NONE = 0;
  6120. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  6121. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  6122. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  6123. return ShadowGenerator;
  6124. })();
  6125. BABYLON.ShadowGenerator = ShadowGenerator;
  6126. })(BABYLON || (BABYLON = {}));
  6127. //# sourceMappingURL=babylon.shadowGenerator.js.map
  6128. var BABYLON;
  6129. (function (BABYLON) {
  6130. var HemisphericLight = (function (_super) {
  6131. __extends(HemisphericLight, _super);
  6132. function HemisphericLight(name, direction, scene) {
  6133. _super.call(this, name, scene);
  6134. this.direction = direction;
  6135. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  6136. }
  6137. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  6138. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  6139. return this.direction;
  6140. };
  6141. HemisphericLight.prototype.getShadowGenerator = function () {
  6142. return null;
  6143. };
  6144. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  6145. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  6146. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  6147. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  6148. };
  6149. HemisphericLight.prototype._getWorldMatrix = function () {
  6150. if (!this._worldMatrix) {
  6151. this._worldMatrix = BABYLON.Matrix.Identity();
  6152. }
  6153. return this._worldMatrix;
  6154. };
  6155. return HemisphericLight;
  6156. })(BABYLON.Light);
  6157. BABYLON.HemisphericLight = HemisphericLight;
  6158. })(BABYLON || (BABYLON = {}));
  6159. //# sourceMappingURL=babylon.hemisphericLight.js.mapvar BABYLON;
  6160. (function (BABYLON) {
  6161. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  6162. if (boxMin.x > sphereCenter.x + sphereRadius)
  6163. return false;
  6164. if (sphereCenter.x - sphereRadius > boxMax.x)
  6165. return false;
  6166. if (boxMin.y > sphereCenter.y + sphereRadius)
  6167. return false;
  6168. if (sphereCenter.y - sphereRadius > boxMax.y)
  6169. return false;
  6170. if (boxMin.z > sphereCenter.z + sphereRadius)
  6171. return false;
  6172. if (sphereCenter.z - sphereRadius > boxMax.z)
  6173. return false;
  6174. return true;
  6175. };
  6176. var getLowestRoot = function (a, b, c, maxR) {
  6177. var determinant = b * b - 4.0 * a * c;
  6178. var result = { root: 0, found: false };
  6179. if (determinant < 0)
  6180. return result;
  6181. var sqrtD = Math.sqrt(determinant);
  6182. var r1 = (-b - sqrtD) / (2.0 * a);
  6183. var r2 = (-b + sqrtD) / (2.0 * a);
  6184. if (r1 > r2) {
  6185. var temp = r2;
  6186. r2 = r1;
  6187. r1 = temp;
  6188. }
  6189. if (r1 > 0 && r1 < maxR) {
  6190. result.root = r1;
  6191. result.found = true;
  6192. return result;
  6193. }
  6194. if (r2 > 0 && r2 < maxR) {
  6195. result.root = r2;
  6196. result.found = true;
  6197. return result;
  6198. }
  6199. return result;
  6200. };
  6201. var Collider = (function () {
  6202. function Collider() {
  6203. this.radius = new BABYLON.Vector3(1, 1, 1);
  6204. this.retry = 0;
  6205. this.basePointWorld = BABYLON.Vector3.Zero();
  6206. this.velocityWorld = BABYLON.Vector3.Zero();
  6207. this.normalizedVelocity = BABYLON.Vector3.Zero();
  6208. this._collisionPoint = BABYLON.Vector3.Zero();
  6209. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  6210. this._tempVector = BABYLON.Vector3.Zero();
  6211. this._tempVector2 = BABYLON.Vector3.Zero();
  6212. this._tempVector3 = BABYLON.Vector3.Zero();
  6213. this._tempVector4 = BABYLON.Vector3.Zero();
  6214. this._edge = BABYLON.Vector3.Zero();
  6215. this._baseToVertex = BABYLON.Vector3.Zero();
  6216. this._destinationPoint = BABYLON.Vector3.Zero();
  6217. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  6218. this._displacementVector = BABYLON.Vector3.Zero();
  6219. }
  6220. // Methods
  6221. Collider.prototype._initialize = function (source, dir, e) {
  6222. this.velocity = dir;
  6223. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  6224. this.basePoint = source;
  6225. source.multiplyToRef(this.radius, this.basePointWorld);
  6226. dir.multiplyToRef(this.radius, this.velocityWorld);
  6227. this.velocityWorldLength = this.velocityWorld.length();
  6228. this.epsilon = e;
  6229. this.collisionFound = false;
  6230. };
  6231. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  6232. pa.subtractToRef(point, this._tempVector);
  6233. pb.subtractToRef(point, this._tempVector2);
  6234. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  6235. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  6236. if (d < 0)
  6237. return false;
  6238. pc.subtractToRef(point, this._tempVector3);
  6239. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  6240. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  6241. if (d < 0)
  6242. return false;
  6243. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  6244. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  6245. return d >= 0;
  6246. };
  6247. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  6248. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  6249. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  6250. if (distance > this.velocityWorldLength + max + sphereRadius) {
  6251. return false;
  6252. }
  6253. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  6254. return false;
  6255. return true;
  6256. };
  6257. Collider.prototype._testTriangle = function (faceIndex, subMesh, p1, p2, p3) {
  6258. var t0;
  6259. var embeddedInPlane = false;
  6260. if (!subMesh._trianglePlanes) {
  6261. subMesh._trianglePlanes = [];
  6262. }
  6263. if (!subMesh._trianglePlanes[faceIndex]) {
  6264. subMesh._trianglePlanes[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  6265. subMesh._trianglePlanes[faceIndex].copyFromPoints(p1, p2, p3);
  6266. }
  6267. var trianglePlane = subMesh._trianglePlanes[faceIndex];
  6268. if ((!subMesh.getMaterial()) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  6269. return;
  6270. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  6271. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  6272. if (normalDotVelocity == 0) {
  6273. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  6274. return;
  6275. embeddedInPlane = true;
  6276. t0 = 0;
  6277. }
  6278. else {
  6279. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  6280. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  6281. if (t0 > t1) {
  6282. var temp = t1;
  6283. t1 = t0;
  6284. t0 = temp;
  6285. }
  6286. if (t0 > 1.0 || t1 < 0.0)
  6287. return;
  6288. if (t0 < 0)
  6289. t0 = 0;
  6290. if (t0 > 1.0)
  6291. t0 = 1.0;
  6292. }
  6293. this._collisionPoint.copyFromFloats(0, 0, 0);
  6294. var found = false;
  6295. var t = 1.0;
  6296. if (!embeddedInPlane) {
  6297. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  6298. this.velocity.scaleToRef(t0, this._tempVector);
  6299. this._planeIntersectionPoint.addInPlace(this._tempVector);
  6300. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  6301. found = true;
  6302. t = t0;
  6303. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  6304. }
  6305. }
  6306. if (!found) {
  6307. var velocitySquaredLength = this.velocity.lengthSquared();
  6308. var a = velocitySquaredLength;
  6309. this.basePoint.subtractToRef(p1, this._tempVector);
  6310. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  6311. var c = this._tempVector.lengthSquared() - 1.0;
  6312. var lowestRoot = getLowestRoot(a, b, c, t);
  6313. if (lowestRoot.found) {
  6314. t = lowestRoot.root;
  6315. found = true;
  6316. this._collisionPoint.copyFrom(p1);
  6317. }
  6318. this.basePoint.subtractToRef(p2, this._tempVector);
  6319. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  6320. c = this._tempVector.lengthSquared() - 1.0;
  6321. lowestRoot = getLowestRoot(a, b, c, t);
  6322. if (lowestRoot.found) {
  6323. t = lowestRoot.root;
  6324. found = true;
  6325. this._collisionPoint.copyFrom(p2);
  6326. }
  6327. this.basePoint.subtractToRef(p3, this._tempVector);
  6328. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  6329. c = this._tempVector.lengthSquared() - 1.0;
  6330. lowestRoot = getLowestRoot(a, b, c, t);
  6331. if (lowestRoot.found) {
  6332. t = lowestRoot.root;
  6333. found = true;
  6334. this._collisionPoint.copyFrom(p3);
  6335. }
  6336. p2.subtractToRef(p1, this._edge);
  6337. p1.subtractToRef(this.basePoint, this._baseToVertex);
  6338. var edgeSquaredLength = this._edge.lengthSquared();
  6339. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  6340. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  6341. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  6342. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  6343. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  6344. lowestRoot = getLowestRoot(a, b, c, t);
  6345. if (lowestRoot.found) {
  6346. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  6347. if (f >= 0.0 && f <= 1.0) {
  6348. t = lowestRoot.root;
  6349. found = true;
  6350. this._edge.scaleInPlace(f);
  6351. p1.addToRef(this._edge, this._collisionPoint);
  6352. }
  6353. }
  6354. p3.subtractToRef(p2, this._edge);
  6355. p2.subtractToRef(this.basePoint, this._baseToVertex);
  6356. edgeSquaredLength = this._edge.lengthSquared();
  6357. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  6358. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  6359. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  6360. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  6361. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  6362. lowestRoot = getLowestRoot(a, b, c, t);
  6363. if (lowestRoot.found) {
  6364. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  6365. if (f >= 0.0 && f <= 1.0) {
  6366. t = lowestRoot.root;
  6367. found = true;
  6368. this._edge.scaleInPlace(f);
  6369. p2.addToRef(this._edge, this._collisionPoint);
  6370. }
  6371. }
  6372. p1.subtractToRef(p3, this._edge);
  6373. p3.subtractToRef(this.basePoint, this._baseToVertex);
  6374. edgeSquaredLength = this._edge.lengthSquared();
  6375. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  6376. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  6377. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  6378. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  6379. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  6380. lowestRoot = getLowestRoot(a, b, c, t);
  6381. if (lowestRoot.found) {
  6382. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  6383. if (f >= 0.0 && f <= 1.0) {
  6384. t = lowestRoot.root;
  6385. found = true;
  6386. this._edge.scaleInPlace(f);
  6387. p3.addToRef(this._edge, this._collisionPoint);
  6388. }
  6389. }
  6390. }
  6391. if (found) {
  6392. var distToCollision = t * this.velocity.length();
  6393. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  6394. if (!this.intersectionPoint) {
  6395. this.intersectionPoint = this._collisionPoint.clone();
  6396. }
  6397. else {
  6398. this.intersectionPoint.copyFrom(this._collisionPoint);
  6399. }
  6400. this.nearestDistance = distToCollision;
  6401. this.collisionFound = true;
  6402. this.collidedMesh = subMesh.getMesh();
  6403. }
  6404. }
  6405. };
  6406. Collider.prototype._collide = function (subMesh, pts, indices, indexStart, indexEnd, decal) {
  6407. for (var i = indexStart; i < indexEnd; i += 3) {
  6408. var p1 = pts[indices[i] - decal];
  6409. var p2 = pts[indices[i + 1] - decal];
  6410. var p3 = pts[indices[i + 2] - decal];
  6411. this._testTriangle(i, subMesh, p3, p2, p1);
  6412. }
  6413. };
  6414. Collider.prototype._getResponse = function (pos, vel) {
  6415. pos.addToRef(vel, this._destinationPoint);
  6416. vel.scaleInPlace((this.nearestDistance / vel.length()));
  6417. this.basePoint.addToRef(vel, pos);
  6418. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  6419. this._slidePlaneNormal.normalize();
  6420. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  6421. pos.addInPlace(this._displacementVector);
  6422. this.intersectionPoint.addInPlace(this._displacementVector);
  6423. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  6424. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  6425. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  6426. };
  6427. return Collider;
  6428. })();
  6429. BABYLON.Collider = Collider;
  6430. })(BABYLON || (BABYLON = {}));
  6431. //# sourceMappingURL=babylon.collider.js.map
  6432. var BABYLON;
  6433. (function (BABYLON) {
  6434. var Camera = (function (_super) {
  6435. __extends(Camera, _super);
  6436. function Camera(name, position, scene) {
  6437. _super.call(this, name, scene);
  6438. this.position = position;
  6439. // Members
  6440. this.upVector = BABYLON.Vector3.Up();
  6441. this.orthoLeft = null;
  6442. this.orthoRight = null;
  6443. this.orthoBottom = null;
  6444. this.orthoTop = null;
  6445. this.fov = 0.8;
  6446. this.minZ = 1.0;
  6447. this.maxZ = 10000.0;
  6448. this.inertia = 0.9;
  6449. this.mode = Camera.PERSPECTIVE_CAMERA;
  6450. this.isIntermediate = false;
  6451. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  6452. this.subCameras = [];
  6453. this.layerMask = 0xFFFFFFFF;
  6454. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  6455. this._computedViewMatrix = BABYLON.Matrix.Identity();
  6456. this._projectionMatrix = new BABYLON.Matrix();
  6457. this._postProcesses = new Array();
  6458. this._postProcessesTakenIndices = [];
  6459. this._activeMeshes = new BABYLON.SmartArray(256);
  6460. scene.cameras.push(this);
  6461. if (!scene.activeCamera) {
  6462. scene.activeCamera = this;
  6463. }
  6464. }
  6465. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  6466. get: function () {
  6467. return Camera._PERSPECTIVE_CAMERA;
  6468. },
  6469. enumerable: true,
  6470. configurable: true
  6471. });
  6472. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  6473. get: function () {
  6474. return Camera._ORTHOGRAPHIC_CAMERA;
  6475. },
  6476. enumerable: true,
  6477. configurable: true
  6478. });
  6479. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  6480. get: function () {
  6481. return Camera._FOVMODE_VERTICAL_FIXED;
  6482. },
  6483. enumerable: true,
  6484. configurable: true
  6485. });
  6486. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  6487. get: function () {
  6488. return Camera._FOVMODE_HORIZONTAL_FIXED;
  6489. },
  6490. enumerable: true,
  6491. configurable: true
  6492. });
  6493. Camera.prototype.getActiveMeshes = function () {
  6494. return this._activeMeshes;
  6495. };
  6496. Camera.prototype.isActiveMesh = function (mesh) {
  6497. return (this._activeMeshes.indexOf(mesh) !== -1);
  6498. };
  6499. //Cache
  6500. Camera.prototype._initCache = function () {
  6501. _super.prototype._initCache.call(this);
  6502. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6503. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6504. this._cache.mode = undefined;
  6505. this._cache.minZ = undefined;
  6506. this._cache.maxZ = undefined;
  6507. this._cache.fov = undefined;
  6508. this._cache.aspectRatio = undefined;
  6509. this._cache.orthoLeft = undefined;
  6510. this._cache.orthoRight = undefined;
  6511. this._cache.orthoBottom = undefined;
  6512. this._cache.orthoTop = undefined;
  6513. this._cache.renderWidth = undefined;
  6514. this._cache.renderHeight = undefined;
  6515. };
  6516. Camera.prototype._updateCache = function (ignoreParentClass) {
  6517. if (!ignoreParentClass) {
  6518. _super.prototype._updateCache.call(this);
  6519. }
  6520. var engine = this.getEngine();
  6521. this._cache.position.copyFrom(this.position);
  6522. this._cache.upVector.copyFrom(this.upVector);
  6523. this._cache.mode = this.mode;
  6524. this._cache.minZ = this.minZ;
  6525. this._cache.maxZ = this.maxZ;
  6526. this._cache.fov = this.fov;
  6527. this._cache.aspectRatio = engine.getAspectRatio(this);
  6528. this._cache.orthoLeft = this.orthoLeft;
  6529. this._cache.orthoRight = this.orthoRight;
  6530. this._cache.orthoBottom = this.orthoBottom;
  6531. this._cache.orthoTop = this.orthoTop;
  6532. this._cache.renderWidth = engine.getRenderWidth();
  6533. this._cache.renderHeight = engine.getRenderHeight();
  6534. };
  6535. Camera.prototype._updateFromScene = function () {
  6536. this.updateCache();
  6537. this._update();
  6538. };
  6539. // Synchronized
  6540. Camera.prototype._isSynchronized = function () {
  6541. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  6542. };
  6543. Camera.prototype._isSynchronizedViewMatrix = function () {
  6544. if (!_super.prototype._isSynchronized.call(this))
  6545. return false;
  6546. return this._cache.position.equals(this.position) && this._cache.upVector.equals(this.upVector) && this.isSynchronizedWithParent();
  6547. };
  6548. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  6549. var check = this._cache.mode === this.mode && this._cache.minZ === this.minZ && this._cache.maxZ === this.maxZ;
  6550. if (!check) {
  6551. return false;
  6552. }
  6553. var engine = this.getEngine();
  6554. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  6555. check = this._cache.fov === this.fov && this._cache.aspectRatio === engine.getAspectRatio(this);
  6556. }
  6557. else {
  6558. 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();
  6559. }
  6560. return check;
  6561. };
  6562. // Controls
  6563. Camera.prototype.attachControl = function (element) {
  6564. };
  6565. Camera.prototype.detachControl = function (element) {
  6566. };
  6567. Camera.prototype._update = function () {
  6568. };
  6569. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  6570. if (insertAt === void 0) { insertAt = null; }
  6571. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  6572. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  6573. return 0;
  6574. }
  6575. if (insertAt == null || insertAt < 0) {
  6576. this._postProcesses.push(postProcess);
  6577. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  6578. return this._postProcesses.length - 1;
  6579. }
  6580. var add = 0;
  6581. if (this._postProcesses[insertAt]) {
  6582. var start = this._postProcesses.length - 1;
  6583. for (var i = start; i >= insertAt + 1; --i) {
  6584. this._postProcesses[i + 1] = this._postProcesses[i];
  6585. }
  6586. add = 1;
  6587. }
  6588. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  6589. if (this._postProcessesTakenIndices[i] < insertAt) {
  6590. continue;
  6591. }
  6592. start = this._postProcessesTakenIndices.length - 1;
  6593. for (var j = start; j >= i; --j) {
  6594. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  6595. }
  6596. this._postProcessesTakenIndices[i] = insertAt;
  6597. break;
  6598. }
  6599. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) == -1) {
  6600. this._postProcessesTakenIndices.push(insertAt);
  6601. }
  6602. var result = insertAt + add;
  6603. this._postProcesses[result] = postProcess;
  6604. return result;
  6605. };
  6606. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  6607. if (atIndices === void 0) { atIndices = null; }
  6608. var result = [];
  6609. if (!atIndices) {
  6610. var length = this._postProcesses.length;
  6611. for (var i = 0; i < length; i++) {
  6612. if (this._postProcesses[i] !== postProcess) {
  6613. continue;
  6614. }
  6615. delete this._postProcesses[i];
  6616. var index = this._postProcessesTakenIndices.indexOf(i);
  6617. this._postProcessesTakenIndices.splice(index, 1);
  6618. }
  6619. }
  6620. else {
  6621. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  6622. for (i = 0; i < atIndices.length; i++) {
  6623. var foundPostProcess = this._postProcesses[atIndices[i]];
  6624. if (foundPostProcess !== postProcess) {
  6625. result.push(i);
  6626. continue;
  6627. }
  6628. delete this._postProcesses[atIndices[i]];
  6629. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  6630. this._postProcessesTakenIndices.splice(index, 1);
  6631. }
  6632. }
  6633. return result;
  6634. };
  6635. Camera.prototype.getWorldMatrix = function () {
  6636. if (!this._worldMatrix) {
  6637. this._worldMatrix = BABYLON.Matrix.Identity();
  6638. }
  6639. var viewMatrix = this.getViewMatrix();
  6640. viewMatrix.invertToRef(this._worldMatrix);
  6641. return this._worldMatrix;
  6642. };
  6643. Camera.prototype._getViewMatrix = function () {
  6644. return BABYLON.Matrix.Identity();
  6645. };
  6646. Camera.prototype.getViewMatrix = function () {
  6647. this._computedViewMatrix = this._computeViewMatrix();
  6648. if (!this.parent || !this.parent.getWorldMatrix || this.isSynchronized()) {
  6649. return this._computedViewMatrix;
  6650. }
  6651. if (!this._worldMatrix) {
  6652. this._worldMatrix = BABYLON.Matrix.Identity();
  6653. }
  6654. this._computedViewMatrix.invertToRef(this._worldMatrix);
  6655. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  6656. this._computedViewMatrix.invert();
  6657. this._currentRenderId = this.getScene().getRenderId();
  6658. return this._computedViewMatrix;
  6659. };
  6660. Camera.prototype._computeViewMatrix = function (force) {
  6661. if (!force && this._isSynchronizedViewMatrix()) {
  6662. return this._computedViewMatrix;
  6663. }
  6664. this._computedViewMatrix = this._getViewMatrix();
  6665. if (!this.parent || !this.parent.getWorldMatrix) {
  6666. this._currentRenderId = this.getScene().getRenderId();
  6667. }
  6668. return this._computedViewMatrix;
  6669. };
  6670. Camera.prototype.getProjectionMatrix = function (force) {
  6671. if (!force && this._isSynchronizedProjectionMatrix()) {
  6672. return this._projectionMatrix;
  6673. }
  6674. var engine = this.getEngine();
  6675. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  6676. if (this.minZ <= 0) {
  6677. this.minZ = 0.1;
  6678. }
  6679. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode);
  6680. return this._projectionMatrix;
  6681. }
  6682. var halfWidth = engine.getRenderWidth() / 2.0;
  6683. var halfHeight = engine.getRenderHeight() / 2.0;
  6684. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  6685. return this._projectionMatrix;
  6686. };
  6687. Camera.prototype.dispose = function () {
  6688. // Remove from scene
  6689. var index = this.getScene().cameras.indexOf(this);
  6690. this.getScene().cameras.splice(index, 1);
  6691. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  6692. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  6693. }
  6694. };
  6695. // Statics
  6696. Camera._PERSPECTIVE_CAMERA = 0;
  6697. Camera._ORTHOGRAPHIC_CAMERA = 1;
  6698. Camera._FOVMODE_VERTICAL_FIXED = 0;
  6699. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  6700. return Camera;
  6701. })(BABYLON.Node);
  6702. BABYLON.Camera = Camera;
  6703. })(BABYLON || (BABYLON = {}));
  6704. //# sourceMappingURL=babylon.camera.js.map
  6705. var BABYLON;
  6706. (function (BABYLON) {
  6707. var TargetCamera = (function (_super) {
  6708. __extends(TargetCamera, _super);
  6709. function TargetCamera(name, position, scene) {
  6710. _super.call(this, name, position, scene);
  6711. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  6712. this.cameraRotation = new BABYLON.Vector2(0, 0);
  6713. this.rotation = new BABYLON.Vector3(0, 0, 0);
  6714. this.speed = 2.0;
  6715. this.noRotationConstraint = false;
  6716. this.lockedTarget = null;
  6717. this._currentTarget = BABYLON.Vector3.Zero();
  6718. this._viewMatrix = BABYLON.Matrix.Zero();
  6719. this._camMatrix = BABYLON.Matrix.Zero();
  6720. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  6721. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  6722. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  6723. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  6724. this._lookAtTemp = BABYLON.Matrix.Zero();
  6725. this._tempMatrix = BABYLON.Matrix.Zero();
  6726. }
  6727. TargetCamera.prototype._getLockedTargetPosition = function () {
  6728. if (!this.lockedTarget) {
  6729. return null;
  6730. }
  6731. return this.lockedTarget.position || this.lockedTarget;
  6732. };
  6733. // Cache
  6734. TargetCamera.prototype._initCache = function () {
  6735. _super.prototype._initCache.call(this);
  6736. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6737. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6738. };
  6739. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  6740. if (!ignoreParentClass) {
  6741. _super.prototype._updateCache.call(this);
  6742. }
  6743. var lockedTargetPosition = this._getLockedTargetPosition();
  6744. if (!lockedTargetPosition) {
  6745. this._cache.lockedTarget = null;
  6746. }
  6747. else {
  6748. if (!this._cache.lockedTarget) {
  6749. this._cache.lockedTarget = lockedTargetPosition.clone();
  6750. }
  6751. else {
  6752. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  6753. }
  6754. }
  6755. this._cache.rotation.copyFrom(this.rotation);
  6756. };
  6757. // Synchronized
  6758. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  6759. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  6760. return false;
  6761. }
  6762. var lockedTargetPosition = this._getLockedTargetPosition();
  6763. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition) && this._cache.rotation.equals(this.rotation);
  6764. };
  6765. // Methods
  6766. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  6767. var engine = this.getEngine();
  6768. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  6769. };
  6770. // Target
  6771. TargetCamera.prototype.setTarget = function (target) {
  6772. this.upVector.normalize();
  6773. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  6774. this._camMatrix.invert();
  6775. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  6776. var vDir = target.subtract(this.position);
  6777. if (vDir.x >= 0.0) {
  6778. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  6779. }
  6780. else {
  6781. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  6782. }
  6783. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  6784. if (isNaN(this.rotation.x)) {
  6785. this.rotation.x = 0;
  6786. }
  6787. if (isNaN(this.rotation.y)) {
  6788. this.rotation.y = 0;
  6789. }
  6790. if (isNaN(this.rotation.z)) {
  6791. this.rotation.z = 0;
  6792. }
  6793. };
  6794. TargetCamera.prototype.getTarget = function () {
  6795. return this._currentTarget;
  6796. };
  6797. TargetCamera.prototype._decideIfNeedsToMove = function () {
  6798. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  6799. };
  6800. TargetCamera.prototype._updatePosition = function () {
  6801. this.position.addInPlace(this.cameraDirection);
  6802. };
  6803. TargetCamera.prototype._update = function () {
  6804. var needToMove = this._decideIfNeedsToMove();
  6805. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  6806. // Move
  6807. if (needToMove) {
  6808. this._updatePosition();
  6809. }
  6810. // Rotate
  6811. if (needToRotate) {
  6812. this.rotation.x += this.cameraRotation.x;
  6813. this.rotation.y += this.cameraRotation.y;
  6814. if (!this.noRotationConstraint) {
  6815. var limit = (Math.PI / 2) * 0.95;
  6816. if (this.rotation.x > limit)
  6817. this.rotation.x = limit;
  6818. if (this.rotation.x < -limit)
  6819. this.rotation.x = -limit;
  6820. }
  6821. }
  6822. // Inertia
  6823. if (needToMove) {
  6824. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  6825. this.cameraDirection.x = 0;
  6826. }
  6827. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  6828. this.cameraDirection.y = 0;
  6829. }
  6830. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  6831. this.cameraDirection.z = 0;
  6832. }
  6833. this.cameraDirection.scaleInPlace(this.inertia);
  6834. }
  6835. if (needToRotate) {
  6836. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  6837. this.cameraRotation.x = 0;
  6838. }
  6839. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  6840. this.cameraRotation.y = 0;
  6841. }
  6842. this.cameraRotation.scaleInPlace(this.inertia);
  6843. }
  6844. };
  6845. TargetCamera.prototype._getViewMatrix = function () {
  6846. if (!this.lockedTarget) {
  6847. // Compute
  6848. if (this.upVector.x != 0 || this.upVector.y != 1.0 || this.upVector.z != 0) {
  6849. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  6850. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  6851. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  6852. this._lookAtTemp.invert();
  6853. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  6854. }
  6855. else {
  6856. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  6857. }
  6858. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  6859. // Computing target and final matrix
  6860. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  6861. }
  6862. else {
  6863. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  6864. }
  6865. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  6866. return this._viewMatrix;
  6867. };
  6868. return TargetCamera;
  6869. })(BABYLON.Camera);
  6870. BABYLON.TargetCamera = TargetCamera;
  6871. })(BABYLON || (BABYLON = {}));
  6872. //# sourceMappingURL=babylon.targetCamera.js.map
  6873. var BABYLON;
  6874. (function (BABYLON) {
  6875. var FollowCamera = (function (_super) {
  6876. __extends(FollowCamera, _super);
  6877. function FollowCamera(name, position, scene) {
  6878. _super.call(this, name, position, scene);
  6879. this.radius = 12;
  6880. this.rotationOffset = 0;
  6881. this.heightOffset = 4;
  6882. this.cameraAcceleration = 0.05;
  6883. this.maxCameraSpeed = 20;
  6884. }
  6885. FollowCamera.prototype.getRadians = function (degrees) {
  6886. return degrees * Math.PI / 180;
  6887. };
  6888. FollowCamera.prototype.follow = function (cameraTarget) {
  6889. if (!cameraTarget)
  6890. return;
  6891. var radians = this.getRadians(this.rotationOffset) + cameraTarget.rotation.y;
  6892. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  6893. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  6894. var dx = targetX - this.position.x;
  6895. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  6896. var dz = (targetZ) - this.position.z;
  6897. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  6898. var vy = dy * this.cameraAcceleration;
  6899. var vz = dz * this.cameraAcceleration * 2;
  6900. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  6901. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  6902. }
  6903. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  6904. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  6905. }
  6906. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  6907. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  6908. }
  6909. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  6910. this.setTarget(cameraTarget.position);
  6911. };
  6912. FollowCamera.prototype._update = function () {
  6913. _super.prototype._update.call(this);
  6914. this.follow(this.target);
  6915. };
  6916. return FollowCamera;
  6917. })(BABYLON.TargetCamera);
  6918. BABYLON.FollowCamera = FollowCamera;
  6919. })(BABYLON || (BABYLON = {}));
  6920. //# sourceMappingURL=babylon.followCamera.js.map
  6921. var BABYLON;
  6922. (function (BABYLON) {
  6923. var FreeCamera = (function (_super) {
  6924. __extends(FreeCamera, _super);
  6925. function FreeCamera(name, position, scene) {
  6926. _super.call(this, name, position, scene);
  6927. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  6928. this.keysUp = [38];
  6929. this.keysDown = [40];
  6930. this.keysLeft = [37];
  6931. this.keysRight = [39];
  6932. this.checkCollisions = false;
  6933. this.applyGravity = false;
  6934. this.angularSensibility = 2000.0;
  6935. this._keys = [];
  6936. this._collider = new BABYLON.Collider();
  6937. this._needMoveForGravity = true;
  6938. this._oldPosition = BABYLON.Vector3.Zero();
  6939. this._diffPosition = BABYLON.Vector3.Zero();
  6940. this._newPosition = BABYLON.Vector3.Zero();
  6941. }
  6942. // Controls
  6943. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  6944. var _this = this;
  6945. var previousPosition;
  6946. var engine = this.getEngine();
  6947. if (this._attachedElement) {
  6948. return;
  6949. }
  6950. this._attachedElement = element;
  6951. if (this._onMouseDown === undefined) {
  6952. this._onMouseDown = function (evt) {
  6953. previousPosition = {
  6954. x: evt.clientX,
  6955. y: evt.clientY
  6956. };
  6957. if (!noPreventDefault) {
  6958. evt.preventDefault();
  6959. }
  6960. };
  6961. this._onMouseUp = function (evt) {
  6962. previousPosition = null;
  6963. if (!noPreventDefault) {
  6964. evt.preventDefault();
  6965. }
  6966. };
  6967. this._onMouseOut = function (evt) {
  6968. previousPosition = null;
  6969. _this._keys = [];
  6970. if (!noPreventDefault) {
  6971. evt.preventDefault();
  6972. }
  6973. };
  6974. this._onMouseMove = function (evt) {
  6975. if (!previousPosition && !engine.isPointerLock) {
  6976. return;
  6977. }
  6978. var offsetX;
  6979. var offsetY;
  6980. if (!engine.isPointerLock) {
  6981. offsetX = evt.clientX - previousPosition.x;
  6982. offsetY = evt.clientY - previousPosition.y;
  6983. }
  6984. else {
  6985. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  6986. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  6987. }
  6988. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  6989. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  6990. previousPosition = {
  6991. x: evt.clientX,
  6992. y: evt.clientY
  6993. };
  6994. if (!noPreventDefault) {
  6995. evt.preventDefault();
  6996. }
  6997. };
  6998. this._onKeyDown = function (evt) {
  6999. 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) {
  7000. var index = _this._keys.indexOf(evt.keyCode);
  7001. if (index === -1) {
  7002. _this._keys.push(evt.keyCode);
  7003. }
  7004. if (!noPreventDefault) {
  7005. evt.preventDefault();
  7006. }
  7007. }
  7008. };
  7009. this._onKeyUp = function (evt) {
  7010. 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) {
  7011. var index = _this._keys.indexOf(evt.keyCode);
  7012. if (index >= 0) {
  7013. _this._keys.splice(index, 1);
  7014. }
  7015. if (!noPreventDefault) {
  7016. evt.preventDefault();
  7017. }
  7018. }
  7019. };
  7020. this._onLostFocus = function () {
  7021. _this._keys = [];
  7022. };
  7023. this._reset = function () {
  7024. _this._keys = [];
  7025. previousPosition = null;
  7026. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  7027. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  7028. };
  7029. }
  7030. element.addEventListener("mousedown", this._onMouseDown, false);
  7031. element.addEventListener("mouseup", this._onMouseUp, false);
  7032. element.addEventListener("mouseout", this._onMouseOut, false);
  7033. element.addEventListener("mousemove", this._onMouseMove, false);
  7034. BABYLON.Tools.RegisterTopRootEvents([
  7035. { name: "keydown", handler: this._onKeyDown },
  7036. { name: "keyup", handler: this._onKeyUp },
  7037. { name: "blur", handler: this._onLostFocus }
  7038. ]);
  7039. };
  7040. FreeCamera.prototype.detachControl = function (element) {
  7041. if (this._attachedElement != element) {
  7042. return;
  7043. }
  7044. element.removeEventListener("mousedown", this._onMouseDown);
  7045. element.removeEventListener("mouseup", this._onMouseUp);
  7046. element.removeEventListener("mouseout", this._onMouseOut);
  7047. element.removeEventListener("mousemove", this._onMouseMove);
  7048. BABYLON.Tools.UnregisterTopRootEvents([
  7049. { name: "keydown", handler: this._onKeyDown },
  7050. { name: "keyup", handler: this._onKeyUp },
  7051. { name: "blur", handler: this._onLostFocus }
  7052. ]);
  7053. this._attachedElement = null;
  7054. if (this._reset) {
  7055. this._reset();
  7056. }
  7057. };
  7058. FreeCamera.prototype._collideWithWorld = function (velocity) {
  7059. var globalPosition;
  7060. if (this.parent) {
  7061. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  7062. }
  7063. else {
  7064. globalPosition = this.position;
  7065. }
  7066. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  7067. this._collider.radius = this.ellipsoid;
  7068. this.getScene()._getNewPosition(this._oldPosition, velocity, this._collider, 3, this._newPosition);
  7069. this._newPosition.subtractToRef(this._oldPosition, this._diffPosition);
  7070. if (this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  7071. this.position.addInPlace(this._diffPosition);
  7072. if (this.onCollide) {
  7073. this.onCollide(this._collider.collidedMesh);
  7074. }
  7075. }
  7076. };
  7077. FreeCamera.prototype._checkInputs = function () {
  7078. if (!this._localDirection) {
  7079. this._localDirection = BABYLON.Vector3.Zero();
  7080. this._transformedDirection = BABYLON.Vector3.Zero();
  7081. }
  7082. for (var index = 0; index < this._keys.length; index++) {
  7083. var keyCode = this._keys[index];
  7084. var speed = this._computeLocalCameraSpeed();
  7085. if (this.keysLeft.indexOf(keyCode) !== -1) {
  7086. this._localDirection.copyFromFloats(-speed, 0, 0);
  7087. }
  7088. else if (this.keysUp.indexOf(keyCode) !== -1) {
  7089. this._localDirection.copyFromFloats(0, 0, speed);
  7090. }
  7091. else if (this.keysRight.indexOf(keyCode) !== -1) {
  7092. this._localDirection.copyFromFloats(speed, 0, 0);
  7093. }
  7094. else if (this.keysDown.indexOf(keyCode) !== -1) {
  7095. this._localDirection.copyFromFloats(0, 0, -speed);
  7096. }
  7097. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  7098. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  7099. this.cameraDirection.addInPlace(this._transformedDirection);
  7100. }
  7101. };
  7102. FreeCamera.prototype._decideIfNeedsToMove = function () {
  7103. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  7104. };
  7105. FreeCamera.prototype._updatePosition = function () {
  7106. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  7107. this._collideWithWorld(this.cameraDirection);
  7108. if (this.applyGravity) {
  7109. var oldPosition = this.position;
  7110. this._collideWithWorld(this.getScene().gravity);
  7111. this._needMoveForGravity = (BABYLON.Vector3.DistanceSquared(oldPosition, this.position) != 0);
  7112. }
  7113. }
  7114. else {
  7115. this.position.addInPlace(this.cameraDirection);
  7116. }
  7117. };
  7118. FreeCamera.prototype._update = function () {
  7119. this._checkInputs();
  7120. _super.prototype._update.call(this);
  7121. };
  7122. return FreeCamera;
  7123. })(BABYLON.TargetCamera);
  7124. BABYLON.FreeCamera = FreeCamera;
  7125. })(BABYLON || (BABYLON = {}));
  7126. //# sourceMappingURL=babylon.freeCamera.js.map
  7127. var BABYLON;
  7128. (function (BABYLON) {
  7129. // We're mainly based on the logic defined into the FreeCamera code
  7130. var TouchCamera = (function (_super) {
  7131. __extends(TouchCamera, _super);
  7132. function TouchCamera(name, position, scene) {
  7133. _super.call(this, name, position, scene);
  7134. this._offsetX = null;
  7135. this._offsetY = null;
  7136. this._pointerCount = 0;
  7137. this._pointerPressed = [];
  7138. this.angularSensibility = 200000.0;
  7139. this.moveSensibility = 500.0;
  7140. }
  7141. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  7142. var _this = this;
  7143. var previousPosition;
  7144. if (this._attachedCanvas) {
  7145. return;
  7146. }
  7147. this._attachedCanvas = canvas;
  7148. if (this._onPointerDown === undefined) {
  7149. this._onPointerDown = function (evt) {
  7150. if (!noPreventDefault) {
  7151. evt.preventDefault();
  7152. }
  7153. _this._pointerPressed.push(evt.pointerId);
  7154. if (_this._pointerPressed.length !== 1) {
  7155. return;
  7156. }
  7157. previousPosition = {
  7158. x: evt.clientX,
  7159. y: evt.clientY
  7160. };
  7161. };
  7162. this._onPointerUp = function (evt) {
  7163. if (!noPreventDefault) {
  7164. evt.preventDefault();
  7165. }
  7166. var index = _this._pointerPressed.indexOf(evt.pointerId);
  7167. if (index === -1) {
  7168. return;
  7169. }
  7170. _this._pointerPressed.splice(index, 1);
  7171. if (index != 0) {
  7172. return;
  7173. }
  7174. previousPosition = null;
  7175. _this._offsetX = null;
  7176. _this._offsetY = null;
  7177. };
  7178. this._onPointerMove = function (evt) {
  7179. if (!noPreventDefault) {
  7180. evt.preventDefault();
  7181. }
  7182. if (!previousPosition) {
  7183. return;
  7184. }
  7185. var index = _this._pointerPressed.indexOf(evt.pointerId);
  7186. if (index != 0) {
  7187. return;
  7188. }
  7189. _this._offsetX = evt.clientX - previousPosition.x;
  7190. _this._offsetY = -(evt.clientY - previousPosition.y);
  7191. };
  7192. this._onLostFocus = function () {
  7193. _this._offsetX = null;
  7194. _this._offsetY = null;
  7195. };
  7196. }
  7197. canvas.addEventListener("pointerdown", this._onPointerDown);
  7198. canvas.addEventListener("pointerup", this._onPointerUp);
  7199. canvas.addEventListener("pointerout", this._onPointerUp);
  7200. canvas.addEventListener("pointermove", this._onPointerMove);
  7201. BABYLON.Tools.RegisterTopRootEvents([
  7202. { name: "blur", handler: this._onLostFocus }
  7203. ]);
  7204. };
  7205. TouchCamera.prototype.detachControl = function (canvas) {
  7206. if (this._attachedCanvas != canvas) {
  7207. return;
  7208. }
  7209. canvas.removeEventListener("pointerdown", this._onPointerDown);
  7210. canvas.removeEventListener("pointerup", this._onPointerUp);
  7211. canvas.removeEventListener("pointerout", this._onPointerUp);
  7212. canvas.removeEventListener("pointermove", this._onPointerMove);
  7213. BABYLON.Tools.UnregisterTopRootEvents([
  7214. { name: "blur", handler: this._onLostFocus }
  7215. ]);
  7216. this._attachedCanvas = null;
  7217. };
  7218. TouchCamera.prototype._checkInputs = function () {
  7219. if (!this._offsetX) {
  7220. return;
  7221. }
  7222. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  7223. if (this._pointerPressed.length > 1) {
  7224. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  7225. }
  7226. else {
  7227. var speed = this._computeLocalCameraSpeed();
  7228. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  7229. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  7230. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  7231. }
  7232. };
  7233. return TouchCamera;
  7234. })(BABYLON.FreeCamera);
  7235. BABYLON.TouchCamera = TouchCamera;
  7236. })(BABYLON || (BABYLON = {}));
  7237. //# sourceMappingURL=babylon.touchCamera.js.map
  7238. var BABYLON;
  7239. (function (BABYLON) {
  7240. // We're mainly based on the logic defined into the FreeCamera code
  7241. var DeviceOrientationCamera = (function (_super) {
  7242. __extends(DeviceOrientationCamera, _super);
  7243. function DeviceOrientationCamera(name, position, scene) {
  7244. var _this = this;
  7245. _super.call(this, name, position, scene);
  7246. this._offsetX = null;
  7247. this._offsetY = null;
  7248. this._orientationGamma = 0;
  7249. this._orientationBeta = 0;
  7250. this._initialOrientationGamma = 0;
  7251. this._initialOrientationBeta = 0;
  7252. this.angularSensibility = 10000.0;
  7253. this.moveSensibility = 50.0;
  7254. window.addEventListener("resize", function () {
  7255. _this._initialOrientationGamma = null;
  7256. }, false);
  7257. }
  7258. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  7259. var _this = this;
  7260. if (this._attachedCanvas) {
  7261. return;
  7262. }
  7263. this._attachedCanvas = canvas;
  7264. if (!this._orientationChanged) {
  7265. this._orientationChanged = function (evt) {
  7266. if (!_this._initialOrientationGamma) {
  7267. _this._initialOrientationGamma = evt.gamma;
  7268. _this._initialOrientationBeta = evt.beta;
  7269. }
  7270. _this._orientationGamma = evt.gamma;
  7271. _this._orientationBeta = evt.beta;
  7272. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  7273. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  7274. };
  7275. }
  7276. window.addEventListener("deviceorientation", this._orientationChanged);
  7277. };
  7278. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  7279. if (this._attachedCanvas != canvas) {
  7280. return;
  7281. }
  7282. window.removeEventListener("deviceorientation", this._orientationChanged);
  7283. this._attachedCanvas = null;
  7284. this._orientationGamma = 0;
  7285. this._orientationBeta = 0;
  7286. this._initialOrientationGamma = 0;
  7287. this._initialOrientationBeta = 0;
  7288. };
  7289. DeviceOrientationCamera.prototype._checkInputs = function () {
  7290. if (!this._offsetX) {
  7291. return;
  7292. }
  7293. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  7294. var speed = this._computeLocalCameraSpeed();
  7295. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  7296. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  7297. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  7298. };
  7299. return DeviceOrientationCamera;
  7300. })(BABYLON.FreeCamera);
  7301. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  7302. })(BABYLON || (BABYLON = {}));
  7303. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  7304. var BABYLON;
  7305. (function (BABYLON) {
  7306. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  7307. var ArcRotateCamera = (function (_super) {
  7308. __extends(ArcRotateCamera, _super);
  7309. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  7310. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  7311. this.alpha = alpha;
  7312. this.beta = beta;
  7313. this.radius = radius;
  7314. this.target = target;
  7315. this.inertialAlphaOffset = 0;
  7316. this.inertialBetaOffset = 0;
  7317. this.inertialRadiusOffset = 0;
  7318. this.lowerAlphaLimit = null;
  7319. this.upperAlphaLimit = null;
  7320. this.lowerBetaLimit = 0.01;
  7321. this.upperBetaLimit = Math.PI;
  7322. this.lowerRadiusLimit = null;
  7323. this.upperRadiusLimit = null;
  7324. this.angularSensibility = 1000.0;
  7325. this.wheelPrecision = 3.0;
  7326. this.keysUp = [38];
  7327. this.keysDown = [40];
  7328. this.keysLeft = [37];
  7329. this.keysRight = [39];
  7330. this.zoomOnFactor = 1;
  7331. this.targetScreenOffset = BABYLON.Vector2.Zero();
  7332. this._keys = [];
  7333. this._viewMatrix = new BABYLON.Matrix();
  7334. this.checkCollisions = false;
  7335. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  7336. this._collider = new BABYLON.Collider();
  7337. this._previousPosition = BABYLON.Vector3.Zero();
  7338. this._collisionVelocity = BABYLON.Vector3.Zero();
  7339. this._newPosition = BABYLON.Vector3.Zero();
  7340. // Pinch
  7341. // value for pinch step scaling
  7342. // set to 20 by default
  7343. this.pinchPrecision = 20;
  7344. this.getViewMatrix();
  7345. }
  7346. ArcRotateCamera.prototype._getTargetPosition = function () {
  7347. return this.target.position || this.target;
  7348. };
  7349. // Cache
  7350. ArcRotateCamera.prototype._initCache = function () {
  7351. _super.prototype._initCache.call(this);
  7352. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7353. this._cache.alpha = undefined;
  7354. this._cache.beta = undefined;
  7355. this._cache.radius = undefined;
  7356. this._cache.targetScreenOffset = undefined;
  7357. };
  7358. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  7359. if (!ignoreParentClass) {
  7360. _super.prototype._updateCache.call(this);
  7361. }
  7362. this._cache.target.copyFrom(this._getTargetPosition());
  7363. this._cache.alpha = this.alpha;
  7364. this._cache.beta = this.beta;
  7365. this._cache.radius = this.radius;
  7366. this._cache.targetScreenOffset = this.targetScreenOffset.clone();
  7367. };
  7368. // Synchronized
  7369. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  7370. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  7371. return false;
  7372. 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);
  7373. };
  7374. // Methods
  7375. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault) {
  7376. var _this = this;
  7377. var previousPosition;
  7378. var pointerId;
  7379. // to know if pinch started
  7380. var pinchStarted = false;
  7381. // two pinch point on X
  7382. // that will use for find if user action is pinch open or pinch close
  7383. var pinchPointX1, pinchPointX2;
  7384. if (this._attachedElement) {
  7385. return;
  7386. }
  7387. this._attachedElement = element;
  7388. var engine = this.getEngine();
  7389. if (this._onPointerDown === undefined) {
  7390. this._onPointerDown = function (evt) {
  7391. if (pointerId) {
  7392. return;
  7393. }
  7394. pointerId = evt.pointerId;
  7395. previousPosition = {
  7396. x: evt.clientX,
  7397. y: evt.clientY
  7398. };
  7399. if (!noPreventDefault) {
  7400. evt.preventDefault();
  7401. }
  7402. };
  7403. this._onPointerUp = function (evt) {
  7404. previousPosition = null;
  7405. pointerId = null;
  7406. if (!noPreventDefault) {
  7407. evt.preventDefault();
  7408. }
  7409. };
  7410. this._onPointerMove = function (evt) {
  7411. if (!previousPosition) {
  7412. return;
  7413. }
  7414. if (pointerId !== evt.pointerId) {
  7415. return;
  7416. }
  7417. // return pinch is started
  7418. if (pinchStarted) {
  7419. return;
  7420. }
  7421. var offsetX = evt.clientX - previousPosition.x;
  7422. var offsetY = evt.clientY - previousPosition.y;
  7423. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  7424. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  7425. previousPosition = {
  7426. x: evt.clientX,
  7427. y: evt.clientY
  7428. };
  7429. if (!noPreventDefault) {
  7430. evt.preventDefault();
  7431. }
  7432. };
  7433. this._onMouseMove = function (evt) {
  7434. if (!engine.isPointerLock) {
  7435. return;
  7436. }
  7437. // return pinch is started
  7438. if (pinchStarted) {
  7439. return;
  7440. }
  7441. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  7442. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  7443. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  7444. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  7445. if (!noPreventDefault) {
  7446. evt.preventDefault();
  7447. }
  7448. };
  7449. this._wheel = function (event) {
  7450. var delta = 0;
  7451. if (event.wheelDelta) {
  7452. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  7453. }
  7454. else if (event.detail) {
  7455. delta = -event.detail / _this.wheelPrecision;
  7456. }
  7457. if (delta)
  7458. _this.inertialRadiusOffset += delta;
  7459. if (event.preventDefault) {
  7460. if (!noPreventDefault) {
  7461. event.preventDefault();
  7462. }
  7463. }
  7464. };
  7465. this._onKeyDown = function (evt) {
  7466. 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) {
  7467. var index = _this._keys.indexOf(evt.keyCode);
  7468. if (index === -1) {
  7469. _this._keys.push(evt.keyCode);
  7470. }
  7471. if (evt.preventDefault) {
  7472. if (!noPreventDefault) {
  7473. evt.preventDefault();
  7474. }
  7475. }
  7476. }
  7477. };
  7478. this._onKeyUp = function (evt) {
  7479. 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) {
  7480. var index = _this._keys.indexOf(evt.keyCode);
  7481. if (index >= 0) {
  7482. _this._keys.splice(index, 1);
  7483. }
  7484. if (evt.preventDefault) {
  7485. if (!noPreventDefault) {
  7486. evt.preventDefault();
  7487. }
  7488. }
  7489. }
  7490. };
  7491. this._onLostFocus = function () {
  7492. _this._keys = [];
  7493. pointerId = null;
  7494. };
  7495. this._onGestureStart = function (e) {
  7496. if (window.MSGesture === undefined) {
  7497. return;
  7498. }
  7499. if (!_this._MSGestureHandler) {
  7500. _this._MSGestureHandler = new MSGesture();
  7501. _this._MSGestureHandler.target = element;
  7502. }
  7503. _this._MSGestureHandler.addPointer(e.pointerId);
  7504. };
  7505. this._onGesture = function (e) {
  7506. _this.radius *= e.scale;
  7507. if (e.preventDefault) {
  7508. if (!noPreventDefault) {
  7509. e.stopPropagation();
  7510. e.preventDefault();
  7511. }
  7512. }
  7513. };
  7514. this._reset = function () {
  7515. _this._keys = [];
  7516. _this.inertialAlphaOffset = 0;
  7517. _this.inertialBetaOffset = 0;
  7518. _this.inertialRadiusOffset = 0;
  7519. previousPosition = null;
  7520. pointerId = null;
  7521. };
  7522. this._touchStart = function (event) {
  7523. if (event.touches.length === 2) {
  7524. //-- start pinch if two fingers on the screen
  7525. pinchStarted = true;
  7526. _this._pinchStart(event);
  7527. }
  7528. };
  7529. this._touchMove = function (event) {
  7530. if (pinchStarted) {
  7531. //-- make scaling
  7532. _this._pinchMove(event);
  7533. }
  7534. };
  7535. this._touchEnd = function (event) {
  7536. if (pinchStarted) {
  7537. //-- end of pinch
  7538. _this._pinchEnd(event);
  7539. }
  7540. };
  7541. this._pinchStart = function (event) {
  7542. // save origin touch point
  7543. pinchPointX1 = event.touches[0].clientX;
  7544. pinchPointX2 = event.touches[1].clientX;
  7545. // block the camera
  7546. // if not it rotate around target during pinch
  7547. pinchStarted = true;
  7548. };
  7549. this._pinchMove = function (event) {
  7550. // variable for new camera's radius
  7551. var delta = 0;
  7552. // variables to know if pinch open or pinch close
  7553. var direction = 1;
  7554. var distanceXOrigine, distanceXNow;
  7555. if (event.touches.length !== 2)
  7556. return;
  7557. // calculate absolute distances of the two fingers
  7558. distanceXOrigine = Math.abs(pinchPointX1 - pinchPointX2);
  7559. distanceXNow = Math.abs(event.touches[0].clientX - event.touches[1].clientX);
  7560. // if distanceXNow < distanceXOrigine -> pinch close so direction = -1
  7561. if (distanceXNow < distanceXOrigine) {
  7562. direction = -1;
  7563. }
  7564. // calculate new radius
  7565. delta = (_this.pinchPrecision / (_this.wheelPrecision * 40)) * direction;
  7566. // set new radius
  7567. _this.inertialRadiusOffset -= delta;
  7568. // save origin touch point
  7569. pinchPointX1 = event.touches[0].clientX;
  7570. pinchPointX2 = event.touches[1].clientX;
  7571. };
  7572. this._pinchEnd = function (event) {
  7573. // cancel pinch and deblock camera rotation
  7574. pinchStarted = false;
  7575. };
  7576. }
  7577. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  7578. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  7579. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  7580. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  7581. element.addEventListener("mousemove", this._onMouseMove, false);
  7582. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  7583. element.addEventListener("MSGestureChange", this._onGesture, false);
  7584. element.addEventListener('mousewheel', this._wheel, false);
  7585. element.addEventListener('DOMMouseScroll', this._wheel, false);
  7586. // pinch
  7587. element.addEventListener('touchstart', this._touchStart, false);
  7588. element.addEventListener('touchmove', this._touchMove, false);
  7589. element.addEventListener('touchend', this._touchEnd, false);
  7590. BABYLON.Tools.RegisterTopRootEvents([
  7591. { name: "keydown", handler: this._onKeyDown },
  7592. { name: "keyup", handler: this._onKeyUp },
  7593. { name: "blur", handler: this._onLostFocus }
  7594. ]);
  7595. };
  7596. ArcRotateCamera.prototype.detachControl = function (element) {
  7597. if (this._attachedElement != element) {
  7598. return;
  7599. }
  7600. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  7601. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  7602. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  7603. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  7604. element.removeEventListener("mousemove", this._onMouseMove);
  7605. element.removeEventListener("MSPointerDown", this._onGestureStart);
  7606. element.removeEventListener("MSGestureChange", this._onGesture);
  7607. element.removeEventListener('mousewheel', this._wheel);
  7608. element.removeEventListener('DOMMouseScroll', this._wheel);
  7609. // pinch
  7610. element.removeEventListener('touchstart', this._touchStart);
  7611. element.removeEventListener('touchmove', this._touchMove);
  7612. element.removeEventListener('touchend', this._touchEnd);
  7613. BABYLON.Tools.UnregisterTopRootEvents([
  7614. { name: "keydown", handler: this._onKeyDown },
  7615. { name: "keyup", handler: this._onKeyUp },
  7616. { name: "blur", handler: this._onLostFocus }
  7617. ]);
  7618. this._MSGestureHandler = null;
  7619. this._attachedElement = null;
  7620. if (this._reset) {
  7621. this._reset();
  7622. }
  7623. };
  7624. ArcRotateCamera.prototype._update = function () {
  7625. for (var index = 0; index < this._keys.length; index++) {
  7626. var keyCode = this._keys[index];
  7627. if (this.keysLeft.indexOf(keyCode) !== -1) {
  7628. this.inertialAlphaOffset -= 0.01;
  7629. }
  7630. else if (this.keysUp.indexOf(keyCode) !== -1) {
  7631. this.inertialBetaOffset -= 0.01;
  7632. }
  7633. else if (this.keysRight.indexOf(keyCode) !== -1) {
  7634. this.inertialAlphaOffset += 0.01;
  7635. }
  7636. else if (this.keysDown.indexOf(keyCode) !== -1) {
  7637. this.inertialBetaOffset += 0.01;
  7638. }
  7639. }
  7640. // Inertia
  7641. if (this.inertialAlphaOffset != 0 || this.inertialBetaOffset != 0 || this.inertialRadiusOffset != 0) {
  7642. this.alpha += this.inertialAlphaOffset;
  7643. this.beta += this.inertialBetaOffset;
  7644. this.radius -= this.inertialRadiusOffset;
  7645. this.inertialAlphaOffset *= this.inertia;
  7646. this.inertialBetaOffset *= this.inertia;
  7647. this.inertialRadiusOffset *= this.inertia;
  7648. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  7649. this.inertialAlphaOffset = 0;
  7650. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  7651. this.inertialBetaOffset = 0;
  7652. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  7653. this.inertialRadiusOffset = 0;
  7654. }
  7655. // Limits
  7656. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  7657. this.alpha = this.lowerAlphaLimit;
  7658. }
  7659. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  7660. this.alpha = this.upperAlphaLimit;
  7661. }
  7662. if (this.lowerBetaLimit && this.beta < this.lowerBetaLimit) {
  7663. this.beta = this.lowerBetaLimit;
  7664. }
  7665. if (this.upperBetaLimit && this.beta > this.upperBetaLimit) {
  7666. this.beta = this.upperBetaLimit;
  7667. }
  7668. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  7669. this.radius = this.lowerRadiusLimit;
  7670. }
  7671. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  7672. this.radius = this.upperRadiusLimit;
  7673. }
  7674. };
  7675. ArcRotateCamera.prototype.setPosition = function (position) {
  7676. var radiusv3 = position.subtract(this._getTargetPosition());
  7677. this.radius = radiusv3.length();
  7678. // Alpha
  7679. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  7680. if (radiusv3.z < 0) {
  7681. this.alpha = 2 * Math.PI - this.alpha;
  7682. }
  7683. // Beta
  7684. this.beta = Math.acos(radiusv3.y / this.radius);
  7685. };
  7686. ArcRotateCamera.prototype._getViewMatrix = function () {
  7687. // Compute
  7688. var cosa = Math.cos(this.alpha);
  7689. var sina = Math.sin(this.alpha);
  7690. var cosb = Math.cos(this.beta);
  7691. var sinb = Math.sin(this.beta);
  7692. var target = this._getTargetPosition();
  7693. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this.position);
  7694. if (this.checkCollisions) {
  7695. this._collider.radius = this.collisionRadius;
  7696. this.position.subtractToRef(this._previousPosition, this._collisionVelocity);
  7697. this.getScene()._getNewPosition(this._previousPosition, this._collisionVelocity, this._collider, 3, this._newPosition);
  7698. if (!this._newPosition.equalsWithEpsilon(this.position)) {
  7699. this.position.copyFrom(this._previousPosition);
  7700. this.alpha = this._previousAlpha;
  7701. this.beta = this._previousBeta;
  7702. this.radius = this._previousRadius;
  7703. if (this.onCollide) {
  7704. this.onCollide(this._collider.collidedMesh);
  7705. }
  7706. }
  7707. }
  7708. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._viewMatrix);
  7709. this._previousAlpha = this.alpha;
  7710. this._previousBeta = this.beta;
  7711. this._previousRadius = this.radius;
  7712. this._previousPosition.copyFrom(this.position);
  7713. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  7714. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  7715. return this._viewMatrix;
  7716. };
  7717. ArcRotateCamera.prototype.zoomOn = function (meshes) {
  7718. meshes = meshes || this.getScene().meshes;
  7719. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  7720. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  7721. this.radius = distance * this.zoomOnFactor;
  7722. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance });
  7723. };
  7724. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance) {
  7725. var meshesOrMinMaxVector;
  7726. var distance;
  7727. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  7728. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  7729. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  7730. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  7731. }
  7732. else {
  7733. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  7734. distance = meshesOrMinMaxVectorAndDistance.distance;
  7735. }
  7736. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  7737. this.maxZ = distance * 2;
  7738. };
  7739. return ArcRotateCamera;
  7740. })(BABYLON.Camera);
  7741. BABYLON.ArcRotateCamera = ArcRotateCamera;
  7742. })(BABYLON || (BABYLON = {}));
  7743. //# sourceMappingURL=babylon.arcRotateCamera.js.mapvar BABYLON;
  7744. (function (BABYLON) {
  7745. /**
  7746. * Represents a scene to be rendered by the engine.
  7747. * @see http://doc.babylonjs.com/page.php?p=21911
  7748. */
  7749. var Scene = (function () {
  7750. /**
  7751. * @constructor
  7752. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  7753. */
  7754. function Scene(engine) {
  7755. // Members
  7756. this.autoClear = true;
  7757. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  7758. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  7759. this.forceWireframe = false;
  7760. this.forcePointsCloud = false;
  7761. this.forceShowBoundingBoxes = false;
  7762. this.animationsEnabled = true;
  7763. this.cameraToUseForPointers = null; // Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position
  7764. // Fog
  7765. /**
  7766. * is fog enabled on this scene.
  7767. * @type {boolean}
  7768. */
  7769. this.fogEnabled = true;
  7770. this.fogMode = Scene.FOGMODE_NONE;
  7771. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  7772. this.fogDensity = 0.1;
  7773. this.fogStart = 0;
  7774. this.fogEnd = 1000.0;
  7775. // Lights
  7776. /**
  7777. * is shadow enabled on this scene.
  7778. * @type {boolean}
  7779. */
  7780. this.shadowsEnabled = true;
  7781. /**
  7782. * is light enabled on this scene.
  7783. * @type {boolean}
  7784. */
  7785. this.lightsEnabled = true;
  7786. /**
  7787. * All of the lights added to this scene.
  7788. * @see BABYLON.Light
  7789. * @type {BABYLON.Light[]}
  7790. */
  7791. this.lights = new Array();
  7792. // Cameras
  7793. /**
  7794. * All of the cameras added to this scene.
  7795. * @see BABYLON.Camera
  7796. * @type {BABYLON.Camera[]}
  7797. */
  7798. this.cameras = new Array();
  7799. this.activeCameras = new Array();
  7800. // Meshes
  7801. /**
  7802. * All of the (abstract) meshes added to this scene.
  7803. * @see BABYLON.AbstractMesh
  7804. * @type {BABYLON.AbstractMesh[]}
  7805. */
  7806. this.meshes = new Array();
  7807. // Geometries
  7808. this._geometries = new Array();
  7809. this.materials = new Array();
  7810. this.multiMaterials = new Array();
  7811. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  7812. // Textures
  7813. this.texturesEnabled = true;
  7814. this.textures = new Array();
  7815. // Particles
  7816. this.particlesEnabled = true;
  7817. this.particleSystems = new Array();
  7818. // Sprites
  7819. this.spritesEnabled = true;
  7820. this.spriteManagers = new Array();
  7821. // Layers
  7822. this.layers = new Array();
  7823. // Skeletons
  7824. this.skeletonsEnabled = true;
  7825. this.skeletons = new Array();
  7826. // Lens flares
  7827. this.lensFlaresEnabled = true;
  7828. this.lensFlareSystems = new Array();
  7829. // Collisions
  7830. this.collisionsEnabled = true;
  7831. this.gravity = new BABYLON.Vector3(0, -9.0, 0);
  7832. // Postprocesses
  7833. this.postProcessesEnabled = true;
  7834. // Customs render targets
  7835. this.renderTargetsEnabled = true;
  7836. this.dumpNextRenderTargets = false;
  7837. this.customRenderTargets = new Array();
  7838. // Imported meshes
  7839. this.importedMeshesFiles = new Array();
  7840. this._actionManagers = new Array();
  7841. this._meshesForIntersections = new BABYLON.SmartArray(256);
  7842. // Procedural textures
  7843. this.proceduralTexturesEnabled = true;
  7844. this._proceduralTextures = new Array();
  7845. this.soundTracks = new Array();
  7846. this._audioEnabled = true;
  7847. this._totalVertices = 0;
  7848. this._activeVertices = 0;
  7849. this._activeParticles = 0;
  7850. this._lastFrameDuration = 0;
  7851. this._evaluateActiveMeshesDuration = 0;
  7852. this._renderTargetsDuration = 0;
  7853. this._particlesDuration = 0;
  7854. this._renderDuration = 0;
  7855. this._spritesDuration = 0;
  7856. this._animationRatio = 0;
  7857. this._renderId = 0;
  7858. this._executeWhenReadyTimeoutId = -1;
  7859. this._toBeDisposed = new BABYLON.SmartArray(256);
  7860. this._onReadyCallbacks = new Array();
  7861. this._pendingData = []; //ANY
  7862. this._onBeforeRenderCallbacks = new Array();
  7863. this._onAfterRenderCallbacks = new Array();
  7864. this._activeMeshes = new BABYLON.SmartArray(256);
  7865. this._processedMaterials = new BABYLON.SmartArray(256);
  7866. this._renderTargets = new BABYLON.SmartArray(256);
  7867. this._activeParticleSystems = new BABYLON.SmartArray(256);
  7868. this._activeSkeletons = new BABYLON.SmartArray(32);
  7869. this._activeBones = 0;
  7870. this._activeAnimatables = new Array();
  7871. this._transformMatrix = BABYLON.Matrix.Zero();
  7872. this._scaledPosition = BABYLON.Vector3.Zero();
  7873. this._scaledVelocity = BABYLON.Vector3.Zero();
  7874. this._engine = engine;
  7875. engine.scenes.push(this);
  7876. this._renderingManager = new BABYLON.RenderingManager(this);
  7877. this.postProcessManager = new BABYLON.PostProcessManager(this);
  7878. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  7879. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  7880. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  7881. this.attachControl();
  7882. this._debugLayer = new BABYLON.DebugLayer(this);
  7883. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  7884. }
  7885. Object.defineProperty(Scene, "FOGMODE_NONE", {
  7886. get: function () {
  7887. return Scene._FOGMODE_NONE;
  7888. },
  7889. enumerable: true,
  7890. configurable: true
  7891. });
  7892. Object.defineProperty(Scene, "FOGMODE_EXP", {
  7893. get: function () {
  7894. return Scene._FOGMODE_EXP;
  7895. },
  7896. enumerable: true,
  7897. configurable: true
  7898. });
  7899. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  7900. get: function () {
  7901. return Scene._FOGMODE_EXP2;
  7902. },
  7903. enumerable: true,
  7904. configurable: true
  7905. });
  7906. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  7907. get: function () {
  7908. return Scene._FOGMODE_LINEAR;
  7909. },
  7910. enumerable: true,
  7911. configurable: true
  7912. });
  7913. Object.defineProperty(Scene.prototype, "debugLayer", {
  7914. // Properties
  7915. get: function () {
  7916. return this._debugLayer;
  7917. },
  7918. enumerable: true,
  7919. configurable: true
  7920. });
  7921. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  7922. /**
  7923. * The mesh that is currently under the pointer.
  7924. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  7925. */
  7926. get: function () {
  7927. return this._meshUnderPointer;
  7928. },
  7929. enumerable: true,
  7930. configurable: true
  7931. });
  7932. Object.defineProperty(Scene.prototype, "pointerX", {
  7933. /**
  7934. * Current on-screen X position of the pointer
  7935. * @return {number} X position of the pointer
  7936. */
  7937. get: function () {
  7938. return this._pointerX;
  7939. },
  7940. enumerable: true,
  7941. configurable: true
  7942. });
  7943. Object.defineProperty(Scene.prototype, "pointerY", {
  7944. /**
  7945. * Current on-screen Y position of the pointer
  7946. * @return {number} Y position of the pointer
  7947. */
  7948. get: function () {
  7949. return this._pointerY;
  7950. },
  7951. enumerable: true,
  7952. configurable: true
  7953. });
  7954. Scene.prototype.getCachedMaterial = function () {
  7955. return this._cachedMaterial;
  7956. };
  7957. Scene.prototype.getBoundingBoxRenderer = function () {
  7958. return this._boundingBoxRenderer;
  7959. };
  7960. Scene.prototype.getOutlineRenderer = function () {
  7961. return this._outlineRenderer;
  7962. };
  7963. Scene.prototype.getEngine = function () {
  7964. return this._engine;
  7965. };
  7966. Scene.prototype.getTotalVertices = function () {
  7967. return this._totalVertices;
  7968. };
  7969. Scene.prototype.getActiveVertices = function () {
  7970. return this._activeVertices;
  7971. };
  7972. Scene.prototype.getActiveParticles = function () {
  7973. return this._activeParticles;
  7974. };
  7975. Scene.prototype.getActiveBones = function () {
  7976. return this._activeBones;
  7977. };
  7978. // Stats
  7979. Scene.prototype.getLastFrameDuration = function () {
  7980. return this._lastFrameDuration;
  7981. };
  7982. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  7983. return this._evaluateActiveMeshesDuration;
  7984. };
  7985. Scene.prototype.getActiveMeshes = function () {
  7986. return this._activeMeshes;
  7987. };
  7988. Scene.prototype.getRenderTargetsDuration = function () {
  7989. return this._renderTargetsDuration;
  7990. };
  7991. Scene.prototype.getRenderDuration = function () {
  7992. return this._renderDuration;
  7993. };
  7994. Scene.prototype.getParticlesDuration = function () {
  7995. return this._particlesDuration;
  7996. };
  7997. Scene.prototype.getSpritesDuration = function () {
  7998. return this._spritesDuration;
  7999. };
  8000. Scene.prototype.getAnimationRatio = function () {
  8001. return this._animationRatio;
  8002. };
  8003. Scene.prototype.getRenderId = function () {
  8004. return this._renderId;
  8005. };
  8006. Scene.prototype.incrementRenderId = function () {
  8007. this._renderId++;
  8008. };
  8009. Scene.prototype._updatePointerPosition = function (evt) {
  8010. var canvasRect = this._engine.getRenderingCanvasClientRect();
  8011. this._pointerX = evt.clientX - canvasRect.left;
  8012. this._pointerY = evt.clientY - canvasRect.top;
  8013. if (this.cameraToUseForPointers) {
  8014. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  8015. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  8016. }
  8017. };
  8018. // Pointers handling
  8019. Scene.prototype.attachControl = function () {
  8020. var _this = this;
  8021. this._onPointerMove = function (evt) {
  8022. var canvas = _this._engine.getRenderingCanvas();
  8023. _this._updatePointerPosition(evt);
  8024. var pickResult = _this.pick(_this._pointerX, _this._pointerY, function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPointerTriggers; }, false, _this.cameraToUseForPointers);
  8025. if (pickResult.hit) {
  8026. _this._meshUnderPointer = pickResult.pickedMesh;
  8027. _this.setPointerOverMesh(pickResult.pickedMesh);
  8028. canvas.style.cursor = "pointer";
  8029. }
  8030. else {
  8031. _this.setPointerOverMesh(null);
  8032. canvas.style.cursor = "";
  8033. _this._meshUnderPointer = null;
  8034. }
  8035. };
  8036. this._onPointerDown = function (evt) {
  8037. var predicate = null;
  8038. if (!_this.onPointerDown) {
  8039. predicate = function (mesh) {
  8040. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  8041. };
  8042. }
  8043. _this._updatePointerPosition(evt);
  8044. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  8045. if (pickResult.hit) {
  8046. if (pickResult.pickedMesh.actionManager) {
  8047. switch (evt.button) {
  8048. case 0:
  8049. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  8050. break;
  8051. case 1:
  8052. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  8053. break;
  8054. case 2:
  8055. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  8056. break;
  8057. }
  8058. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  8059. }
  8060. }
  8061. if (_this.onPointerDown) {
  8062. _this.onPointerDown(evt, pickResult);
  8063. }
  8064. };
  8065. this._onKeyDown = function (evt) {
  8066. if (_this.actionManager) {
  8067. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  8068. }
  8069. };
  8070. this._onKeyUp = function (evt) {
  8071. if (_this.actionManager) {
  8072. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  8073. }
  8074. };
  8075. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  8076. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  8077. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  8078. BABYLON.Tools.RegisterTopRootEvents([
  8079. { name: "keydown", handler: this._onKeyDown },
  8080. { name: "keyup", handler: this._onKeyUp }
  8081. ]);
  8082. };
  8083. Scene.prototype.detachControl = function () {
  8084. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  8085. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  8086. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  8087. BABYLON.Tools.UnregisterTopRootEvents([
  8088. { name: "keydown", handler: this._onKeyDown },
  8089. { name: "keyup", handler: this._onKeyUp }
  8090. ]);
  8091. };
  8092. // Ready
  8093. Scene.prototype.isReady = function () {
  8094. if (this._pendingData.length > 0) {
  8095. return false;
  8096. }
  8097. for (var index = 0; index < this._geometries.length; index++) {
  8098. var geometry = this._geometries[index];
  8099. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  8100. return false;
  8101. }
  8102. }
  8103. for (index = 0; index < this.meshes.length; index++) {
  8104. var mesh = this.meshes[index];
  8105. if (!mesh.isReady()) {
  8106. return false;
  8107. }
  8108. var mat = mesh.material;
  8109. if (mat) {
  8110. if (!mat.isReady(mesh)) {
  8111. return false;
  8112. }
  8113. }
  8114. }
  8115. return true;
  8116. };
  8117. Scene.prototype.resetCachedMaterial = function () {
  8118. this._cachedMaterial = null;
  8119. };
  8120. Scene.prototype.registerBeforeRender = function (func) {
  8121. this._onBeforeRenderCallbacks.push(func);
  8122. };
  8123. Scene.prototype.unregisterBeforeRender = function (func) {
  8124. var index = this._onBeforeRenderCallbacks.indexOf(func);
  8125. if (index > -1) {
  8126. this._onBeforeRenderCallbacks.splice(index, 1);
  8127. }
  8128. };
  8129. Scene.prototype.registerAfterRender = function (func) {
  8130. this._onAfterRenderCallbacks.push(func);
  8131. };
  8132. Scene.prototype.unregisterAfterRender = function (func) {
  8133. var index = this._onAfterRenderCallbacks.indexOf(func);
  8134. if (index > -1) {
  8135. this._onAfterRenderCallbacks.splice(index, 1);
  8136. }
  8137. };
  8138. Scene.prototype._addPendingData = function (data) {
  8139. this._pendingData.push(data);
  8140. };
  8141. Scene.prototype._removePendingData = function (data) {
  8142. var index = this._pendingData.indexOf(data);
  8143. if (index !== -1) {
  8144. this._pendingData.splice(index, 1);
  8145. }
  8146. };
  8147. Scene.prototype.getWaitingItemsCount = function () {
  8148. return this._pendingData.length;
  8149. };
  8150. /**
  8151. * Registers a function to be executed when the scene is ready.
  8152. * @param {Function} func - the function to be executed.
  8153. */
  8154. Scene.prototype.executeWhenReady = function (func) {
  8155. var _this = this;
  8156. this._onReadyCallbacks.push(func);
  8157. if (this._executeWhenReadyTimeoutId !== -1) {
  8158. return;
  8159. }
  8160. this._executeWhenReadyTimeoutId = setTimeout(function () {
  8161. _this._checkIsReady();
  8162. }, 150);
  8163. };
  8164. Scene.prototype._checkIsReady = function () {
  8165. var _this = this;
  8166. if (this.isReady()) {
  8167. this._onReadyCallbacks.forEach(function (func) {
  8168. func();
  8169. });
  8170. this._onReadyCallbacks = [];
  8171. this._executeWhenReadyTimeoutId = -1;
  8172. return;
  8173. }
  8174. this._executeWhenReadyTimeoutId = setTimeout(function () {
  8175. _this._checkIsReady();
  8176. }, 150);
  8177. };
  8178. // Animations
  8179. /**
  8180. * Will start the animation sequence of a given target
  8181. * @param target - the target
  8182. * @param {number} from - from which frame should animation start
  8183. * @param {number} to - till which frame should animation run.
  8184. * @param {boolean} [loop] - should the animation loop
  8185. * @param {number} [speedRatio] - the speed in which to run the animation
  8186. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  8187. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  8188. * @return {BABYLON.Animatable} the animatable object created for this animation
  8189. * @see BABYLON.Animatable
  8190. * @see http://doc.babylonjs.com/page.php?p=22081
  8191. */
  8192. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  8193. if (speedRatio === undefined) {
  8194. speedRatio = 1.0;
  8195. }
  8196. this.stopAnimation(target);
  8197. if (!animatable) {
  8198. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  8199. }
  8200. // Local animations
  8201. if (target.animations) {
  8202. animatable.appendAnimations(target, target.animations);
  8203. }
  8204. // Children animations
  8205. if (target.getAnimatables) {
  8206. var animatables = target.getAnimatables();
  8207. for (var index = 0; index < animatables.length; index++) {
  8208. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  8209. }
  8210. }
  8211. return animatable;
  8212. };
  8213. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  8214. if (speedRatio === undefined) {
  8215. speedRatio = 1.0;
  8216. }
  8217. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  8218. return animatable;
  8219. };
  8220. Scene.prototype.getAnimatableByTarget = function (target) {
  8221. for (var index = 0; index < this._activeAnimatables.length; index++) {
  8222. if (this._activeAnimatables[index].target === target) {
  8223. return this._activeAnimatables[index];
  8224. }
  8225. }
  8226. return null;
  8227. };
  8228. /**
  8229. * Will stop the animation of the given target
  8230. * @param target - the target
  8231. * @see beginAnimation
  8232. */
  8233. Scene.prototype.stopAnimation = function (target) {
  8234. var animatable = this.getAnimatableByTarget(target);
  8235. if (animatable) {
  8236. animatable.stop();
  8237. }
  8238. };
  8239. Scene.prototype._animate = function () {
  8240. if (!this.animationsEnabled) {
  8241. return;
  8242. }
  8243. if (!this._animationStartDate) {
  8244. this._animationStartDate = BABYLON.Tools.Now;
  8245. }
  8246. // Getting time
  8247. var now = BABYLON.Tools.Now;
  8248. var delay = now - this._animationStartDate;
  8249. for (var index = 0; index < this._activeAnimatables.length; index++) {
  8250. if (!this._activeAnimatables[index]._animate(delay)) {
  8251. this._activeAnimatables.splice(index, 1);
  8252. index--;
  8253. }
  8254. }
  8255. };
  8256. // Matrix
  8257. Scene.prototype.getViewMatrix = function () {
  8258. return this._viewMatrix;
  8259. };
  8260. Scene.prototype.getProjectionMatrix = function () {
  8261. return this._projectionMatrix;
  8262. };
  8263. Scene.prototype.getTransformMatrix = function () {
  8264. return this._transformMatrix;
  8265. };
  8266. Scene.prototype.setTransformMatrix = function (view, projection) {
  8267. this._viewMatrix = view;
  8268. this._projectionMatrix = projection;
  8269. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  8270. };
  8271. // Methods
  8272. /**
  8273. * sets the active camera of the scene using its ID
  8274. * @param {string} id - the camera's ID
  8275. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  8276. * @see activeCamera
  8277. */
  8278. Scene.prototype.setActiveCameraByID = function (id) {
  8279. var camera = this.getCameraByID(id);
  8280. if (camera) {
  8281. this.activeCamera = camera;
  8282. return camera;
  8283. }
  8284. return null;
  8285. };
  8286. /**
  8287. * sets the active camera of the scene using its name
  8288. * @param {string} name - the camera's name
  8289. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  8290. * @see activeCamera
  8291. */
  8292. Scene.prototype.setActiveCameraByName = function (name) {
  8293. var camera = this.getCameraByName(name);
  8294. if (camera) {
  8295. this.activeCamera = camera;
  8296. return camera;
  8297. }
  8298. return null;
  8299. };
  8300. /**
  8301. * get a material using its id
  8302. * @param {string} the material's ID
  8303. * @return {BABYLON.Material|null} the material or null if none found.
  8304. */
  8305. Scene.prototype.getMaterialByID = function (id) {
  8306. for (var index = 0; index < this.materials.length; index++) {
  8307. if (this.materials[index].id === id) {
  8308. return this.materials[index];
  8309. }
  8310. }
  8311. return null;
  8312. };
  8313. /**
  8314. * get a material using its name
  8315. * @param {string} the material's name
  8316. * @return {BABYLON.Material|null} the material or null if none found.
  8317. */
  8318. Scene.prototype.getMaterialByName = function (name) {
  8319. for (var index = 0; index < this.materials.length; index++) {
  8320. if (this.materials[index].name === name) {
  8321. return this.materials[index];
  8322. }
  8323. }
  8324. return null;
  8325. };
  8326. Scene.prototype.getCameraByID = function (id) {
  8327. for (var index = 0; index < this.cameras.length; index++) {
  8328. if (this.cameras[index].id === id) {
  8329. return this.cameras[index];
  8330. }
  8331. }
  8332. return null;
  8333. };
  8334. /**
  8335. * get a camera using its name
  8336. * @param {string} the camera's name
  8337. * @return {BABYLON.Camera|null} the camera or null if none found.
  8338. */
  8339. Scene.prototype.getCameraByName = function (name) {
  8340. for (var index = 0; index < this.cameras.length; index++) {
  8341. if (this.cameras[index].name === name) {
  8342. return this.cameras[index];
  8343. }
  8344. }
  8345. return null;
  8346. };
  8347. /**
  8348. * get a light node using its name
  8349. * @param {string} the light's name
  8350. * @return {BABYLON.Light|null} the light or null if none found.
  8351. */
  8352. Scene.prototype.getLightByName = function (name) {
  8353. for (var index = 0; index < this.lights.length; index++) {
  8354. if (this.lights[index].name === name) {
  8355. return this.lights[index];
  8356. }
  8357. }
  8358. return null;
  8359. };
  8360. /**
  8361. * get a light node using its ID
  8362. * @param {string} the light's id
  8363. * @return {BABYLON.Light|null} the light or null if none found.
  8364. */
  8365. Scene.prototype.getLightByID = function (id) {
  8366. for (var index = 0; index < this.lights.length; index++) {
  8367. if (this.lights[index].id === id) {
  8368. return this.lights[index];
  8369. }
  8370. }
  8371. return null;
  8372. };
  8373. /**
  8374. * get a geometry using its ID
  8375. * @param {string} the geometry's id
  8376. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  8377. */
  8378. Scene.prototype.getGeometryByID = function (id) {
  8379. for (var index = 0; index < this._geometries.length; index++) {
  8380. if (this._geometries[index].id === id) {
  8381. return this._geometries[index];
  8382. }
  8383. }
  8384. return null;
  8385. };
  8386. /**
  8387. * add a new geometry to this scene.
  8388. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  8389. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  8390. * @return {boolean} was the geometry added or not
  8391. */
  8392. Scene.prototype.pushGeometry = function (geometry, force) {
  8393. if (!force && this.getGeometryByID(geometry.id)) {
  8394. return false;
  8395. }
  8396. this._geometries.push(geometry);
  8397. return true;
  8398. };
  8399. Scene.prototype.getGeometries = function () {
  8400. return this._geometries;
  8401. };
  8402. /**
  8403. * Get a the first added mesh found of a given ID
  8404. * @param {string} id - the id to search for
  8405. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  8406. */
  8407. Scene.prototype.getMeshByID = function (id) {
  8408. for (var index = 0; index < this.meshes.length; index++) {
  8409. if (this.meshes[index].id === id) {
  8410. return this.meshes[index];
  8411. }
  8412. }
  8413. return null;
  8414. };
  8415. /**
  8416. * Get a the last added mesh found of a given ID
  8417. * @param {string} id - the id to search for
  8418. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  8419. */
  8420. Scene.prototype.getLastMeshByID = function (id) {
  8421. for (var index = this.meshes.length - 1; index >= 0; index--) {
  8422. if (this.meshes[index].id === id) {
  8423. return this.meshes[index];
  8424. }
  8425. }
  8426. return null;
  8427. };
  8428. /**
  8429. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  8430. * @param {string} id - the id to search for
  8431. * @return {BABYLON.Node|null} the node found or null if not found at all.
  8432. */
  8433. Scene.prototype.getLastEntryByID = function (id) {
  8434. for (var index = this.meshes.length - 1; index >= 0; index--) {
  8435. if (this.meshes[index].id === id) {
  8436. return this.meshes[index];
  8437. }
  8438. }
  8439. for (index = this.cameras.length - 1; index >= 0; index--) {
  8440. if (this.cameras[index].id === id) {
  8441. return this.cameras[index];
  8442. }
  8443. }
  8444. for (index = this.lights.length - 1; index >= 0; index--) {
  8445. if (this.lights[index].id === id) {
  8446. return this.lights[index];
  8447. }
  8448. }
  8449. return null;
  8450. };
  8451. Scene.prototype.getNodeByName = function (name) {
  8452. var mesh = this.getMeshByName(name);
  8453. if (mesh) {
  8454. return mesh;
  8455. }
  8456. var light = this.getLightByName(name);
  8457. if (light) {
  8458. return light;
  8459. }
  8460. return this.getCameraByName(name);
  8461. };
  8462. Scene.prototype.getMeshByName = function (name) {
  8463. for (var index = 0; index < this.meshes.length; index++) {
  8464. if (this.meshes[index].name === name) {
  8465. return this.meshes[index];
  8466. }
  8467. }
  8468. return null;
  8469. };
  8470. Scene.prototype.getSoundByName = function (name) {
  8471. for (var index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  8472. if (this.mainSoundTrack.soundCollection[index].name === name) {
  8473. return this.mainSoundTrack.soundCollection[index];
  8474. }
  8475. }
  8476. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  8477. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  8478. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  8479. return this.soundTracks[sdIndex].soundCollection[index];
  8480. }
  8481. }
  8482. }
  8483. return null;
  8484. };
  8485. Scene.prototype.getLastSkeletonByID = function (id) {
  8486. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  8487. if (this.skeletons[index].id === id) {
  8488. return this.skeletons[index];
  8489. }
  8490. }
  8491. return null;
  8492. };
  8493. Scene.prototype.getSkeletonById = function (id) {
  8494. for (var index = 0; index < this.skeletons.length; index++) {
  8495. if (this.skeletons[index].id === id) {
  8496. return this.skeletons[index];
  8497. }
  8498. }
  8499. return null;
  8500. };
  8501. Scene.prototype.getSkeletonByName = function (name) {
  8502. for (var index = 0; index < this.skeletons.length; index++) {
  8503. if (this.skeletons[index].name === name) {
  8504. return this.skeletons[index];
  8505. }
  8506. }
  8507. return null;
  8508. };
  8509. Scene.prototype.isActiveMesh = function (mesh) {
  8510. return (this._activeMeshes.indexOf(mesh) !== -1);
  8511. };
  8512. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  8513. if (mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  8514. var material = subMesh.getMaterial();
  8515. if (mesh.showSubMeshesBoundingBox) {
  8516. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  8517. }
  8518. if (material) {
  8519. // Render targets
  8520. if (material.getRenderTargetTextures) {
  8521. if (this._processedMaterials.indexOf(material) === -1) {
  8522. this._processedMaterials.push(material);
  8523. this._renderTargets.concat(material.getRenderTargetTextures());
  8524. }
  8525. }
  8526. // Dispatch
  8527. this._activeVertices += subMesh.indexCount;
  8528. this._renderingManager.dispatch(subMesh);
  8529. }
  8530. }
  8531. };
  8532. Scene.prototype._evaluateActiveMeshes = function () {
  8533. this.activeCamera._activeMeshes.reset();
  8534. this._activeMeshes.reset();
  8535. this._renderingManager.reset();
  8536. this._processedMaterials.reset();
  8537. this._activeParticleSystems.reset();
  8538. this._activeSkeletons.reset();
  8539. this._boundingBoxRenderer.reset();
  8540. if (!this._frustumPlanes) {
  8541. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  8542. }
  8543. else {
  8544. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  8545. }
  8546. // Meshes
  8547. var meshes;
  8548. var len;
  8549. if (this._selectionOctree) {
  8550. var selection = this._selectionOctree.select(this._frustumPlanes);
  8551. meshes = selection.data;
  8552. len = selection.length;
  8553. }
  8554. else {
  8555. len = this.meshes.length;
  8556. meshes = this.meshes;
  8557. }
  8558. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  8559. var mesh = meshes[meshIndex];
  8560. if (mesh.isBlocked) {
  8561. continue;
  8562. }
  8563. this._totalVertices += mesh.getTotalVertices();
  8564. if (!mesh.isReady()) {
  8565. continue;
  8566. }
  8567. mesh.computeWorldMatrix();
  8568. // Intersections
  8569. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  8570. this._meshesForIntersections.pushNoDuplicate(mesh);
  8571. }
  8572. // Switch to current LOD
  8573. var meshLOD = mesh.getLOD(this.activeCamera);
  8574. if (!meshLOD) {
  8575. continue;
  8576. }
  8577. mesh._preActivate();
  8578. if (mesh.isEnabled() && mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  8579. this._activeMeshes.push(mesh);
  8580. this.activeCamera._activeMeshes.push(mesh);
  8581. mesh._activate(this._renderId);
  8582. this._activeMesh(meshLOD);
  8583. }
  8584. }
  8585. // Particle systems
  8586. var beforeParticlesDate = BABYLON.Tools.Now;
  8587. if (this.particlesEnabled) {
  8588. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  8589. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  8590. var particleSystem = this.particleSystems[particleIndex];
  8591. if (!particleSystem.isStarted()) {
  8592. continue;
  8593. }
  8594. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  8595. this._activeParticleSystems.push(particleSystem);
  8596. particleSystem.animate();
  8597. }
  8598. }
  8599. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  8600. }
  8601. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  8602. };
  8603. Scene.prototype._activeMesh = function (mesh) {
  8604. if (mesh.skeleton && this.skeletonsEnabled) {
  8605. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  8606. }
  8607. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  8608. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  8609. }
  8610. if (mesh && mesh.subMeshes) {
  8611. // Submeshes Octrees
  8612. var len;
  8613. var subMeshes;
  8614. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  8615. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  8616. len = intersections.length;
  8617. subMeshes = intersections.data;
  8618. }
  8619. else {
  8620. subMeshes = mesh.subMeshes;
  8621. len = subMeshes.length;
  8622. }
  8623. for (var subIndex = 0; subIndex < len; subIndex++) {
  8624. var subMesh = subMeshes[subIndex];
  8625. this._evaluateSubMesh(subMesh, mesh);
  8626. }
  8627. }
  8628. };
  8629. Scene.prototype.updateTransformMatrix = function (force) {
  8630. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  8631. };
  8632. Scene.prototype._renderForCamera = function (camera) {
  8633. var engine = this._engine;
  8634. this.activeCamera = camera;
  8635. if (!this.activeCamera)
  8636. throw new Error("Active camera not set");
  8637. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  8638. // Viewport
  8639. engine.setViewport(this.activeCamera.viewport);
  8640. // Camera
  8641. this._renderId++;
  8642. this.updateTransformMatrix();
  8643. if (this.beforeCameraRender) {
  8644. this.beforeCameraRender(this.activeCamera);
  8645. }
  8646. // Meshes
  8647. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  8648. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  8649. this._evaluateActiveMeshes();
  8650. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  8651. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  8652. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  8653. var skeleton = this._activeSkeletons.data[skeletonIndex];
  8654. skeleton.prepare();
  8655. }
  8656. // Render targets
  8657. var beforeRenderTargetDate = BABYLON.Tools.Now;
  8658. if (this.renderTargetsEnabled) {
  8659. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  8660. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  8661. var renderTarget = this._renderTargets.data[renderIndex];
  8662. if (renderTarget._shouldRender()) {
  8663. this._renderId++;
  8664. renderTarget.render(false, this.dumpNextRenderTargets);
  8665. }
  8666. }
  8667. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  8668. this._renderId++;
  8669. }
  8670. if (this._renderTargets.length > 0) {
  8671. engine.restoreDefaultFramebuffer();
  8672. }
  8673. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  8674. // Prepare Frame
  8675. this.postProcessManager._prepareFrame();
  8676. var beforeRenderDate = BABYLON.Tools.Now;
  8677. // Backgrounds
  8678. if (this.layers.length) {
  8679. engine.setDepthBuffer(false);
  8680. var layerIndex;
  8681. var layer;
  8682. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  8683. layer = this.layers[layerIndex];
  8684. if (layer.isBackground) {
  8685. layer.render();
  8686. }
  8687. }
  8688. engine.setDepthBuffer(true);
  8689. }
  8690. // Render
  8691. BABYLON.Tools.StartPerformanceCounter("Main render");
  8692. this._renderingManager.render(null, null, true, true);
  8693. BABYLON.Tools.EndPerformanceCounter("Main render");
  8694. // Bounding boxes
  8695. this._boundingBoxRenderer.render();
  8696. // Lens flares
  8697. if (this.lensFlaresEnabled) {
  8698. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  8699. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  8700. this.lensFlareSystems[lensFlareSystemIndex].render();
  8701. }
  8702. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  8703. }
  8704. // Foregrounds
  8705. if (this.layers.length) {
  8706. engine.setDepthBuffer(false);
  8707. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  8708. layer = this.layers[layerIndex];
  8709. if (!layer.isBackground) {
  8710. layer.render();
  8711. }
  8712. }
  8713. engine.setDepthBuffer(true);
  8714. }
  8715. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  8716. // Finalize frame
  8717. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  8718. // Update camera
  8719. this.activeCamera._updateFromScene();
  8720. // Reset some special arrays
  8721. this._renderTargets.reset();
  8722. if (this.afterCameraRender) {
  8723. this.afterCameraRender(this.activeCamera);
  8724. }
  8725. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  8726. };
  8727. Scene.prototype._processSubCameras = function (camera) {
  8728. if (camera.subCameras.length === 0) {
  8729. this._renderForCamera(camera);
  8730. return;
  8731. }
  8732. for (var index = 0; index < camera.subCameras.length; index++) {
  8733. this._renderForCamera(camera.subCameras[index]);
  8734. }
  8735. this.activeCamera = camera;
  8736. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  8737. // Update camera
  8738. this.activeCamera._updateFromScene();
  8739. };
  8740. Scene.prototype._checkIntersections = function () {
  8741. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  8742. var sourceMesh = this._meshesForIntersections.data[index];
  8743. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  8744. var action = sourceMesh.actionManager.actions[actionIndex];
  8745. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  8746. var parameters = action.getTriggerParameter();
  8747. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  8748. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  8749. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  8750. if (areIntersecting && currentIntersectionInProgress === -1) {
  8751. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  8752. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  8753. sourceMesh._intersectionsInProgress.push(otherMesh);
  8754. }
  8755. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  8756. sourceMesh._intersectionsInProgress.push(otherMesh);
  8757. }
  8758. }
  8759. else if (!areIntersecting && currentIntersectionInProgress > -1 && action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  8760. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  8761. var indexOfOther = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  8762. if (indexOfOther > -1) {
  8763. sourceMesh._intersectionsInProgress.splice(indexOfOther, 1);
  8764. }
  8765. }
  8766. }
  8767. }
  8768. }
  8769. };
  8770. Scene.prototype.render = function () {
  8771. var startDate = BABYLON.Tools.Now;
  8772. this._particlesDuration = 0;
  8773. this._spritesDuration = 0;
  8774. this._activeParticles = 0;
  8775. this._renderDuration = 0;
  8776. this._renderTargetsDuration = 0;
  8777. this._evaluateActiveMeshesDuration = 0;
  8778. this._totalVertices = 0;
  8779. this._activeVertices = 0;
  8780. this._activeBones = 0;
  8781. this.getEngine().resetDrawCalls();
  8782. this._meshesForIntersections.reset();
  8783. this.resetCachedMaterial();
  8784. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  8785. // Actions
  8786. if (this.actionManager) {
  8787. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  8788. }
  8789. // Before render
  8790. if (this.beforeRender) {
  8791. this.beforeRender();
  8792. }
  8793. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  8794. this._onBeforeRenderCallbacks[callbackIndex]();
  8795. }
  8796. // Animations
  8797. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  8798. this._animationRatio = deltaTime * (60.0 / 1000.0);
  8799. this._animate();
  8800. // Physics
  8801. if (this._physicsEngine) {
  8802. BABYLON.Tools.StartPerformanceCounter("Physics");
  8803. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  8804. BABYLON.Tools.EndPerformanceCounter("Physics");
  8805. }
  8806. // Customs render targets
  8807. var beforeRenderTargetDate = BABYLON.Tools.Now;
  8808. var engine = this.getEngine();
  8809. var currentActiveCamera = this.activeCamera;
  8810. if (this.renderTargetsEnabled) {
  8811. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  8812. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  8813. var renderTarget = this.customRenderTargets[customIndex];
  8814. if (renderTarget._shouldRender()) {
  8815. this._renderId++;
  8816. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  8817. if (!this.activeCamera)
  8818. throw new Error("Active camera not set");
  8819. // Viewport
  8820. engine.setViewport(this.activeCamera.viewport);
  8821. // Camera
  8822. this.updateTransformMatrix();
  8823. renderTarget.render(false, this.dumpNextRenderTargets);
  8824. }
  8825. }
  8826. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  8827. this._renderId++;
  8828. }
  8829. if (this.customRenderTargets.length > 0) {
  8830. engine.restoreDefaultFramebuffer();
  8831. }
  8832. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  8833. this.activeCamera = currentActiveCamera;
  8834. // Procedural textures
  8835. if (this.proceduralTexturesEnabled) {
  8836. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  8837. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  8838. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  8839. if (proceduralTexture._shouldRender()) {
  8840. proceduralTexture.render();
  8841. }
  8842. }
  8843. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  8844. }
  8845. // Clear
  8846. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  8847. // Shadows
  8848. if (this.shadowsEnabled) {
  8849. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  8850. var light = this.lights[lightIndex];
  8851. var shadowGenerator = light.getShadowGenerator();
  8852. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  8853. this._renderTargets.push(shadowGenerator.getShadowMap());
  8854. }
  8855. }
  8856. }
  8857. // Depth renderer
  8858. if (this._depthRenderer) {
  8859. this._renderTargets.push(this._depthRenderer.getDepthMap());
  8860. }
  8861. // RenderPipeline
  8862. this.postProcessRenderPipelineManager.update();
  8863. // Multi-cameras?
  8864. if (this.activeCameras.length > 0) {
  8865. var currentRenderId = this._renderId;
  8866. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  8867. this._renderId = currentRenderId;
  8868. this._processSubCameras(this.activeCameras[cameraIndex]);
  8869. }
  8870. }
  8871. else {
  8872. if (!this.activeCamera) {
  8873. throw new Error("No camera defined");
  8874. }
  8875. this._processSubCameras(this.activeCamera);
  8876. }
  8877. // Intersection checks
  8878. this._checkIntersections();
  8879. // Update the audio listener attached to the camera
  8880. this._updateAudioParameters();
  8881. // After render
  8882. if (this.afterRender) {
  8883. this.afterRender();
  8884. }
  8885. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  8886. this._onAfterRenderCallbacks[callbackIndex]();
  8887. }
  8888. for (var index = 0; index < this._toBeDisposed.length; index++) {
  8889. this._toBeDisposed.data[index].dispose();
  8890. this._toBeDisposed[index] = null;
  8891. }
  8892. this._toBeDisposed.reset();
  8893. if (this.dumpNextRenderTargets) {
  8894. this.dumpNextRenderTargets = false;
  8895. }
  8896. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  8897. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  8898. };
  8899. Scene.prototype._updateAudioParameters = function () {
  8900. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 0)) {
  8901. return;
  8902. }
  8903. var listeningCamera;
  8904. var audioEngine = BABYLON.Engine.audioEngine;
  8905. if (this.activeCameras.length > 0) {
  8906. listeningCamera = this.activeCameras[0];
  8907. }
  8908. else {
  8909. listeningCamera = this.activeCamera;
  8910. }
  8911. if (listeningCamera && audioEngine.canUseWebAudio) {
  8912. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  8913. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  8914. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  8915. cameraDirection.normalize();
  8916. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  8917. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  8918. var sound = this.mainSoundTrack.soundCollection[i];
  8919. if (sound.useCustomAttenuation) {
  8920. sound.updateDistanceFromListener();
  8921. }
  8922. }
  8923. for (i = 0; i < this.soundTracks.length; i++) {
  8924. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  8925. sound = this.soundTracks[i].soundCollection[j];
  8926. if (sound.useCustomAttenuation) {
  8927. sound.updateDistanceFromListener();
  8928. }
  8929. }
  8930. }
  8931. }
  8932. };
  8933. Object.defineProperty(Scene.prototype, "audioEnabled", {
  8934. get: function () {
  8935. return this._audioEnabled;
  8936. },
  8937. set: function (value) {
  8938. this._audioEnabled = value;
  8939. if (this._audioEnabled) {
  8940. this._enableAudio();
  8941. }
  8942. else {
  8943. this._disableAudio();
  8944. }
  8945. },
  8946. enumerable: true,
  8947. configurable: true
  8948. });
  8949. Scene.prototype._disableAudio = function () {
  8950. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  8951. this.mainSoundTrack.soundCollection[i].pause();
  8952. }
  8953. for (i = 0; i < this.soundTracks.length; i++) {
  8954. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  8955. this.soundTracks[i].soundCollection[j].pause();
  8956. }
  8957. }
  8958. };
  8959. Scene.prototype._enableAudio = function () {
  8960. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  8961. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  8962. this.mainSoundTrack.soundCollection[i].play();
  8963. }
  8964. }
  8965. for (i = 0; i < this.soundTracks.length; i++) {
  8966. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  8967. if (this.soundTracks[i].soundCollection[j].isPaused) {
  8968. this.soundTracks[i].soundCollection[j].play();
  8969. }
  8970. }
  8971. }
  8972. };
  8973. Scene.prototype.enableDepthRenderer = function () {
  8974. if (this._depthRenderer) {
  8975. return this._depthRenderer;
  8976. }
  8977. this._depthRenderer = new BABYLON.DepthRenderer(this);
  8978. return this._depthRenderer;
  8979. };
  8980. Scene.prototype.disableDepthRenderer = function () {
  8981. if (!this._depthRenderer) {
  8982. return;
  8983. }
  8984. this._depthRenderer.dispose();
  8985. this._depthRenderer = null;
  8986. };
  8987. Scene.prototype.dispose = function () {
  8988. this.beforeRender = null;
  8989. this.afterRender = null;
  8990. this.skeletons = [];
  8991. this._boundingBoxRenderer.dispose();
  8992. if (this._depthRenderer) {
  8993. this._depthRenderer.dispose();
  8994. }
  8995. // Debug layer
  8996. this.debugLayer.hide();
  8997. // Events
  8998. if (this.onDispose) {
  8999. this.onDispose();
  9000. }
  9001. this._onBeforeRenderCallbacks = [];
  9002. this._onAfterRenderCallbacks = [];
  9003. this.detachControl();
  9004. // Release sounds & sounds tracks
  9005. this.disposeSounds();
  9006. // Detach cameras
  9007. var canvas = this._engine.getRenderingCanvas();
  9008. var index;
  9009. for (index = 0; index < this.cameras.length; index++) {
  9010. this.cameras[index].detachControl(canvas);
  9011. }
  9012. while (this.lights.length) {
  9013. this.lights[0].dispose();
  9014. }
  9015. while (this.meshes.length) {
  9016. this.meshes[0].dispose(true);
  9017. }
  9018. while (this.cameras.length) {
  9019. this.cameras[0].dispose();
  9020. }
  9021. while (this.materials.length) {
  9022. this.materials[0].dispose();
  9023. }
  9024. while (this.particleSystems.length) {
  9025. this.particleSystems[0].dispose();
  9026. }
  9027. while (this.spriteManagers.length) {
  9028. this.spriteManagers[0].dispose();
  9029. }
  9030. while (this.layers.length) {
  9031. this.layers[0].dispose();
  9032. }
  9033. while (this.textures.length) {
  9034. this.textures[0].dispose();
  9035. }
  9036. // Post-processes
  9037. this.postProcessManager.dispose();
  9038. // Physics
  9039. if (this._physicsEngine) {
  9040. this.disablePhysicsEngine();
  9041. }
  9042. // Remove from engine
  9043. index = this._engine.scenes.indexOf(this);
  9044. if (index > -1) {
  9045. this._engine.scenes.splice(index, 1);
  9046. }
  9047. this._engine.wipeCaches();
  9048. };
  9049. // Release sounds & sounds tracks
  9050. Scene.prototype.disposeSounds = function () {
  9051. this.mainSoundTrack.dispose();
  9052. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  9053. this.soundTracks[scIndex].dispose();
  9054. }
  9055. };
  9056. // Collisions
  9057. Scene.prototype._getNewPosition = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  9058. if (excludedMesh === void 0) { excludedMesh = null; }
  9059. position.divideToRef(collider.radius, this._scaledPosition);
  9060. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9061. collider.retry = 0;
  9062. collider.initialVelocity = this._scaledVelocity;
  9063. collider.initialPosition = this._scaledPosition;
  9064. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, finalPosition, excludedMesh);
  9065. finalPosition.multiplyInPlace(collider.radius);
  9066. };
  9067. Scene.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  9068. if (excludedMesh === void 0) { excludedMesh = null; }
  9069. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  9070. if (collider.retry >= maximumRetry) {
  9071. finalPosition.copyFrom(position);
  9072. return;
  9073. }
  9074. collider._initialize(position, velocity, closeDistance);
  9075. for (var index = 0; index < this.meshes.length; index++) {
  9076. var mesh = this.meshes[index];
  9077. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  9078. mesh._checkCollision(collider);
  9079. }
  9080. }
  9081. if (!collider.collisionFound) {
  9082. position.addToRef(velocity, finalPosition);
  9083. return;
  9084. }
  9085. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  9086. collider._getResponse(position, velocity);
  9087. }
  9088. if (velocity.length() <= closeDistance) {
  9089. finalPosition.copyFrom(position);
  9090. return;
  9091. }
  9092. collider.retry++;
  9093. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  9094. };
  9095. // Octrees
  9096. Scene.prototype.getWorldExtends = function () {
  9097. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9098. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  9099. for (var index = 0; index < this.meshes.length; index++) {
  9100. var mesh = this.meshes[index];
  9101. mesh.computeWorldMatrix(true);
  9102. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  9103. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  9104. BABYLON.Tools.CheckExtends(minBox, min, max);
  9105. BABYLON.Tools.CheckExtends(maxBox, min, max);
  9106. }
  9107. return {
  9108. min: min,
  9109. max: max
  9110. };
  9111. };
  9112. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  9113. if (maxCapacity === void 0) { maxCapacity = 64; }
  9114. if (maxDepth === void 0) { maxDepth = 2; }
  9115. if (!this._selectionOctree) {
  9116. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  9117. }
  9118. var worldExtends = this.getWorldExtends();
  9119. // Update octree
  9120. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  9121. return this._selectionOctree;
  9122. };
  9123. // Picking
  9124. Scene.prototype.createPickingRay = function (x, y, world, camera) {
  9125. var engine = this._engine;
  9126. if (!camera) {
  9127. if (!this.activeCamera)
  9128. throw new Error("Active camera not set");
  9129. camera = this.activeCamera;
  9130. }
  9131. var cameraViewport = camera.viewport;
  9132. var viewport = cameraViewport.toGlobal(engine);
  9133. // Moving coordinates to local viewport world
  9134. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  9135. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  9136. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  9137. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  9138. };
  9139. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  9140. var pickingInfo = null;
  9141. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  9142. var mesh = this.meshes[meshIndex];
  9143. if (predicate) {
  9144. if (!predicate(mesh)) {
  9145. continue;
  9146. }
  9147. }
  9148. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  9149. continue;
  9150. }
  9151. var world = mesh.getWorldMatrix();
  9152. var ray = rayFunction(world);
  9153. var result = mesh.intersects(ray, fastCheck);
  9154. if (!result || !result.hit)
  9155. continue;
  9156. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  9157. continue;
  9158. pickingInfo = result;
  9159. if (fastCheck) {
  9160. break;
  9161. }
  9162. }
  9163. return pickingInfo || new BABYLON.PickingInfo();
  9164. };
  9165. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  9166. var _this = this;
  9167. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  9168. /// <param name="x">X position on screen</param>
  9169. /// <param name="y">Y position on screen</param>
  9170. /// <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>
  9171. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  9172. /// <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>
  9173. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  9174. };
  9175. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  9176. var _this = this;
  9177. return this._internalPick(function (world) {
  9178. if (!_this._pickWithRayInverseMatrix) {
  9179. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  9180. }
  9181. world.invertToRef(_this._pickWithRayInverseMatrix);
  9182. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  9183. }, predicate, fastCheck);
  9184. };
  9185. Scene.prototype.setPointerOverMesh = function (mesh) {
  9186. if (this._pointerOverMesh === mesh) {
  9187. return;
  9188. }
  9189. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  9190. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  9191. }
  9192. this._pointerOverMesh = mesh;
  9193. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  9194. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  9195. }
  9196. };
  9197. Scene.prototype.getPointerOverMesh = function () {
  9198. return this._pointerOverMesh;
  9199. };
  9200. // Physics
  9201. Scene.prototype.getPhysicsEngine = function () {
  9202. return this._physicsEngine;
  9203. };
  9204. Scene.prototype.enablePhysics = function (gravity, plugin) {
  9205. if (this._physicsEngine) {
  9206. return true;
  9207. }
  9208. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  9209. if (!this._physicsEngine.isSupported()) {
  9210. this._physicsEngine = null;
  9211. return false;
  9212. }
  9213. this._physicsEngine._initialize(gravity);
  9214. return true;
  9215. };
  9216. Scene.prototype.disablePhysicsEngine = function () {
  9217. if (!this._physicsEngine) {
  9218. return;
  9219. }
  9220. this._physicsEngine.dispose();
  9221. this._physicsEngine = undefined;
  9222. };
  9223. Scene.prototype.isPhysicsEnabled = function () {
  9224. return this._physicsEngine !== undefined;
  9225. };
  9226. Scene.prototype.setGravity = function (gravity) {
  9227. if (!this._physicsEngine) {
  9228. return;
  9229. }
  9230. this._physicsEngine._setGravity(gravity);
  9231. };
  9232. Scene.prototype.createCompoundImpostor = function (parts, options) {
  9233. if (parts.parts) {
  9234. options = parts;
  9235. parts = parts.parts;
  9236. }
  9237. if (!this._physicsEngine) {
  9238. return null;
  9239. }
  9240. for (var index = 0; index < parts.length; index++) {
  9241. var mesh = parts[index].mesh;
  9242. mesh._physicImpostor = parts[index].impostor;
  9243. mesh._physicsMass = options.mass / parts.length;
  9244. mesh._physicsFriction = options.friction;
  9245. mesh._physicRestitution = options.restitution;
  9246. }
  9247. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  9248. };
  9249. Scene.prototype.deleteCompoundImpostor = function (compound) {
  9250. for (var index = 0; index < compound.parts.length; index++) {
  9251. var mesh = compound.parts[index].mesh;
  9252. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  9253. this._physicsEngine._unregisterMesh(mesh);
  9254. }
  9255. };
  9256. // Misc.
  9257. Scene.prototype.createDefaultCameraOrLight = function () {
  9258. // Light
  9259. if (this.lights.length === 0) {
  9260. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  9261. }
  9262. // Camera
  9263. if (!this.activeCamera) {
  9264. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  9265. // Compute position
  9266. var worldExtends = this.getWorldExtends();
  9267. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  9268. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  9269. camera.setTarget(worldCenter);
  9270. this.activeCamera = camera;
  9271. }
  9272. };
  9273. // Tags
  9274. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  9275. if (tagsQuery === undefined) {
  9276. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  9277. return list;
  9278. }
  9279. var listByTags = [];
  9280. forEach = forEach || (function (item) {
  9281. return;
  9282. });
  9283. for (var i in list) {
  9284. var item = list[i];
  9285. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  9286. listByTags.push(item);
  9287. forEach(item);
  9288. }
  9289. }
  9290. return listByTags;
  9291. };
  9292. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  9293. return this._getByTags(this.meshes, tagsQuery, forEach);
  9294. };
  9295. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  9296. return this._getByTags(this.cameras, tagsQuery, forEach);
  9297. };
  9298. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  9299. return this._getByTags(this.lights, tagsQuery, forEach);
  9300. };
  9301. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  9302. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  9303. };
  9304. // Audio
  9305. Scene.prototype.switchAudioModeForHeadphones = function () {
  9306. this.mainSoundTrack.switchPanningModelToHRTF();
  9307. for (var i = 0; i < this.soundTracks.length; i++) {
  9308. this.soundTracks[i].switchPanningModelToHRTF();
  9309. }
  9310. };
  9311. Scene.prototype.switchAudioModeForNormalSpeakers = function () {
  9312. this.mainSoundTrack.switchPanningModelToEqualPower();
  9313. for (var i = 0; i < this.soundTracks.length; i++) {
  9314. this.soundTracks[i].switchPanningModelToEqualPower();
  9315. }
  9316. };
  9317. // Statics
  9318. Scene._FOGMODE_NONE = 0;
  9319. Scene._FOGMODE_EXP = 1;
  9320. Scene._FOGMODE_EXP2 = 2;
  9321. Scene._FOGMODE_LINEAR = 3;
  9322. Scene.MinDeltaTime = 1.0;
  9323. Scene.MaxDeltaTime = 1000.0;
  9324. return Scene;
  9325. })();
  9326. BABYLON.Scene = Scene;
  9327. })(BABYLON || (BABYLON = {}));
  9328. //# sourceMappingURL=babylon.scene.js.mapvar BABYLON;
  9329. (function (BABYLON) {
  9330. var VertexBuffer = (function () {
  9331. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  9332. if (engine instanceof BABYLON.Mesh) {
  9333. this._engine = engine.getScene().getEngine();
  9334. }
  9335. else {
  9336. this._engine = engine;
  9337. }
  9338. this._updatable = updatable;
  9339. this._data = data;
  9340. if (!postponeInternalCreation) {
  9341. this.create();
  9342. }
  9343. this._kind = kind;
  9344. if (stride) {
  9345. this._strideSize = stride;
  9346. return;
  9347. }
  9348. switch (kind) {
  9349. case VertexBuffer.PositionKind:
  9350. this._strideSize = 3;
  9351. break;
  9352. case VertexBuffer.NormalKind:
  9353. this._strideSize = 3;
  9354. break;
  9355. case VertexBuffer.UVKind:
  9356. this._strideSize = 2;
  9357. break;
  9358. case VertexBuffer.UV2Kind:
  9359. this._strideSize = 2;
  9360. break;
  9361. case VertexBuffer.ColorKind:
  9362. this._strideSize = 4;
  9363. break;
  9364. case VertexBuffer.MatricesIndicesKind:
  9365. this._strideSize = 4;
  9366. break;
  9367. case VertexBuffer.MatricesWeightsKind:
  9368. this._strideSize = 4;
  9369. break;
  9370. }
  9371. }
  9372. // Properties
  9373. VertexBuffer.prototype.isUpdatable = function () {
  9374. return this._updatable;
  9375. };
  9376. VertexBuffer.prototype.getData = function () {
  9377. return this._data;
  9378. };
  9379. VertexBuffer.prototype.getBuffer = function () {
  9380. return this._buffer;
  9381. };
  9382. VertexBuffer.prototype.getStrideSize = function () {
  9383. return this._strideSize;
  9384. };
  9385. // Methods
  9386. VertexBuffer.prototype.create = function (data) {
  9387. if (!data && this._buffer) {
  9388. return; // nothing to do
  9389. }
  9390. data = data || this._data;
  9391. if (!this._buffer) {
  9392. if (this._updatable) {
  9393. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  9394. }
  9395. else {
  9396. this._buffer = this._engine.createVertexBuffer(data);
  9397. }
  9398. }
  9399. if (this._updatable) {
  9400. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  9401. this._data = data;
  9402. }
  9403. };
  9404. VertexBuffer.prototype.update = function (data) {
  9405. this.create(data);
  9406. };
  9407. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  9408. if (!this._buffer) {
  9409. return;
  9410. }
  9411. if (this._updatable) {
  9412. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  9413. this._data = null;
  9414. }
  9415. };
  9416. VertexBuffer.prototype.dispose = function () {
  9417. if (!this._buffer) {
  9418. return;
  9419. }
  9420. if (this._engine._releaseBuffer(this._buffer)) {
  9421. this._buffer = null;
  9422. }
  9423. };
  9424. Object.defineProperty(VertexBuffer, "PositionKind", {
  9425. get: function () {
  9426. return VertexBuffer._PositionKind;
  9427. },
  9428. enumerable: true,
  9429. configurable: true
  9430. });
  9431. Object.defineProperty(VertexBuffer, "NormalKind", {
  9432. get: function () {
  9433. return VertexBuffer._NormalKind;
  9434. },
  9435. enumerable: true,
  9436. configurable: true
  9437. });
  9438. Object.defineProperty(VertexBuffer, "UVKind", {
  9439. get: function () {
  9440. return VertexBuffer._UVKind;
  9441. },
  9442. enumerable: true,
  9443. configurable: true
  9444. });
  9445. Object.defineProperty(VertexBuffer, "UV2Kind", {
  9446. get: function () {
  9447. return VertexBuffer._UV2Kind;
  9448. },
  9449. enumerable: true,
  9450. configurable: true
  9451. });
  9452. Object.defineProperty(VertexBuffer, "ColorKind", {
  9453. get: function () {
  9454. return VertexBuffer._ColorKind;
  9455. },
  9456. enumerable: true,
  9457. configurable: true
  9458. });
  9459. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  9460. get: function () {
  9461. return VertexBuffer._MatricesIndicesKind;
  9462. },
  9463. enumerable: true,
  9464. configurable: true
  9465. });
  9466. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  9467. get: function () {
  9468. return VertexBuffer._MatricesWeightsKind;
  9469. },
  9470. enumerable: true,
  9471. configurable: true
  9472. });
  9473. // Enums
  9474. VertexBuffer._PositionKind = "position";
  9475. VertexBuffer._NormalKind = "normal";
  9476. VertexBuffer._UVKind = "uv";
  9477. VertexBuffer._UV2Kind = "uv2";
  9478. VertexBuffer._ColorKind = "color";
  9479. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  9480. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  9481. return VertexBuffer;
  9482. })();
  9483. BABYLON.VertexBuffer = VertexBuffer;
  9484. })(BABYLON || (BABYLON = {}));
  9485. //# sourceMappingURL=babylon.vertexBuffer.js.map
  9486. var BABYLON;
  9487. (function (BABYLON) {
  9488. var AbstractMesh = (function (_super) {
  9489. __extends(AbstractMesh, _super);
  9490. function AbstractMesh(name, scene) {
  9491. _super.call(this, name, scene);
  9492. // Properties
  9493. this.definedFacingForward = true; // orientation for POV movement & rotation
  9494. this.position = new BABYLON.Vector3(0, 0, 0);
  9495. this.rotation = new BABYLON.Vector3(0, 0, 0);
  9496. this.scaling = new BABYLON.Vector3(1, 1, 1);
  9497. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  9498. this.visibility = 1.0;
  9499. this.alphaIndex = Number.MAX_VALUE;
  9500. this.infiniteDistance = false;
  9501. this.isVisible = true;
  9502. this.isPickable = true;
  9503. this.showBoundingBox = false;
  9504. this.showSubMeshesBoundingBox = false;
  9505. this.onDispose = null;
  9506. this.checkCollisions = false;
  9507. this.isBlocker = false;
  9508. this.renderingGroupId = 0;
  9509. this.receiveShadows = false;
  9510. this.renderOutline = false;
  9511. this.outlineColor = BABYLON.Color3.Red();
  9512. this.outlineWidth = 0.02;
  9513. this.renderOverlay = false;
  9514. this.overlayColor = BABYLON.Color3.Red();
  9515. this.overlayAlpha = 0.5;
  9516. this.hasVertexAlpha = false;
  9517. this.useVertexColors = true;
  9518. this.applyFog = true;
  9519. this.useOctreeForRenderingSelection = true;
  9520. this.useOctreeForPicking = true;
  9521. this.useOctreeForCollisions = true;
  9522. this.layerMask = 0xFFFFFFFF;
  9523. // Physics
  9524. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  9525. // Collisions
  9526. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  9527. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  9528. this._collider = new BABYLON.Collider();
  9529. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  9530. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  9531. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  9532. // Cache
  9533. this._localScaling = BABYLON.Matrix.Zero();
  9534. this._localRotation = BABYLON.Matrix.Zero();
  9535. this._localTranslation = BABYLON.Matrix.Zero();
  9536. this._localBillboard = BABYLON.Matrix.Zero();
  9537. this._localPivotScaling = BABYLON.Matrix.Zero();
  9538. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  9539. this._localWorld = BABYLON.Matrix.Zero();
  9540. this._worldMatrix = BABYLON.Matrix.Zero();
  9541. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  9542. this._absolutePosition = BABYLON.Vector3.Zero();
  9543. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  9544. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  9545. this._isDirty = false;
  9546. this._pivotMatrix = BABYLON.Matrix.Identity();
  9547. this._isDisposed = false;
  9548. this._renderId = 0;
  9549. this._intersectionsInProgress = new Array();
  9550. this._onAfterWorldMatrixUpdate = new Array();
  9551. scene.meshes.push(this);
  9552. }
  9553. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  9554. get: function () {
  9555. return AbstractMesh._BILLBOARDMODE_NONE;
  9556. },
  9557. enumerable: true,
  9558. configurable: true
  9559. });
  9560. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  9561. get: function () {
  9562. return AbstractMesh._BILLBOARDMODE_X;
  9563. },
  9564. enumerable: true,
  9565. configurable: true
  9566. });
  9567. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  9568. get: function () {
  9569. return AbstractMesh._BILLBOARDMODE_Y;
  9570. },
  9571. enumerable: true,
  9572. configurable: true
  9573. });
  9574. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  9575. get: function () {
  9576. return AbstractMesh._BILLBOARDMODE_Z;
  9577. },
  9578. enumerable: true,
  9579. configurable: true
  9580. });
  9581. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  9582. get: function () {
  9583. return AbstractMesh._BILLBOARDMODE_ALL;
  9584. },
  9585. enumerable: true,
  9586. configurable: true
  9587. });
  9588. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  9589. // Methods
  9590. get: function () {
  9591. return false;
  9592. },
  9593. enumerable: true,
  9594. configurable: true
  9595. });
  9596. AbstractMesh.prototype.getLOD = function (camera) {
  9597. return this;
  9598. };
  9599. AbstractMesh.prototype.getTotalVertices = function () {
  9600. return 0;
  9601. };
  9602. AbstractMesh.prototype.getIndices = function () {
  9603. return null;
  9604. };
  9605. AbstractMesh.prototype.getVerticesData = function (kind) {
  9606. return null;
  9607. };
  9608. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  9609. return false;
  9610. };
  9611. AbstractMesh.prototype.getBoundingInfo = function () {
  9612. if (this._masterMesh) {
  9613. return this._masterMesh.getBoundingInfo();
  9614. }
  9615. if (!this._boundingInfo) {
  9616. this._updateBoundingInfo();
  9617. }
  9618. return this._boundingInfo;
  9619. };
  9620. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  9621. get: function () {
  9622. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  9623. },
  9624. enumerable: true,
  9625. configurable: true
  9626. });
  9627. AbstractMesh.prototype._preActivate = function () {
  9628. };
  9629. AbstractMesh.prototype._activate = function (renderId) {
  9630. this._renderId = renderId;
  9631. };
  9632. AbstractMesh.prototype.getWorldMatrix = function () {
  9633. if (this._masterMesh) {
  9634. return this._masterMesh.getWorldMatrix();
  9635. }
  9636. if (this._currentRenderId !== this.getScene().getRenderId()) {
  9637. this.computeWorldMatrix();
  9638. }
  9639. return this._worldMatrix;
  9640. };
  9641. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  9642. get: function () {
  9643. return this._worldMatrix;
  9644. },
  9645. enumerable: true,
  9646. configurable: true
  9647. });
  9648. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  9649. get: function () {
  9650. return this._absolutePosition;
  9651. },
  9652. enumerable: true,
  9653. configurable: true
  9654. });
  9655. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  9656. if (!this.rotationQuaternion) {
  9657. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  9658. this.rotation = BABYLON.Vector3.Zero();
  9659. }
  9660. if (!space || space == 0 /* LOCAL */) {
  9661. var rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  9662. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  9663. }
  9664. else {
  9665. if (this.parent) {
  9666. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  9667. invertParentWorldMatrix.invert();
  9668. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  9669. }
  9670. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  9671. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  9672. }
  9673. };
  9674. AbstractMesh.prototype.translate = function (axis, distance, space) {
  9675. var displacementVector = axis.scale(distance);
  9676. if (!space || space == 0 /* LOCAL */) {
  9677. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  9678. this.setPositionWithLocalVector(tempV3);
  9679. }
  9680. else {
  9681. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  9682. }
  9683. };
  9684. AbstractMesh.prototype.getAbsolutePosition = function () {
  9685. this.computeWorldMatrix();
  9686. return this._absolutePosition;
  9687. };
  9688. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  9689. if (!absolutePosition) {
  9690. return;
  9691. }
  9692. var absolutePositionX;
  9693. var absolutePositionY;
  9694. var absolutePositionZ;
  9695. if (absolutePosition.x === undefined) {
  9696. if (arguments.length < 3) {
  9697. return;
  9698. }
  9699. absolutePositionX = arguments[0];
  9700. absolutePositionY = arguments[1];
  9701. absolutePositionZ = arguments[2];
  9702. }
  9703. else {
  9704. absolutePositionX = absolutePosition.x;
  9705. absolutePositionY = absolutePosition.y;
  9706. absolutePositionZ = absolutePosition.z;
  9707. }
  9708. if (this.parent) {
  9709. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  9710. invertParentWorldMatrix.invert();
  9711. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  9712. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  9713. }
  9714. else {
  9715. this.position.x = absolutePositionX;
  9716. this.position.y = absolutePositionY;
  9717. this.position.z = absolutePositionZ;
  9718. }
  9719. };
  9720. // ================================== Point of View Movement =================================
  9721. /**
  9722. * Perform relative position change from the point of view of behind the front of the mesh.
  9723. * This is performed taking into account the meshes current rotation, so you do not have to care.
  9724. * Supports definition of mesh facing forward or backward.
  9725. * @param {number} amountRight
  9726. * @param {number} amountUp
  9727. * @param {number} amountForward
  9728. */
  9729. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  9730. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  9731. };
  9732. /**
  9733. * Calculate relative position change from the point of view of behind the front of the mesh.
  9734. * This is performed taking into account the meshes current rotation, so you do not have to care.
  9735. * Supports definition of mesh facing forward or backward.
  9736. * @param {number} amountRight
  9737. * @param {number} amountUp
  9738. * @param {number} amountForward
  9739. */
  9740. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  9741. var rotMatrix = new BABYLON.Matrix();
  9742. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  9743. rotQuaternion.toRotationMatrix(rotMatrix);
  9744. var translationDelta = BABYLON.Vector3.Zero();
  9745. var defForwardMult = this.definedFacingForward ? -1 : 1;
  9746. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  9747. return translationDelta;
  9748. };
  9749. // ================================== Point of View Rotation =================================
  9750. /**
  9751. * Perform relative rotation change from the point of view of behind the front of the mesh.
  9752. * Supports definition of mesh facing forward or backward.
  9753. * @param {number} flipBack
  9754. * @param {number} twirlClockwise
  9755. * @param {number} tiltRight
  9756. */
  9757. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  9758. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  9759. };
  9760. /**
  9761. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  9762. * Supports definition of mesh facing forward or backward.
  9763. * @param {number} flipBack
  9764. * @param {number} twirlClockwise
  9765. * @param {number} tiltRight
  9766. */
  9767. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  9768. var defForwardMult = this.definedFacingForward ? 1 : -1;
  9769. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  9770. };
  9771. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  9772. this._pivotMatrix = matrix;
  9773. this._cache.pivotMatrixUpdated = true;
  9774. };
  9775. AbstractMesh.prototype.getPivotMatrix = function () {
  9776. return this._pivotMatrix;
  9777. };
  9778. AbstractMesh.prototype._isSynchronized = function () {
  9779. if (this._isDirty) {
  9780. return false;
  9781. }
  9782. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  9783. return false;
  9784. if (this._cache.pivotMatrixUpdated) {
  9785. return false;
  9786. }
  9787. if (this.infiniteDistance) {
  9788. return false;
  9789. }
  9790. if (!this._cache.position.equals(this.position))
  9791. return false;
  9792. if (this.rotationQuaternion) {
  9793. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  9794. return false;
  9795. }
  9796. else {
  9797. if (!this._cache.rotation.equals(this.rotation))
  9798. return false;
  9799. }
  9800. if (!this._cache.scaling.equals(this.scaling))
  9801. return false;
  9802. return true;
  9803. };
  9804. AbstractMesh.prototype._initCache = function () {
  9805. _super.prototype._initCache.call(this);
  9806. this._cache.localMatrixUpdated = false;
  9807. this._cache.position = BABYLON.Vector3.Zero();
  9808. this._cache.scaling = BABYLON.Vector3.Zero();
  9809. this._cache.rotation = BABYLON.Vector3.Zero();
  9810. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  9811. };
  9812. AbstractMesh.prototype.markAsDirty = function (property) {
  9813. if (property === "rotation") {
  9814. this.rotationQuaternion = null;
  9815. }
  9816. this._currentRenderId = Number.MAX_VALUE;
  9817. this._isDirty = true;
  9818. };
  9819. AbstractMesh.prototype._updateBoundingInfo = function () {
  9820. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  9821. this._boundingInfo._update(this.worldMatrixFromCache);
  9822. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  9823. };
  9824. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  9825. if (!this.subMeshes) {
  9826. return;
  9827. }
  9828. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  9829. var subMesh = this.subMeshes[subIndex];
  9830. subMesh.updateBoundingInfo(matrix);
  9831. }
  9832. };
  9833. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  9834. if (!force && (this._currentRenderId == this.getScene().getRenderId() || this.isSynchronized(true))) {
  9835. return this._worldMatrix;
  9836. }
  9837. this._cache.position.copyFrom(this.position);
  9838. this._cache.scaling.copyFrom(this.scaling);
  9839. this._cache.pivotMatrixUpdated = false;
  9840. this._currentRenderId = this.getScene().getRenderId();
  9841. this._isDirty = false;
  9842. // Scaling
  9843. BABYLON.Matrix.ScalingToRef(this.scaling.x, this.scaling.y, this.scaling.z, this._localScaling);
  9844. // Rotation
  9845. if (this.rotationQuaternion) {
  9846. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  9847. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  9848. }
  9849. else {
  9850. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  9851. this._cache.rotation.copyFrom(this.rotation);
  9852. }
  9853. // Translation
  9854. if (this.infiniteDistance && !this.parent) {
  9855. var camera = this.getScene().activeCamera;
  9856. var cameraWorldMatrix = camera.getWorldMatrix();
  9857. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  9858. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  9859. }
  9860. else {
  9861. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  9862. }
  9863. // Composing transformations
  9864. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  9865. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  9866. // Billboarding
  9867. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  9868. var localPosition = this.position.clone();
  9869. var zero = this.getScene().activeCamera.position.clone();
  9870. if (this.parent && this.parent.position) {
  9871. localPosition.addInPlace(this.parent.position);
  9872. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  9873. }
  9874. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) === AbstractMesh.BILLBOARDMODE_ALL) {
  9875. zero = this.getScene().activeCamera.position;
  9876. }
  9877. else {
  9878. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X)
  9879. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  9880. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y)
  9881. zero.y = localPosition.y + 0.001;
  9882. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z)
  9883. zero.z = localPosition.z + 0.001;
  9884. }
  9885. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  9886. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  9887. this._localBillboard.invert();
  9888. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  9889. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  9890. }
  9891. // Local world
  9892. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  9893. // Parent
  9894. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  9895. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  9896. }
  9897. else {
  9898. this._worldMatrix.copyFrom(this._localWorld);
  9899. }
  9900. // Bounding info
  9901. this._updateBoundingInfo();
  9902. // Absolute position
  9903. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  9904. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  9905. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  9906. }
  9907. return this._worldMatrix;
  9908. };
  9909. /**
  9910. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  9911. * @param func: callback function to add
  9912. */
  9913. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  9914. this._onAfterWorldMatrixUpdate.push(func);
  9915. };
  9916. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  9917. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  9918. if (index > -1) {
  9919. this._onAfterWorldMatrixUpdate.splice(index, 1);
  9920. }
  9921. };
  9922. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  9923. this.computeWorldMatrix();
  9924. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  9925. };
  9926. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  9927. this.computeWorldMatrix();
  9928. var invLocalWorldMatrix = this._localWorld.clone();
  9929. invLocalWorldMatrix.invert();
  9930. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  9931. };
  9932. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  9933. this.computeWorldMatrix();
  9934. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  9935. };
  9936. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  9937. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  9938. /// <param name="targetPoint" type="BABYLON.Vector3">The position (must be in same space as current mesh) to look at</param>
  9939. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  9940. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  9941. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  9942. /// <returns>Mesh oriented towards targetMesh</returns>
  9943. yawCor = yawCor || 0; // default to zero if undefined
  9944. pitchCor = pitchCor || 0;
  9945. rollCor = rollCor || 0;
  9946. var dv = targetPoint.subtract(this.position);
  9947. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  9948. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  9949. var pitch = Math.atan2(dv.y, len);
  9950. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  9951. };
  9952. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  9953. if (!this._boundingInfo.isInFrustum(frustumPlanes)) {
  9954. return false;
  9955. }
  9956. return true;
  9957. };
  9958. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  9959. if (!camera) {
  9960. camera = this.getScene().activeCamera;
  9961. }
  9962. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  9963. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  9964. return false;
  9965. }
  9966. return true;
  9967. };
  9968. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  9969. if (!this._boundingInfo || !mesh._boundingInfo) {
  9970. return false;
  9971. }
  9972. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  9973. };
  9974. AbstractMesh.prototype.intersectsPoint = function (point) {
  9975. if (!this._boundingInfo) {
  9976. return false;
  9977. }
  9978. return this._boundingInfo.intersectsPoint(point);
  9979. };
  9980. // Physics
  9981. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  9982. var physicsEngine = this.getScene().getPhysicsEngine();
  9983. if (!physicsEngine) {
  9984. return;
  9985. }
  9986. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  9987. if (impostor.impostor) {
  9988. // Old API
  9989. options = impostor;
  9990. impostor = impostor.impostor;
  9991. }
  9992. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  9993. physicsEngine._unregisterMesh(this);
  9994. return;
  9995. }
  9996. if (!options) {
  9997. options = { mass: 0, friction: 0.2, restitution: 0.2 };
  9998. }
  9999. else {
  10000. if (!options.mass && options.mass !== 0)
  10001. options.mass = 0;
  10002. if (!options.friction && options.friction !== 0)
  10003. options.friction = 0.2;
  10004. if (!options.restitution && options.restitution !== 0)
  10005. options.restitution = 0.2;
  10006. }
  10007. this._physicImpostor = impostor;
  10008. this._physicsMass = options.mass;
  10009. this._physicsFriction = options.friction;
  10010. this._physicRestitution = options.restitution;
  10011. return physicsEngine._registerMesh(this, impostor, options);
  10012. };
  10013. AbstractMesh.prototype.getPhysicsImpostor = function () {
  10014. if (!this._physicImpostor) {
  10015. return BABYLON.PhysicsEngine.NoImpostor;
  10016. }
  10017. return this._physicImpostor;
  10018. };
  10019. AbstractMesh.prototype.getPhysicsMass = function () {
  10020. if (!this._physicsMass) {
  10021. return 0;
  10022. }
  10023. return this._physicsMass;
  10024. };
  10025. AbstractMesh.prototype.getPhysicsFriction = function () {
  10026. if (!this._physicsFriction) {
  10027. return 0;
  10028. }
  10029. return this._physicsFriction;
  10030. };
  10031. AbstractMesh.prototype.getPhysicsRestitution = function () {
  10032. if (!this._physicRestitution) {
  10033. return 0;
  10034. }
  10035. return this._physicRestitution;
  10036. };
  10037. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  10038. if (!camera) {
  10039. camera = this.getScene().activeCamera;
  10040. }
  10041. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  10042. };
  10043. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  10044. if (!camera) {
  10045. camera = this.getScene().activeCamera;
  10046. }
  10047. return this.absolutePosition.subtract(camera.position).length();
  10048. };
  10049. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  10050. if (!this._physicImpostor) {
  10051. return;
  10052. }
  10053. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  10054. };
  10055. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  10056. if (!this._physicImpostor) {
  10057. return;
  10058. }
  10059. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  10060. };
  10061. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  10062. if (!this._physicImpostor) {
  10063. return;
  10064. }
  10065. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  10066. };
  10067. // Collisions
  10068. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  10069. var globalPosition = this.getAbsolutePosition();
  10070. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  10071. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  10072. this._collider.radius = this.ellipsoid;
  10073. this.getScene()._getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this._newPositionForCollisions, this);
  10074. this._newPositionForCollisions.subtractToRef(this._oldPositionForCollisions, this._diffPositionForCollisions);
  10075. if (this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  10076. this.position.addInPlace(this._diffPositionForCollisions);
  10077. }
  10078. };
  10079. // Submeshes octree
  10080. /**
  10081. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  10082. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  10083. */
  10084. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  10085. if (maxCapacity === void 0) { maxCapacity = 64; }
  10086. if (maxDepth === void 0) { maxDepth = 2; }
  10087. if (!this._submeshesOctree) {
  10088. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  10089. }
  10090. this.computeWorldMatrix(true);
  10091. // Update octree
  10092. var bbox = this.getBoundingInfo().boundingBox;
  10093. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  10094. return this._submeshesOctree;
  10095. };
  10096. // Collisions
  10097. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  10098. this._generatePointsArray();
  10099. // Transformation
  10100. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  10101. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  10102. subMesh._lastColliderWorldVertices = [];
  10103. subMesh._trianglePlanes = [];
  10104. var start = subMesh.verticesStart;
  10105. var end = (subMesh.verticesStart + subMesh.verticesCount);
  10106. for (var i = start; i < end; i++) {
  10107. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  10108. }
  10109. }
  10110. // Collide
  10111. collider._collide(subMesh, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart);
  10112. };
  10113. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  10114. var subMeshes;
  10115. var len;
  10116. // Octrees
  10117. if (this._submeshesOctree && this.useOctreeForCollisions) {
  10118. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  10119. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  10120. len = intersections.length;
  10121. subMeshes = intersections.data;
  10122. }
  10123. else {
  10124. subMeshes = this.subMeshes;
  10125. len = subMeshes.length;
  10126. }
  10127. for (var index = 0; index < len; index++) {
  10128. var subMesh = subMeshes[index];
  10129. // Bounding test
  10130. if (len > 1 && !subMesh._checkCollision(collider))
  10131. continue;
  10132. this._collideForSubMesh(subMesh, transformMatrix, collider);
  10133. }
  10134. };
  10135. AbstractMesh.prototype._checkCollision = function (collider) {
  10136. // Bounding box test
  10137. if (!this._boundingInfo._checkCollision(collider))
  10138. return;
  10139. // Transformation matrix
  10140. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  10141. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  10142. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  10143. };
  10144. // Picking
  10145. AbstractMesh.prototype._generatePointsArray = function () {
  10146. return false;
  10147. };
  10148. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  10149. var pickingInfo = new BABYLON.PickingInfo();
  10150. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  10151. return pickingInfo;
  10152. }
  10153. if (!this._generatePointsArray()) {
  10154. return pickingInfo;
  10155. }
  10156. var intersectInfo = null;
  10157. // Octrees
  10158. var subMeshes;
  10159. var len;
  10160. if (this._submeshesOctree && this.useOctreeForPicking) {
  10161. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  10162. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  10163. len = intersections.length;
  10164. subMeshes = intersections.data;
  10165. }
  10166. else {
  10167. subMeshes = this.subMeshes;
  10168. len = subMeshes.length;
  10169. }
  10170. for (var index = 0; index < len; index++) {
  10171. var subMesh = subMeshes[index];
  10172. // Bounding test
  10173. if (len > 1 && !subMesh.canIntersects(ray))
  10174. continue;
  10175. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  10176. if (currentIntersectInfo) {
  10177. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  10178. intersectInfo = currentIntersectInfo;
  10179. intersectInfo.subMeshId = index;
  10180. if (fastCheck) {
  10181. break;
  10182. }
  10183. }
  10184. }
  10185. }
  10186. if (intersectInfo) {
  10187. // Get picked point
  10188. var world = this.getWorldMatrix();
  10189. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  10190. var direction = ray.direction.clone();
  10191. direction = direction.scale(intersectInfo.distance);
  10192. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  10193. var pickedPoint = worldOrigin.add(worldDirection);
  10194. // Return result
  10195. pickingInfo.hit = true;
  10196. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  10197. pickingInfo.pickedPoint = pickedPoint;
  10198. pickingInfo.pickedMesh = this;
  10199. pickingInfo.bu = intersectInfo.bu;
  10200. pickingInfo.bv = intersectInfo.bv;
  10201. pickingInfo.faceId = intersectInfo.faceId;
  10202. pickingInfo.subMeshId = intersectInfo.subMeshId;
  10203. return pickingInfo;
  10204. }
  10205. return pickingInfo;
  10206. };
  10207. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  10208. return null;
  10209. };
  10210. AbstractMesh.prototype.releaseSubMeshes = function () {
  10211. if (this.subMeshes) {
  10212. while (this.subMeshes.length) {
  10213. this.subMeshes[0].dispose();
  10214. }
  10215. }
  10216. else {
  10217. this.subMeshes = new Array();
  10218. }
  10219. };
  10220. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  10221. // Physics
  10222. if (this.getPhysicsImpostor() != BABYLON.PhysicsEngine.NoImpostor) {
  10223. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  10224. }
  10225. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  10226. var other = this._intersectionsInProgress[index];
  10227. var pos = other._intersectionsInProgress.indexOf(this);
  10228. other._intersectionsInProgress.splice(pos, 1);
  10229. }
  10230. this._intersectionsInProgress = [];
  10231. // SubMeshes
  10232. this.releaseSubMeshes();
  10233. // Remove from scene
  10234. var index = this.getScene().meshes.indexOf(this);
  10235. if (index != -1) {
  10236. // Remove from the scene if mesh found
  10237. this.getScene().meshes.splice(index, 1);
  10238. }
  10239. if (!doNotRecurse) {
  10240. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  10241. if (this.getScene().particleSystems[index].emitter == this) {
  10242. this.getScene().particleSystems[index].dispose();
  10243. index--;
  10244. }
  10245. }
  10246. // Children
  10247. var objects = this.getScene().meshes.slice(0);
  10248. for (index = 0; index < objects.length; index++) {
  10249. if (objects[index].parent == this) {
  10250. objects[index].dispose();
  10251. }
  10252. }
  10253. }
  10254. else {
  10255. for (index = 0; index < this.getScene().meshes.length; index++) {
  10256. var obj = this.getScene().meshes[index];
  10257. if (obj.parent === this) {
  10258. obj.parent = null;
  10259. obj.computeWorldMatrix(true);
  10260. }
  10261. }
  10262. }
  10263. this._onAfterWorldMatrixUpdate = [];
  10264. this._isDisposed = true;
  10265. // Callback
  10266. if (this.onDispose) {
  10267. this.onDispose();
  10268. }
  10269. };
  10270. // Statics
  10271. AbstractMesh._BILLBOARDMODE_NONE = 0;
  10272. AbstractMesh._BILLBOARDMODE_X = 1;
  10273. AbstractMesh._BILLBOARDMODE_Y = 2;
  10274. AbstractMesh._BILLBOARDMODE_Z = 4;
  10275. AbstractMesh._BILLBOARDMODE_ALL = 7;
  10276. return AbstractMesh;
  10277. })(BABYLON.Node);
  10278. BABYLON.AbstractMesh = AbstractMesh;
  10279. })(BABYLON || (BABYLON = {}));
  10280. //# sourceMappingURL=babylon.abstractMesh.js.map
  10281. var BABYLON;
  10282. (function (BABYLON) {
  10283. var _InstancesBatch = (function () {
  10284. function _InstancesBatch() {
  10285. this.mustReturn = false;
  10286. this.visibleInstances = new Array();
  10287. this.renderSelf = new Array();
  10288. }
  10289. return _InstancesBatch;
  10290. })();
  10291. BABYLON._InstancesBatch = _InstancesBatch;
  10292. var Mesh = (function (_super) {
  10293. __extends(Mesh, _super);
  10294. /**
  10295. * @constructor
  10296. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  10297. * @param {Scene} scene - The scene to add this mesh to.
  10298. * @param {Node} parent - The parent of this mesh, if it has one
  10299. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  10300. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  10301. * When false, achieved by calling a clone(), also passing False.
  10302. * This will make creation of children, recursive.
  10303. */
  10304. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  10305. if (parent === void 0) { parent = null; }
  10306. _super.call(this, name, scene);
  10307. // Members
  10308. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  10309. this.instances = new Array();
  10310. this._LODLevels = new Array();
  10311. this._onBeforeRenderCallbacks = new Array();
  10312. this._onAfterRenderCallbacks = new Array();
  10313. this._visibleInstances = {};
  10314. this._renderIdForInstances = new Array();
  10315. this._batchCache = new _InstancesBatch();
  10316. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  10317. if (source) {
  10318. // Geometry
  10319. if (source._geometry) {
  10320. source._geometry.applyToMesh(this);
  10321. }
  10322. // Deep copy
  10323. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton"], []);
  10324. // Material
  10325. this.material = source.material;
  10326. if (!doNotCloneChildren) {
  10327. for (var index = 0; index < scene.meshes.length; index++) {
  10328. var mesh = scene.meshes[index];
  10329. if (mesh.parent === source) {
  10330. // doNotCloneChildren is always going to be False
  10331. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  10332. }
  10333. }
  10334. }
  10335. for (index = 0; index < scene.particleSystems.length; index++) {
  10336. var system = scene.particleSystems[index];
  10337. if (system.emitter === source) {
  10338. system.clone(system.name, this);
  10339. }
  10340. }
  10341. this.computeWorldMatrix(true);
  10342. }
  10343. // Parent
  10344. if (parent !== null) {
  10345. this.parent = parent;
  10346. }
  10347. }
  10348. Object.defineProperty(Mesh, "FRONTSIDE", {
  10349. get: function () {
  10350. return Mesh._FRONTSIDE;
  10351. },
  10352. enumerable: true,
  10353. configurable: true
  10354. });
  10355. Object.defineProperty(Mesh, "BACKSIDE", {
  10356. get: function () {
  10357. return Mesh._BACKSIDE;
  10358. },
  10359. enumerable: true,
  10360. configurable: true
  10361. });
  10362. Object.defineProperty(Mesh, "DOUBLESIDE", {
  10363. get: function () {
  10364. return Mesh._DOUBLESIDE;
  10365. },
  10366. enumerable: true,
  10367. configurable: true
  10368. });
  10369. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  10370. get: function () {
  10371. return Mesh._DEFAULTSIDE;
  10372. },
  10373. enumerable: true,
  10374. configurable: true
  10375. });
  10376. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  10377. // Methods
  10378. get: function () {
  10379. return this._LODLevels.length > 0;
  10380. },
  10381. enumerable: true,
  10382. configurable: true
  10383. });
  10384. Mesh.prototype._sortLODLevels = function () {
  10385. this._LODLevels.sort(function (a, b) {
  10386. if (a.distance < b.distance) {
  10387. return 1;
  10388. }
  10389. if (a.distance > b.distance) {
  10390. return -1;
  10391. }
  10392. return 0;
  10393. });
  10394. };
  10395. /**
  10396. * Add a mesh as LOD level triggered at the given distance.
  10397. * @param {number} distance - the distance from the center of the object to show this level
  10398. * @param {BABYLON.Mesh} mesh - the mesh to be added as LOD level
  10399. * @return {BABYLON.Mesh} this mesh (for chaining)
  10400. */
  10401. Mesh.prototype.addLODLevel = function (distance, mesh) {
  10402. if (mesh && mesh._masterMesh) {
  10403. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  10404. return this;
  10405. }
  10406. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  10407. this._LODLevels.push(level);
  10408. if (mesh) {
  10409. mesh._masterMesh = this;
  10410. }
  10411. this._sortLODLevels();
  10412. return this;
  10413. };
  10414. /**
  10415. * Remove a mesh from the LOD array
  10416. * @param {BABYLON.Mesh} mesh - the mesh to be removed.
  10417. * @return {BABYLON.Mesh} this mesh (for chaining)
  10418. */
  10419. Mesh.prototype.removeLODLevel = function (mesh) {
  10420. for (var index = 0; index < this._LODLevels.length; index++) {
  10421. if (this._LODLevels[index].mesh === mesh) {
  10422. this._LODLevels.splice(index, 1);
  10423. if (mesh) {
  10424. mesh._masterMesh = null;
  10425. }
  10426. }
  10427. }
  10428. this._sortLODLevels();
  10429. return this;
  10430. };
  10431. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  10432. if (!this._LODLevels || this._LODLevels.length === 0) {
  10433. return this;
  10434. }
  10435. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  10436. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  10437. return this;
  10438. }
  10439. for (var index = 0; index < this._LODLevels.length; index++) {
  10440. var level = this._LODLevels[index];
  10441. if (level.distance < distanceToCamera) {
  10442. if (level.mesh) {
  10443. level.mesh._preActivate();
  10444. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  10445. }
  10446. return level.mesh;
  10447. }
  10448. }
  10449. return this;
  10450. };
  10451. Object.defineProperty(Mesh.prototype, "geometry", {
  10452. get: function () {
  10453. return this._geometry;
  10454. },
  10455. enumerable: true,
  10456. configurable: true
  10457. });
  10458. Mesh.prototype.getTotalVertices = function () {
  10459. if (!this._geometry) {
  10460. return 0;
  10461. }
  10462. return this._geometry.getTotalVertices();
  10463. };
  10464. Mesh.prototype.getVerticesData = function (kind) {
  10465. if (!this._geometry) {
  10466. return null;
  10467. }
  10468. return this._geometry.getVerticesData(kind);
  10469. };
  10470. Mesh.prototype.getVertexBuffer = function (kind) {
  10471. if (!this._geometry) {
  10472. return undefined;
  10473. }
  10474. return this._geometry.getVertexBuffer(kind);
  10475. };
  10476. Mesh.prototype.isVerticesDataPresent = function (kind) {
  10477. if (!this._geometry) {
  10478. if (this._delayInfo) {
  10479. return this._delayInfo.indexOf(kind) !== -1;
  10480. }
  10481. return false;
  10482. }
  10483. return this._geometry.isVerticesDataPresent(kind);
  10484. };
  10485. Mesh.prototype.getVerticesDataKinds = function () {
  10486. if (!this._geometry) {
  10487. var result = [];
  10488. if (this._delayInfo) {
  10489. for (var kind in this._delayInfo) {
  10490. result.push(kind);
  10491. }
  10492. }
  10493. return result;
  10494. }
  10495. return this._geometry.getVerticesDataKinds();
  10496. };
  10497. Mesh.prototype.getTotalIndices = function () {
  10498. if (!this._geometry) {
  10499. return 0;
  10500. }
  10501. return this._geometry.getTotalIndices();
  10502. };
  10503. Mesh.prototype.getIndices = function () {
  10504. if (!this._geometry) {
  10505. return [];
  10506. }
  10507. return this._geometry.getIndices();
  10508. };
  10509. Object.defineProperty(Mesh.prototype, "isBlocked", {
  10510. get: function () {
  10511. return this._masterMesh !== null && this._masterMesh !== undefined;
  10512. },
  10513. enumerable: true,
  10514. configurable: true
  10515. });
  10516. Mesh.prototype.isReady = function () {
  10517. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  10518. return false;
  10519. }
  10520. return _super.prototype.isReady.call(this);
  10521. };
  10522. Mesh.prototype.isDisposed = function () {
  10523. return this._isDisposed;
  10524. };
  10525. // Methods
  10526. Mesh.prototype._preActivate = function () {
  10527. var sceneRenderId = this.getScene().getRenderId();
  10528. if (this._preActivateId === sceneRenderId) {
  10529. return;
  10530. }
  10531. this._preActivateId = sceneRenderId;
  10532. this._visibleInstances = null;
  10533. };
  10534. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  10535. if (!this._visibleInstances) {
  10536. this._visibleInstances = {};
  10537. this._visibleInstances.defaultRenderId = renderId;
  10538. this._visibleInstances.selfDefaultRenderId = this._renderId;
  10539. }
  10540. if (!this._visibleInstances[renderId]) {
  10541. this._visibleInstances[renderId] = new Array();
  10542. }
  10543. this._visibleInstances[renderId].push(instance);
  10544. };
  10545. Mesh.prototype.refreshBoundingInfo = function () {
  10546. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  10547. if (data) {
  10548. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  10549. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  10550. }
  10551. if (this.subMeshes) {
  10552. for (var index = 0; index < this.subMeshes.length; index++) {
  10553. this.subMeshes[index].refreshBoundingInfo();
  10554. }
  10555. }
  10556. this._updateBoundingInfo();
  10557. };
  10558. Mesh.prototype._createGlobalSubMesh = function () {
  10559. var totalVertices = this.getTotalVertices();
  10560. if (!totalVertices || !this.getIndices()) {
  10561. return null;
  10562. }
  10563. this.releaseSubMeshes();
  10564. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  10565. };
  10566. Mesh.prototype.subdivide = function (count) {
  10567. if (count < 1) {
  10568. return;
  10569. }
  10570. var totalIndices = this.getTotalIndices();
  10571. var subdivisionSize = (totalIndices / count) | 0;
  10572. var offset = 0;
  10573. while (subdivisionSize % 3 !== 0) {
  10574. subdivisionSize++;
  10575. }
  10576. this.releaseSubMeshes();
  10577. for (var index = 0; index < count; index++) {
  10578. if (offset >= totalIndices) {
  10579. break;
  10580. }
  10581. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  10582. offset += subdivisionSize;
  10583. }
  10584. this.synchronizeInstances();
  10585. };
  10586. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  10587. if (kind instanceof Array) {
  10588. var temp = data;
  10589. data = kind;
  10590. kind = temp;
  10591. BABYLON.Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  10592. }
  10593. if (!this._geometry) {
  10594. var vertexData = new BABYLON.VertexData();
  10595. vertexData.set(data, kind);
  10596. var scene = this.getScene();
  10597. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  10598. }
  10599. else {
  10600. this._geometry.setVerticesData(kind, data, updatable, stride);
  10601. }
  10602. };
  10603. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  10604. if (!this._geometry) {
  10605. return;
  10606. }
  10607. if (!makeItUnique) {
  10608. this._geometry.updateVerticesData(kind, data, updateExtends);
  10609. }
  10610. else {
  10611. this.makeGeometryUnique();
  10612. this.updateVerticesData(kind, data, updateExtends, false);
  10613. }
  10614. };
  10615. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  10616. if (!this._geometry) {
  10617. return;
  10618. }
  10619. if (!makeItUnique) {
  10620. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  10621. }
  10622. else {
  10623. this.makeGeometryUnique();
  10624. this.updateVerticesDataDirectly(kind, data, offset, false);
  10625. }
  10626. };
  10627. Mesh.prototype.makeGeometryUnique = function () {
  10628. if (!this._geometry) {
  10629. return;
  10630. }
  10631. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  10632. geometry.applyToMesh(this);
  10633. };
  10634. Mesh.prototype.setIndices = function (indices, totalVertices) {
  10635. if (!this._geometry) {
  10636. var vertexData = new BABYLON.VertexData();
  10637. vertexData.indices = indices;
  10638. var scene = this.getScene();
  10639. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  10640. }
  10641. else {
  10642. this._geometry.setIndices(indices, totalVertices);
  10643. }
  10644. };
  10645. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  10646. var engine = this.getScene().getEngine();
  10647. // Wireframe
  10648. var indexToBind;
  10649. switch (fillMode) {
  10650. case BABYLON.Material.PointFillMode:
  10651. indexToBind = null;
  10652. break;
  10653. case BABYLON.Material.WireFrameFillMode:
  10654. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  10655. break;
  10656. default:
  10657. case BABYLON.Material.TriangleFillMode:
  10658. indexToBind = this._geometry.getIndexBuffer();
  10659. break;
  10660. }
  10661. // VBOs
  10662. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  10663. };
  10664. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  10665. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  10666. return;
  10667. }
  10668. var engine = this.getScene().getEngine();
  10669. switch (fillMode) {
  10670. case BABYLON.Material.PointFillMode:
  10671. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  10672. break;
  10673. case BABYLON.Material.WireFrameFillMode:
  10674. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  10675. break;
  10676. default:
  10677. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  10678. }
  10679. };
  10680. Mesh.prototype.registerBeforeRender = function (func) {
  10681. this._onBeforeRenderCallbacks.push(func);
  10682. };
  10683. Mesh.prototype.unregisterBeforeRender = function (func) {
  10684. var index = this._onBeforeRenderCallbacks.indexOf(func);
  10685. if (index > -1) {
  10686. this._onBeforeRenderCallbacks.splice(index, 1);
  10687. }
  10688. };
  10689. Mesh.prototype.registerAfterRender = function (func) {
  10690. this._onAfterRenderCallbacks.push(func);
  10691. };
  10692. Mesh.prototype.unregisterAfterRender = function (func) {
  10693. var index = this._onAfterRenderCallbacks.indexOf(func);
  10694. if (index > -1) {
  10695. this._onAfterRenderCallbacks.splice(index, 1);
  10696. }
  10697. };
  10698. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  10699. var scene = this.getScene();
  10700. this._batchCache.mustReturn = false;
  10701. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  10702. this._batchCache.visibleInstances[subMeshId] = null;
  10703. if (this._visibleInstances) {
  10704. var currentRenderId = scene.getRenderId();
  10705. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  10706. var selfRenderId = this._renderId;
  10707. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  10708. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  10709. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  10710. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  10711. }
  10712. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  10713. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  10714. this._batchCache.mustReturn = true;
  10715. return this._batchCache;
  10716. }
  10717. if (currentRenderId !== selfRenderId) {
  10718. this._batchCache.renderSelf[subMeshId] = false;
  10719. }
  10720. }
  10721. this._renderIdForInstances[subMeshId] = currentRenderId;
  10722. }
  10723. return this._batchCache;
  10724. };
  10725. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  10726. var visibleInstances = batch.visibleInstances[subMesh._id];
  10727. var matricesCount = visibleInstances.length + 1;
  10728. var bufferSize = matricesCount * 16 * 4;
  10729. while (this._instancesBufferSize < bufferSize) {
  10730. this._instancesBufferSize *= 2;
  10731. }
  10732. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  10733. if (this._worldMatricesInstancesBuffer) {
  10734. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  10735. }
  10736. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  10737. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  10738. }
  10739. var offset = 0;
  10740. var instancesCount = 0;
  10741. var world = this.getWorldMatrix();
  10742. if (batch.renderSelf[subMesh._id]) {
  10743. world.copyToArray(this._worldMatricesInstancesArray, offset);
  10744. offset += 16;
  10745. instancesCount++;
  10746. }
  10747. if (visibleInstances) {
  10748. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  10749. var instance = visibleInstances[instanceIndex];
  10750. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  10751. offset += 16;
  10752. instancesCount++;
  10753. }
  10754. }
  10755. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  10756. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  10757. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  10758. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  10759. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  10760. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  10761. this._draw(subMesh, fillMode, instancesCount);
  10762. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  10763. };
  10764. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  10765. var scene = this.getScene();
  10766. var engine = scene.getEngine();
  10767. if (hardwareInstancedRendering) {
  10768. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  10769. }
  10770. else {
  10771. if (batch.renderSelf[subMesh._id]) {
  10772. // Draw
  10773. if (onBeforeDraw) {
  10774. onBeforeDraw(false, this.getWorldMatrix());
  10775. }
  10776. this._draw(subMesh, fillMode);
  10777. }
  10778. if (batch.visibleInstances[subMesh._id]) {
  10779. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  10780. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  10781. // World
  10782. var world = instance.getWorldMatrix();
  10783. if (onBeforeDraw) {
  10784. onBeforeDraw(true, world);
  10785. }
  10786. // Draw
  10787. this._draw(subMesh, fillMode);
  10788. }
  10789. }
  10790. }
  10791. };
  10792. Mesh.prototype.render = function (subMesh) {
  10793. var scene = this.getScene();
  10794. // Managing instances
  10795. var batch = this._getInstancesRenderList(subMesh._id);
  10796. if (batch.mustReturn) {
  10797. return;
  10798. }
  10799. // Checking geometry state
  10800. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  10801. return;
  10802. }
  10803. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  10804. this._onBeforeRenderCallbacks[callbackIndex](this);
  10805. }
  10806. var engine = scene.getEngine();
  10807. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  10808. // Material
  10809. var effectiveMaterial = subMesh.getMaterial();
  10810. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  10811. return;
  10812. }
  10813. // Outline - step 1
  10814. var savedDepthWrite = engine.getDepthWrite();
  10815. if (this.renderOutline) {
  10816. engine.setDepthWrite(false);
  10817. scene.getOutlineRenderer().render(subMesh, batch);
  10818. engine.setDepthWrite(savedDepthWrite);
  10819. }
  10820. effectiveMaterial._preBind();
  10821. var effect = effectiveMaterial.getEffect();
  10822. // Bind
  10823. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  10824. this._bind(subMesh, effect, fillMode);
  10825. var world = this.getWorldMatrix();
  10826. effectiveMaterial.bind(world, this);
  10827. // Draw
  10828. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  10829. if (isInstance) {
  10830. effectiveMaterial.bindOnlyWorldMatrix(world);
  10831. }
  10832. });
  10833. // Unbind
  10834. effectiveMaterial.unbind();
  10835. // Outline - step 2
  10836. if (this.renderOutline && savedDepthWrite) {
  10837. engine.setDepthWrite(true);
  10838. engine.setColorWrite(false);
  10839. scene.getOutlineRenderer().render(subMesh, batch);
  10840. engine.setColorWrite(true);
  10841. }
  10842. // Overlay
  10843. if (this.renderOverlay) {
  10844. var currentMode = engine.getAlphaMode();
  10845. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  10846. scene.getOutlineRenderer().render(subMesh, batch, true);
  10847. engine.setAlphaMode(currentMode);
  10848. }
  10849. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  10850. this._onAfterRenderCallbacks[callbackIndex](this);
  10851. }
  10852. };
  10853. Mesh.prototype.getEmittedParticleSystems = function () {
  10854. var results = new Array();
  10855. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  10856. var particleSystem = this.getScene().particleSystems[index];
  10857. if (particleSystem.emitter === this) {
  10858. results.push(particleSystem);
  10859. }
  10860. }
  10861. return results;
  10862. };
  10863. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  10864. var results = new Array();
  10865. var descendants = this.getDescendants();
  10866. descendants.push(this);
  10867. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  10868. var particleSystem = this.getScene().particleSystems[index];
  10869. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  10870. results.push(particleSystem);
  10871. }
  10872. }
  10873. return results;
  10874. };
  10875. Mesh.prototype.getChildren = function () {
  10876. var results = [];
  10877. for (var index = 0; index < this.getScene().meshes.length; index++) {
  10878. var mesh = this.getScene().meshes[index];
  10879. if (mesh.parent === this) {
  10880. results.push(mesh);
  10881. }
  10882. }
  10883. return results;
  10884. };
  10885. Mesh.prototype._checkDelayState = function () {
  10886. var _this = this;
  10887. var that = this;
  10888. var scene = this.getScene();
  10889. if (this._geometry) {
  10890. this._geometry.load(scene);
  10891. }
  10892. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  10893. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  10894. scene._addPendingData(that);
  10895. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  10896. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  10897. if (data instanceof ArrayBuffer) {
  10898. _this._delayLoadingFunction(data, _this);
  10899. }
  10900. else {
  10901. _this._delayLoadingFunction(JSON.parse(data), _this);
  10902. }
  10903. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  10904. scene._removePendingData(_this);
  10905. }, function () {
  10906. }, scene.database, getBinaryData);
  10907. }
  10908. };
  10909. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  10910. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  10911. return false;
  10912. }
  10913. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  10914. return false;
  10915. }
  10916. this._checkDelayState();
  10917. return true;
  10918. };
  10919. Mesh.prototype.setMaterialByID = function (id) {
  10920. var materials = this.getScene().materials;
  10921. for (var index = 0; index < materials.length; index++) {
  10922. if (materials[index].id === id) {
  10923. this.material = materials[index];
  10924. return;
  10925. }
  10926. }
  10927. // Multi
  10928. var multiMaterials = this.getScene().multiMaterials;
  10929. for (index = 0; index < multiMaterials.length; index++) {
  10930. if (multiMaterials[index].id === id) {
  10931. this.material = multiMaterials[index];
  10932. return;
  10933. }
  10934. }
  10935. };
  10936. Mesh.prototype.getAnimatables = function () {
  10937. var results = [];
  10938. if (this.material) {
  10939. results.push(this.material);
  10940. }
  10941. if (this.skeleton) {
  10942. results.push(this.skeleton);
  10943. }
  10944. return results;
  10945. };
  10946. // Geometry
  10947. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  10948. // Position
  10949. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  10950. return;
  10951. }
  10952. this._resetPointsArrayCache();
  10953. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  10954. var temp = [];
  10955. for (var index = 0; index < data.length; index += 3) {
  10956. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  10957. }
  10958. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  10959. // Normals
  10960. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  10961. return;
  10962. }
  10963. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  10964. for (index = 0; index < data.length; index += 3) {
  10965. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  10966. }
  10967. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  10968. };
  10969. // Cache
  10970. Mesh.prototype._resetPointsArrayCache = function () {
  10971. this._positions = null;
  10972. };
  10973. Mesh.prototype._generatePointsArray = function () {
  10974. if (this._positions)
  10975. return true;
  10976. this._positions = [];
  10977. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  10978. if (!data) {
  10979. return false;
  10980. }
  10981. for (var index = 0; index < data.length; index += 3) {
  10982. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  10983. }
  10984. return true;
  10985. };
  10986. // Clone
  10987. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  10988. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  10989. };
  10990. // Dispose
  10991. Mesh.prototype.dispose = function (doNotRecurse) {
  10992. if (this._geometry) {
  10993. this._geometry.releaseForMesh(this, true);
  10994. }
  10995. // Instances
  10996. if (this._worldMatricesInstancesBuffer) {
  10997. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  10998. this._worldMatricesInstancesBuffer = null;
  10999. }
  11000. while (this.instances.length) {
  11001. this.instances[0].dispose();
  11002. }
  11003. _super.prototype.dispose.call(this, doNotRecurse);
  11004. };
  11005. // Geometric tools
  11006. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  11007. var _this = this;
  11008. var scene = this.getScene();
  11009. var onload = function (img) {
  11010. // Getting height map data
  11011. var canvas = document.createElement("canvas");
  11012. var context = canvas.getContext("2d");
  11013. var heightMapWidth = img.width;
  11014. var heightMapHeight = img.height;
  11015. canvas.width = heightMapWidth;
  11016. canvas.height = heightMapHeight;
  11017. context.drawImage(img, 0, 0);
  11018. // Create VertexData from map data
  11019. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  11020. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  11021. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  11022. //execute success callback, if set
  11023. if (onSuccess) {
  11024. onSuccess(_this);
  11025. }
  11026. };
  11027. BABYLON.Tools.LoadImage(url, onload, function () {
  11028. }, scene.database);
  11029. };
  11030. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  11031. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  11032. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  11033. return;
  11034. }
  11035. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11036. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  11037. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  11038. var position = BABYLON.Vector3.Zero();
  11039. var normal = BABYLON.Vector3.Zero();
  11040. var uv = BABYLON.Vector2.Zero();
  11041. for (var index = 0; index < positions.length; index += 3) {
  11042. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  11043. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  11044. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  11045. // Compute height
  11046. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  11047. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  11048. var pos = (u + v * heightMapWidth) * 4;
  11049. var r = buffer[pos] / 255.0;
  11050. var g = buffer[pos + 1] / 255.0;
  11051. var b = buffer[pos + 2] / 255.0;
  11052. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  11053. normal.normalize();
  11054. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  11055. position = position.add(normal);
  11056. position.toArray(positions, index);
  11057. }
  11058. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  11059. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  11060. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  11061. };
  11062. Mesh.prototype.convertToFlatShadedMesh = function () {
  11063. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  11064. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  11065. var kinds = this.getVerticesDataKinds();
  11066. var vbs = [];
  11067. var data = [];
  11068. var newdata = [];
  11069. var updatableNormals = false;
  11070. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  11071. var kind = kinds[kindIndex];
  11072. var vertexBuffer = this.getVertexBuffer(kind);
  11073. if (kind === BABYLON.VertexBuffer.NormalKind) {
  11074. updatableNormals = vertexBuffer.isUpdatable();
  11075. kinds.splice(kindIndex, 1);
  11076. kindIndex--;
  11077. continue;
  11078. }
  11079. vbs[kind] = vertexBuffer;
  11080. data[kind] = vbs[kind].getData();
  11081. newdata[kind] = [];
  11082. }
  11083. // Save previous submeshes
  11084. var previousSubmeshes = this.subMeshes.slice(0);
  11085. var indices = this.getIndices();
  11086. var totalIndices = this.getTotalIndices();
  11087. for (var index = 0; index < totalIndices; index++) {
  11088. var vertexIndex = indices[index];
  11089. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  11090. kind = kinds[kindIndex];
  11091. var stride = vbs[kind].getStrideSize();
  11092. for (var offset = 0; offset < stride; offset++) {
  11093. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  11094. }
  11095. }
  11096. }
  11097. // Updating faces & normal
  11098. var normals = [];
  11099. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  11100. for (index = 0; index < totalIndices; index += 3) {
  11101. indices[index] = index;
  11102. indices[index + 1] = index + 1;
  11103. indices[index + 2] = index + 2;
  11104. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  11105. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  11106. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  11107. var p1p2 = p1.subtract(p2);
  11108. var p3p2 = p3.subtract(p2);
  11109. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  11110. for (var localIndex = 0; localIndex < 3; localIndex++) {
  11111. normals.push(normal.x);
  11112. normals.push(normal.y);
  11113. normals.push(normal.z);
  11114. }
  11115. }
  11116. this.setIndices(indices);
  11117. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  11118. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  11119. kind = kinds[kindIndex];
  11120. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  11121. }
  11122. // Updating submeshes
  11123. this.releaseSubMeshes();
  11124. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  11125. var previousOne = previousSubmeshes[submeshIndex];
  11126. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  11127. }
  11128. this.synchronizeInstances();
  11129. };
  11130. // Instances
  11131. Mesh.prototype.createInstance = function (name) {
  11132. return new BABYLON.InstancedMesh(name, this);
  11133. };
  11134. Mesh.prototype.synchronizeInstances = function () {
  11135. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  11136. var instance = this.instances[instanceIndex];
  11137. instance._syncSubMeshes();
  11138. }
  11139. };
  11140. /**
  11141. * Simplify the mesh according to the given array of settings.
  11142. * Function will return immediately and will simplify async.
  11143. * @param settings a collection of simplification settings.
  11144. * @param parallelProcessing should all levels calculate parallel or one after the other.
  11145. * @param type the type of simplification to run.
  11146. * successCallback optional success callback to be called after the simplification finished processing all settings.
  11147. */
  11148. Mesh.prototype.simplify = function (settings, parallelProcessing, type, successCallback) {
  11149. var _this = this;
  11150. if (parallelProcessing === void 0) { parallelProcessing = true; }
  11151. if (type === void 0) { type = 0 /* QUADRATIC */; }
  11152. var getSimplifier = function () {
  11153. switch (type) {
  11154. case 0 /* QUADRATIC */:
  11155. default:
  11156. return new BABYLON.QuadraticErrorSimplification(_this);
  11157. }
  11158. };
  11159. if (parallelProcessing) {
  11160. //parallel simplifier
  11161. settings.forEach(function (setting) {
  11162. var simplifier = getSimplifier();
  11163. simplifier.simplify(setting, function (newMesh) {
  11164. _this.addLODLevel(setting.distance, newMesh);
  11165. //check if it is the last
  11166. if (setting.quality === settings[settings.length - 1].quality && successCallback) {
  11167. //all done, run the success callback.
  11168. successCallback();
  11169. }
  11170. });
  11171. });
  11172. }
  11173. else {
  11174. //single simplifier.
  11175. var simplifier = getSimplifier();
  11176. var runDecimation = function (setting, callback) {
  11177. simplifier.simplify(setting, function (newMesh) {
  11178. _this.addLODLevel(setting.distance, newMesh);
  11179. //run the next quality level
  11180. callback();
  11181. });
  11182. };
  11183. BABYLON.AsyncLoop.Run(settings.length, function (loop) {
  11184. runDecimation(settings[loop.index], function () {
  11185. loop.executeNext();
  11186. });
  11187. }, function () {
  11188. //execution ended, run the success callback.
  11189. if (successCallback) {
  11190. successCallback();
  11191. }
  11192. });
  11193. }
  11194. };
  11195. // Statics
  11196. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation) {
  11197. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11198. var ribbon = new Mesh(name, scene);
  11199. var vertexData = BABYLON.VertexData.CreateRibbon(pathArray, closeArray, closePath, offset, sideOrientation);
  11200. vertexData.applyToMesh(ribbon, updatable);
  11201. return ribbon;
  11202. };
  11203. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  11204. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11205. var box = new Mesh(name, scene);
  11206. var vertexData = BABYLON.VertexData.CreateBox(size, sideOrientation);
  11207. vertexData.applyToMesh(box, updatable);
  11208. return box;
  11209. };
  11210. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  11211. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11212. var sphere = new Mesh(name, scene);
  11213. var vertexData = BABYLON.VertexData.CreateSphere(segments, diameter, sideOrientation);
  11214. vertexData.applyToMesh(sphere, updatable);
  11215. return sphere;
  11216. };
  11217. // Cylinder and cone (Code inspired by SharpDX.org)
  11218. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  11219. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11220. // subdivisions is a new parameter, we need to support old signature
  11221. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  11222. if (scene !== undefined) {
  11223. updatable = scene;
  11224. }
  11225. scene = subdivisions;
  11226. subdivisions = 1;
  11227. }
  11228. var cylinder = new Mesh(name, scene);
  11229. var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions);
  11230. vertexData.applyToMesh(cylinder, updatable);
  11231. return cylinder;
  11232. };
  11233. // Torus (Code from SharpDX.org)
  11234. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  11235. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11236. var torus = new Mesh(name, scene);
  11237. var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation, sideOrientation);
  11238. vertexData.applyToMesh(torus, updatable);
  11239. return torus;
  11240. };
  11241. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  11242. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11243. var torusKnot = new Mesh(name, scene);
  11244. var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q, sideOrientation);
  11245. vertexData.applyToMesh(torusKnot, updatable);
  11246. return torusKnot;
  11247. };
  11248. // Lines
  11249. Mesh.CreateLines = function (name, points, scene, updatable) {
  11250. var lines = new BABYLON.LinesMesh(name, scene, updatable);
  11251. var vertexData = BABYLON.VertexData.CreateLines(points);
  11252. vertexData.applyToMesh(lines, updatable);
  11253. return lines;
  11254. };
  11255. // Plane & ground
  11256. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  11257. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11258. var plane = new Mesh(name, scene);
  11259. var vertexData = BABYLON.VertexData.CreatePlane(size, sideOrientation);
  11260. vertexData.applyToMesh(plane, updatable);
  11261. return plane;
  11262. };
  11263. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  11264. var ground = new BABYLON.GroundMesh(name, scene);
  11265. ground._setReady(false);
  11266. ground._subdivisions = subdivisions;
  11267. var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
  11268. vertexData.applyToMesh(ground, updatable);
  11269. ground._setReady(true);
  11270. return ground;
  11271. };
  11272. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  11273. var tiledGround = new Mesh(name, scene);
  11274. var vertexData = BABYLON.VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  11275. vertexData.applyToMesh(tiledGround, updatable);
  11276. return tiledGround;
  11277. };
  11278. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  11279. var ground = new BABYLON.GroundMesh(name, scene);
  11280. ground._subdivisions = subdivisions;
  11281. ground._setReady(false);
  11282. var onload = function (img) {
  11283. // Getting height map data
  11284. var canvas = document.createElement("canvas");
  11285. var context = canvas.getContext("2d");
  11286. var heightMapWidth = img.width;
  11287. var heightMapHeight = img.height;
  11288. canvas.width = heightMapWidth;
  11289. canvas.height = heightMapHeight;
  11290. context.drawImage(img, 0, 0);
  11291. // Create VertexData from map data
  11292. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  11293. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  11294. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  11295. vertexData.applyToMesh(ground, updatable);
  11296. ground._setReady(true);
  11297. //execute ready callback, if set
  11298. if (onReady) {
  11299. onReady(ground);
  11300. }
  11301. };
  11302. BABYLON.Tools.LoadImage(url, onload, function () {
  11303. }, scene.database);
  11304. return ground;
  11305. };
  11306. Mesh.CreateTube = function (name, path, radius, tesselation, radiusFunction, scene, updatable, sideOrientation) {
  11307. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11308. var path3D = new BABYLON.Path3D(path);
  11309. var tangents = path3D.getTangents();
  11310. var normals = path3D.getNormals();
  11311. var distances = path3D.getDistances();
  11312. var pi2 = Math.PI * 2;
  11313. var step = pi2 / tesselation;
  11314. var returnRadius = function (i, distance) { return radius; };
  11315. var radiusFunctionFinal = radiusFunction || returnRadius;
  11316. var circlePaths = [];
  11317. var circlePath;
  11318. var rad;
  11319. var normal;
  11320. var rotated;
  11321. var rotationMatrix;
  11322. for (var i = 0; i < path.length; i++) {
  11323. rad = radiusFunctionFinal(i, distances[i]); // current radius
  11324. circlePath = []; // current circle array
  11325. normal = normals[i]; // current normal
  11326. for (var ang = 0; ang < pi2; ang += step) {
  11327. rotationMatrix = BABYLON.Matrix.RotationAxis(tangents[i], ang);
  11328. rotated = BABYLON.Vector3.TransformCoordinates(normal, rotationMatrix).scaleInPlace(rad).add(path[i]);
  11329. circlePath.push(rotated);
  11330. }
  11331. circlePaths.push(circlePath);
  11332. }
  11333. var tube = Mesh.CreateRibbon(name, circlePaths, false, true, 0, scene, updatable, sideOrientation);
  11334. return tube;
  11335. };
  11336. // Tools
  11337. Mesh.MinMax = function (meshes) {
  11338. var minVector = null;
  11339. var maxVector = null;
  11340. for (var i in meshes) {
  11341. var mesh = meshes[i];
  11342. var boundingBox = mesh.getBoundingInfo().boundingBox;
  11343. if (!minVector) {
  11344. minVector = boundingBox.minimumWorld;
  11345. maxVector = boundingBox.maximumWorld;
  11346. continue;
  11347. }
  11348. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  11349. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  11350. }
  11351. return {
  11352. min: minVector,
  11353. max: maxVector
  11354. };
  11355. };
  11356. Mesh.Center = function (meshesOrMinMaxVector) {
  11357. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  11358. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  11359. };
  11360. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices) {
  11361. if (disposeSource === void 0) { disposeSource = true; }
  11362. var source = meshes[0];
  11363. var material = source.material;
  11364. var scene = source.getScene();
  11365. if (!allow32BitsIndices) {
  11366. var totalVertices = 0;
  11367. for (var index = 0; index < meshes.length; index++) {
  11368. totalVertices += meshes[index].getTotalVertices();
  11369. if (totalVertices > 65536) {
  11370. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  11371. return null;
  11372. }
  11373. }
  11374. }
  11375. // Merge
  11376. var vertexData = BABYLON.VertexData.ExtractFromMesh(source);
  11377. vertexData.transform(source.getWorldMatrix());
  11378. for (index = 1; index < meshes.length; index++) {
  11379. var otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index]);
  11380. otherVertexData.transform(meshes[index].getWorldMatrix());
  11381. vertexData.merge(otherVertexData);
  11382. }
  11383. var newMesh = new Mesh(source.name + "_merged", scene);
  11384. vertexData.applyToMesh(newMesh);
  11385. // Setting properties
  11386. newMesh.material = material;
  11387. newMesh.checkCollisions = source.checkCollisions;
  11388. // Cleaning
  11389. if (disposeSource) {
  11390. for (index = 0; index < meshes.length; index++) {
  11391. meshes[index].dispose();
  11392. }
  11393. }
  11394. return newMesh;
  11395. };
  11396. // Consts
  11397. Mesh._FRONTSIDE = 0;
  11398. Mesh._BACKSIDE = 1;
  11399. Mesh._DOUBLESIDE = 2;
  11400. Mesh._DEFAULTSIDE = 0;
  11401. return Mesh;
  11402. })(BABYLON.AbstractMesh);
  11403. BABYLON.Mesh = Mesh;
  11404. })(BABYLON || (BABYLON = {}));
  11405. //# sourceMappingURL=babylon.mesh.js.map
  11406. var BABYLON;
  11407. (function (BABYLON) {
  11408. var GroundMesh = (function (_super) {
  11409. __extends(GroundMesh, _super);
  11410. function GroundMesh(name, scene) {
  11411. _super.call(this, name, scene);
  11412. this.generateOctree = false;
  11413. this._worldInverse = new BABYLON.Matrix();
  11414. }
  11415. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  11416. get: function () {
  11417. return this._subdivisions;
  11418. },
  11419. enumerable: true,
  11420. configurable: true
  11421. });
  11422. GroundMesh.prototype.optimize = function (chunksCount) {
  11423. this.subdivide(this._subdivisions);
  11424. this.createOrUpdateSubmeshesOctree(32);
  11425. };
  11426. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  11427. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  11428. this.getWorldMatrix().invertToRef(this._worldInverse);
  11429. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  11430. var pickInfo = this.intersects(ray);
  11431. if (pickInfo.hit) {
  11432. return pickInfo.pickedPoint.y;
  11433. }
  11434. return 0;
  11435. };
  11436. return GroundMesh;
  11437. })(BABYLON.Mesh);
  11438. BABYLON.GroundMesh = GroundMesh;
  11439. })(BABYLON || (BABYLON = {}));
  11440. //# sourceMappingURL=babylon.groundMesh.js.map
  11441. var BABYLON;
  11442. (function (BABYLON) {
  11443. /**
  11444. * Creates an instance based on a source mesh.
  11445. */
  11446. var InstancedMesh = (function (_super) {
  11447. __extends(InstancedMesh, _super);
  11448. function InstancedMesh(name, source) {
  11449. _super.call(this, name, source.getScene());
  11450. source.instances.push(this);
  11451. this._sourceMesh = source;
  11452. this.position.copyFrom(source.position);
  11453. this.rotation.copyFrom(source.rotation);
  11454. this.scaling.copyFrom(source.scaling);
  11455. if (source.rotationQuaternion) {
  11456. this.rotationQuaternion = source.rotationQuaternion.clone();
  11457. }
  11458. this.infiniteDistance = source.infiniteDistance;
  11459. this.setPivotMatrix(source.getPivotMatrix());
  11460. this.refreshBoundingInfo();
  11461. this._syncSubMeshes();
  11462. }
  11463. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  11464. // Methods
  11465. get: function () {
  11466. return this._sourceMesh.receiveShadows;
  11467. },
  11468. enumerable: true,
  11469. configurable: true
  11470. });
  11471. Object.defineProperty(InstancedMesh.prototype, "material", {
  11472. get: function () {
  11473. return this._sourceMesh.material;
  11474. },
  11475. enumerable: true,
  11476. configurable: true
  11477. });
  11478. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  11479. get: function () {
  11480. return this._sourceMesh.visibility;
  11481. },
  11482. enumerable: true,
  11483. configurable: true
  11484. });
  11485. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  11486. get: function () {
  11487. return this._sourceMesh.skeleton;
  11488. },
  11489. enumerable: true,
  11490. configurable: true
  11491. });
  11492. InstancedMesh.prototype.getTotalVertices = function () {
  11493. return this._sourceMesh.getTotalVertices();
  11494. };
  11495. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  11496. get: function () {
  11497. return this._sourceMesh;
  11498. },
  11499. enumerable: true,
  11500. configurable: true
  11501. });
  11502. InstancedMesh.prototype.getVerticesData = function (kind) {
  11503. return this._sourceMesh.getVerticesData(kind);
  11504. };
  11505. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  11506. return this._sourceMesh.isVerticesDataPresent(kind);
  11507. };
  11508. InstancedMesh.prototype.getIndices = function () {
  11509. return this._sourceMesh.getIndices();
  11510. };
  11511. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  11512. get: function () {
  11513. return this._sourceMesh._positions;
  11514. },
  11515. enumerable: true,
  11516. configurable: true
  11517. });
  11518. InstancedMesh.prototype.refreshBoundingInfo = function () {
  11519. var data = this._sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11520. if (data) {
  11521. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._sourceMesh.getTotalVertices());
  11522. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  11523. }
  11524. this._updateBoundingInfo();
  11525. };
  11526. InstancedMesh.prototype._preActivate = function () {
  11527. if (this._currentLOD) {
  11528. this._currentLOD._preActivate();
  11529. }
  11530. };
  11531. InstancedMesh.prototype._activate = function (renderId) {
  11532. if (this._currentLOD) {
  11533. this._currentLOD._registerInstanceForRenderId(this, renderId);
  11534. }
  11535. };
  11536. InstancedMesh.prototype.getLOD = function (camera) {
  11537. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  11538. if (this._currentLOD === this.sourceMesh) {
  11539. return this;
  11540. }
  11541. return this._currentLOD;
  11542. };
  11543. InstancedMesh.prototype._syncSubMeshes = function () {
  11544. this.releaseSubMeshes();
  11545. if (this._sourceMesh.subMeshes) {
  11546. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  11547. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  11548. }
  11549. }
  11550. };
  11551. InstancedMesh.prototype._generatePointsArray = function () {
  11552. return this._sourceMesh._generatePointsArray();
  11553. };
  11554. // Clone
  11555. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  11556. var result = this._sourceMesh.createInstance(name);
  11557. // Deep copy
  11558. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  11559. // Bounding info
  11560. this.refreshBoundingInfo();
  11561. // Parent
  11562. if (newParent) {
  11563. result.parent = newParent;
  11564. }
  11565. if (!doNotCloneChildren) {
  11566. for (var index = 0; index < this.getScene().meshes.length; index++) {
  11567. var mesh = this.getScene().meshes[index];
  11568. if (mesh.parent === this) {
  11569. mesh.clone(mesh.name, result);
  11570. }
  11571. }
  11572. }
  11573. result.computeWorldMatrix(true);
  11574. return result;
  11575. };
  11576. // Dispoe
  11577. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  11578. // Remove from mesh
  11579. var index = this._sourceMesh.instances.indexOf(this);
  11580. this._sourceMesh.instances.splice(index, 1);
  11581. _super.prototype.dispose.call(this, doNotRecurse);
  11582. };
  11583. return InstancedMesh;
  11584. })(BABYLON.AbstractMesh);
  11585. BABYLON.InstancedMesh = InstancedMesh;
  11586. })(BABYLON || (BABYLON = {}));
  11587. //# sourceMappingURL=babylon.instancedMesh.js.mapvar BABYLON;
  11588. (function (BABYLON) {
  11589. var SubMesh = (function () {
  11590. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  11591. if (createBoundingBox === void 0) { createBoundingBox = true; }
  11592. this.materialIndex = materialIndex;
  11593. this.verticesStart = verticesStart;
  11594. this.verticesCount = verticesCount;
  11595. this.indexStart = indexStart;
  11596. this.indexCount = indexCount;
  11597. this._renderId = 0;
  11598. this._mesh = mesh;
  11599. this._renderingMesh = renderingMesh || mesh;
  11600. mesh.subMeshes.push(this);
  11601. this._id = mesh.subMeshes.length - 1;
  11602. if (createBoundingBox) {
  11603. this.refreshBoundingInfo();
  11604. }
  11605. }
  11606. SubMesh.prototype.getBoundingInfo = function () {
  11607. return this._boundingInfo;
  11608. };
  11609. SubMesh.prototype.getMesh = function () {
  11610. return this._mesh;
  11611. };
  11612. SubMesh.prototype.getRenderingMesh = function () {
  11613. return this._renderingMesh;
  11614. };
  11615. SubMesh.prototype.getMaterial = function () {
  11616. var rootMaterial = this._renderingMesh.material;
  11617. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  11618. var multiMaterial = rootMaterial;
  11619. return multiMaterial.getSubMaterial(this.materialIndex);
  11620. }
  11621. if (!rootMaterial) {
  11622. return this._mesh.getScene().defaultMaterial;
  11623. }
  11624. return rootMaterial;
  11625. };
  11626. // Methods
  11627. SubMesh.prototype.refreshBoundingInfo = function () {
  11628. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11629. if (!data) {
  11630. this._boundingInfo = this._mesh._boundingInfo;
  11631. return;
  11632. }
  11633. var indices = this._renderingMesh.getIndices();
  11634. var extend;
  11635. if (this.indexStart === 0 && this.indexCount === indices.length) {
  11636. extend = BABYLON.Tools.ExtractMinAndMax(data, this.verticesStart, this.verticesCount);
  11637. }
  11638. else {
  11639. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  11640. }
  11641. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  11642. };
  11643. SubMesh.prototype._checkCollision = function (collider) {
  11644. return this._boundingInfo._checkCollision(collider);
  11645. };
  11646. SubMesh.prototype.updateBoundingInfo = function (world) {
  11647. if (!this._boundingInfo) {
  11648. this.refreshBoundingInfo();
  11649. }
  11650. this._boundingInfo._update(world);
  11651. };
  11652. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  11653. return this._boundingInfo.isInFrustum(frustumPlanes);
  11654. };
  11655. SubMesh.prototype.render = function () {
  11656. this._renderingMesh.render(this);
  11657. };
  11658. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  11659. if (!this._linesIndexBuffer) {
  11660. var linesIndices = [];
  11661. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  11662. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  11663. }
  11664. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  11665. this.linesIndexCount = linesIndices.length;
  11666. }
  11667. return this._linesIndexBuffer;
  11668. };
  11669. SubMesh.prototype.canIntersects = function (ray) {
  11670. return ray.intersectsBox(this._boundingInfo.boundingBox);
  11671. };
  11672. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  11673. var intersectInfo = null;
  11674. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  11675. var p0 = positions[indices[index]];
  11676. var p1 = positions[indices[index + 1]];
  11677. var p2 = positions[indices[index + 2]];
  11678. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  11679. if (currentIntersectInfo) {
  11680. if (currentIntersectInfo.distance < 0) {
  11681. continue;
  11682. }
  11683. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  11684. intersectInfo = currentIntersectInfo;
  11685. intersectInfo.faceId = index / 3;
  11686. if (fastCheck) {
  11687. break;
  11688. }
  11689. }
  11690. }
  11691. }
  11692. return intersectInfo;
  11693. };
  11694. // Clone
  11695. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  11696. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  11697. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  11698. return result;
  11699. };
  11700. // Dispose
  11701. SubMesh.prototype.dispose = function () {
  11702. if (this._linesIndexBuffer) {
  11703. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  11704. this._linesIndexBuffer = null;
  11705. }
  11706. // Remove from mesh
  11707. var index = this._mesh.subMeshes.indexOf(this);
  11708. this._mesh.subMeshes.splice(index, 1);
  11709. };
  11710. // Statics
  11711. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  11712. var minVertexIndex = Number.MAX_VALUE;
  11713. var maxVertexIndex = -Number.MAX_VALUE;
  11714. renderingMesh = renderingMesh || mesh;
  11715. var indices = renderingMesh.getIndices();
  11716. for (var index = startIndex; index < startIndex + indexCount; index++) {
  11717. var vertexIndex = indices[index];
  11718. if (vertexIndex < minVertexIndex)
  11719. minVertexIndex = vertexIndex;
  11720. if (vertexIndex > maxVertexIndex)
  11721. maxVertexIndex = vertexIndex;
  11722. }
  11723. return new BABYLON.SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  11724. };
  11725. return SubMesh;
  11726. })();
  11727. BABYLON.SubMesh = SubMesh;
  11728. })(BABYLON || (BABYLON = {}));
  11729. //# sourceMappingURL=babylon.subMesh.js.mapvar BABYLON;
  11730. (function (BABYLON) {
  11731. var BaseTexture = (function () {
  11732. function BaseTexture(scene) {
  11733. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  11734. this.hasAlpha = false;
  11735. this.getAlphaFromRGB = false;
  11736. this.level = 1;
  11737. this.isCube = false;
  11738. this.isRenderTarget = false;
  11739. this.animations = new Array();
  11740. this.coordinatesIndex = 0;
  11741. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  11742. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  11743. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  11744. this.anisotropicFilteringLevel = 4;
  11745. this._scene = scene;
  11746. this._scene.textures.push(this);
  11747. }
  11748. BaseTexture.prototype.getScene = function () {
  11749. return this._scene;
  11750. };
  11751. BaseTexture.prototype.getTextureMatrix = function () {
  11752. return null;
  11753. };
  11754. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  11755. return null;
  11756. };
  11757. BaseTexture.prototype.getInternalTexture = function () {
  11758. return this._texture;
  11759. };
  11760. BaseTexture.prototype.isReady = function () {
  11761. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  11762. return true;
  11763. }
  11764. if (this._texture) {
  11765. return this._texture.isReady;
  11766. }
  11767. return false;
  11768. };
  11769. BaseTexture.prototype.getSize = function () {
  11770. if (this._texture._width) {
  11771. return { width: this._texture._width, height: this._texture._height };
  11772. }
  11773. if (this._texture._size) {
  11774. return { width: this._texture._size, height: this._texture._size };
  11775. }
  11776. return { width: 0, height: 0 };
  11777. };
  11778. BaseTexture.prototype.getBaseSize = function () {
  11779. if (!this.isReady())
  11780. return { width: 0, height: 0 };
  11781. if (this._texture._size) {
  11782. return { width: this._texture._size, height: this._texture._size };
  11783. }
  11784. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  11785. };
  11786. BaseTexture.prototype.scale = function (ratio) {
  11787. };
  11788. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  11789. get: function () {
  11790. return false;
  11791. },
  11792. enumerable: true,
  11793. configurable: true
  11794. });
  11795. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  11796. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  11797. for (var index = 0; index < texturesCache.length; index++) {
  11798. var texturesCacheEntry = texturesCache[index];
  11799. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  11800. texturesCache.splice(index, 1);
  11801. return;
  11802. }
  11803. }
  11804. };
  11805. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  11806. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  11807. for (var index = 0; index < texturesCache.length; index++) {
  11808. var texturesCacheEntry = texturesCache[index];
  11809. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  11810. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  11811. texturesCacheEntry.references++;
  11812. return texturesCacheEntry;
  11813. }
  11814. }
  11815. }
  11816. return null;
  11817. };
  11818. BaseTexture.prototype.delayLoad = function () {
  11819. };
  11820. BaseTexture.prototype.releaseInternalTexture = function () {
  11821. if (!this._texture) {
  11822. return;
  11823. }
  11824. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  11825. this._texture.references--;
  11826. // Final reference ?
  11827. if (this._texture.references === 0) {
  11828. var index = texturesCache.indexOf(this._texture);
  11829. texturesCache.splice(index, 1);
  11830. this._scene.getEngine()._releaseTexture(this._texture);
  11831. delete this._texture;
  11832. }
  11833. };
  11834. BaseTexture.prototype.clone = function () {
  11835. return null;
  11836. };
  11837. BaseTexture.prototype.dispose = function () {
  11838. // Remove from scene
  11839. var index = this._scene.textures.indexOf(this);
  11840. if (index >= 0) {
  11841. this._scene.textures.splice(index, 1);
  11842. }
  11843. if (this._texture === undefined) {
  11844. return;
  11845. }
  11846. this.releaseInternalTexture();
  11847. // Callback
  11848. if (this.onDispose) {
  11849. this.onDispose();
  11850. }
  11851. };
  11852. return BaseTexture;
  11853. })();
  11854. BABYLON.BaseTexture = BaseTexture;
  11855. })(BABYLON || (BABYLON = {}));
  11856. //# sourceMappingURL=babylon.baseTexture.js.mapvar BABYLON;
  11857. (function (BABYLON) {
  11858. var RenderingGroup = (function () {
  11859. function RenderingGroup(index, scene) {
  11860. this.index = index;
  11861. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  11862. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  11863. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  11864. this._scene = scene;
  11865. }
  11866. RenderingGroup.prototype.render = function (customRenderFunction) {
  11867. if (customRenderFunction) {
  11868. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  11869. return true;
  11870. }
  11871. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  11872. return false;
  11873. }
  11874. var engine = this._scene.getEngine();
  11875. // Opaque
  11876. var subIndex;
  11877. var submesh;
  11878. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  11879. submesh = this._opaqueSubMeshes.data[subIndex];
  11880. submesh.render();
  11881. }
  11882. // Alpha test
  11883. engine.setAlphaTesting(true);
  11884. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  11885. submesh = this._alphaTestSubMeshes.data[subIndex];
  11886. submesh.render();
  11887. }
  11888. engine.setAlphaTesting(false);
  11889. // Transparent
  11890. if (this._transparentSubMeshes.length) {
  11891. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  11892. submesh = this._transparentSubMeshes.data[subIndex];
  11893. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  11894. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.position).length();
  11895. }
  11896. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  11897. sortedArray.sort(function (a, b) {
  11898. // Alpha index first
  11899. if (a._alphaIndex > b._alphaIndex) {
  11900. return 1;
  11901. }
  11902. if (a._alphaIndex < b._alphaIndex) {
  11903. return -1;
  11904. }
  11905. // Then distance to camera
  11906. if (a._distanceToCamera < b._distanceToCamera) {
  11907. return 1;
  11908. }
  11909. if (a._distanceToCamera > b._distanceToCamera) {
  11910. return -1;
  11911. }
  11912. return 0;
  11913. });
  11914. // Rendering
  11915. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  11916. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  11917. submesh = sortedArray[subIndex];
  11918. submesh.render();
  11919. }
  11920. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  11921. }
  11922. return true;
  11923. };
  11924. RenderingGroup.prototype.prepare = function () {
  11925. this._opaqueSubMeshes.reset();
  11926. this._transparentSubMeshes.reset();
  11927. this._alphaTestSubMeshes.reset();
  11928. };
  11929. RenderingGroup.prototype.dispatch = function (subMesh) {
  11930. var material = subMesh.getMaterial();
  11931. var mesh = subMesh.getMesh();
  11932. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  11933. this._transparentSubMeshes.push(subMesh);
  11934. }
  11935. else if (material.needAlphaTesting()) {
  11936. this._alphaTestSubMeshes.push(subMesh);
  11937. }
  11938. else {
  11939. this._opaqueSubMeshes.push(subMesh); // Opaque
  11940. }
  11941. };
  11942. return RenderingGroup;
  11943. })();
  11944. BABYLON.RenderingGroup = RenderingGroup;
  11945. })(BABYLON || (BABYLON = {}));
  11946. //# sourceMappingURL=babylon.renderingGroup.js.mapvar BABYLON;
  11947. (function (BABYLON) {
  11948. var RenderingManager = (function () {
  11949. function RenderingManager(scene) {
  11950. this._renderingGroups = new Array();
  11951. this._scene = scene;
  11952. }
  11953. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  11954. if (this._scene._activeParticleSystems.length === 0) {
  11955. return;
  11956. }
  11957. // Particles
  11958. var beforeParticlesDate = BABYLON.Tools.Now;
  11959. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  11960. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  11961. if (particleSystem.renderingGroupId !== index) {
  11962. continue;
  11963. }
  11964. this._clearDepthBuffer();
  11965. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  11966. this._scene._activeParticles += particleSystem.render();
  11967. }
  11968. }
  11969. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  11970. };
  11971. RenderingManager.prototype._renderSprites = function (index) {
  11972. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  11973. return;
  11974. }
  11975. // Sprites
  11976. var beforeSpritessDate = BABYLON.Tools.Now;
  11977. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  11978. var spriteManager = this._scene.spriteManagers[id];
  11979. if (spriteManager.renderingGroupId === index) {
  11980. this._clearDepthBuffer();
  11981. spriteManager.render();
  11982. }
  11983. }
  11984. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  11985. };
  11986. RenderingManager.prototype._clearDepthBuffer = function () {
  11987. if (this._depthBufferAlreadyCleaned) {
  11988. return;
  11989. }
  11990. this._scene.getEngine().clear(0, false, true);
  11991. this._depthBufferAlreadyCleaned = true;
  11992. };
  11993. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  11994. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  11995. this._depthBufferAlreadyCleaned = false;
  11996. var renderingGroup = this._renderingGroups[index];
  11997. var needToStepBack = false;
  11998. if (renderingGroup) {
  11999. this._clearDepthBuffer();
  12000. if (!renderingGroup.render(customRenderFunction)) {
  12001. this._renderingGroups.splice(index, 1);
  12002. needToStepBack = true;
  12003. }
  12004. }
  12005. if (renderSprites) {
  12006. this._renderSprites(index);
  12007. }
  12008. if (renderParticles) {
  12009. this._renderParticles(index, activeMeshes);
  12010. }
  12011. if (needToStepBack) {
  12012. index--;
  12013. }
  12014. }
  12015. };
  12016. RenderingManager.prototype.reset = function () {
  12017. for (var index in this._renderingGroups) {
  12018. var renderingGroup = this._renderingGroups[index];
  12019. renderingGroup.prepare();
  12020. }
  12021. };
  12022. RenderingManager.prototype.dispatch = function (subMesh) {
  12023. var mesh = subMesh.getMesh();
  12024. var renderingGroupId = mesh.renderingGroupId || 0;
  12025. if (!this._renderingGroups[renderingGroupId]) {
  12026. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  12027. }
  12028. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  12029. };
  12030. RenderingManager.MAX_RENDERINGGROUPS = 4;
  12031. return RenderingManager;
  12032. })();
  12033. BABYLON.RenderingManager = RenderingManager;
  12034. })(BABYLON || (BABYLON = {}));
  12035. //# sourceMappingURL=babylon.renderingManager.js.map
  12036. var BABYLON;
  12037. (function (BABYLON) {
  12038. var Texture = (function (_super) {
  12039. __extends(Texture, _super);
  12040. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  12041. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  12042. if (onLoad === void 0) { onLoad = null; }
  12043. if (onError === void 0) { onError = null; }
  12044. if (buffer === void 0) { buffer = null; }
  12045. if (deleteBuffer === void 0) { deleteBuffer = false; }
  12046. _super.call(this, scene);
  12047. this.uOffset = 0;
  12048. this.vOffset = 0;
  12049. this.uScale = 1.0;
  12050. this.vScale = 1.0;
  12051. this.uAng = 0;
  12052. this.vAng = 0;
  12053. this.wAng = 0;
  12054. this.name = url;
  12055. this.url = url;
  12056. this._noMipmap = noMipmap;
  12057. this._invertY = invertY;
  12058. this._samplingMode = samplingMode;
  12059. this._buffer = buffer;
  12060. this._deleteBuffer = deleteBuffer;
  12061. if (!url) {
  12062. return;
  12063. }
  12064. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  12065. if (!this._texture) {
  12066. if (!scene.useDelayedTextureLoading) {
  12067. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  12068. if (deleteBuffer) {
  12069. delete this._buffer;
  12070. }
  12071. }
  12072. else {
  12073. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  12074. }
  12075. }
  12076. }
  12077. Texture.prototype.delayLoad = function () {
  12078. if (this.delayLoadState != BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  12079. return;
  12080. }
  12081. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  12082. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  12083. if (!this._texture) {
  12084. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  12085. if (this._deleteBuffer) {
  12086. delete this._buffer;
  12087. }
  12088. }
  12089. };
  12090. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  12091. x -= this.uOffset + 0.5;
  12092. y -= this.vOffset + 0.5;
  12093. z -= 0.5;
  12094. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  12095. t.x *= this.uScale;
  12096. t.y *= this.vScale;
  12097. t.x += 0.5;
  12098. t.y += 0.5;
  12099. t.z += 0.5;
  12100. };
  12101. Texture.prototype.getTextureMatrix = function () {
  12102. 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) {
  12103. return this._cachedTextureMatrix;
  12104. }
  12105. this._cachedUOffset = this.uOffset;
  12106. this._cachedVOffset = this.vOffset;
  12107. this._cachedUScale = this.uScale;
  12108. this._cachedVScale = this.vScale;
  12109. this._cachedUAng = this.uAng;
  12110. this._cachedVAng = this.vAng;
  12111. this._cachedWAng = this.wAng;
  12112. if (!this._cachedTextureMatrix) {
  12113. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  12114. this._rowGenerationMatrix = new BABYLON.Matrix();
  12115. this._t0 = BABYLON.Vector3.Zero();
  12116. this._t1 = BABYLON.Vector3.Zero();
  12117. this._t2 = BABYLON.Vector3.Zero();
  12118. }
  12119. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  12120. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  12121. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  12122. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  12123. this._t1.subtractInPlace(this._t0);
  12124. this._t2.subtractInPlace(this._t0);
  12125. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  12126. this._cachedTextureMatrix.m[0] = this._t1.x;
  12127. this._cachedTextureMatrix.m[1] = this._t1.y;
  12128. this._cachedTextureMatrix.m[2] = this._t1.z;
  12129. this._cachedTextureMatrix.m[4] = this._t2.x;
  12130. this._cachedTextureMatrix.m[5] = this._t2.y;
  12131. this._cachedTextureMatrix.m[6] = this._t2.z;
  12132. this._cachedTextureMatrix.m[8] = this._t0.x;
  12133. this._cachedTextureMatrix.m[9] = this._t0.y;
  12134. this._cachedTextureMatrix.m[10] = this._t0.z;
  12135. return this._cachedTextureMatrix;
  12136. };
  12137. Texture.prototype.getReflectionTextureMatrix = function () {
  12138. if (this.uOffset === this._cachedUOffset && this.vOffset === this._cachedVOffset && this.uScale === this._cachedUScale && this.vScale === this._cachedVScale && this.coordinatesMode === this._cachedCoordinatesMode) {
  12139. return this._cachedTextureMatrix;
  12140. }
  12141. if (!this._cachedTextureMatrix) {
  12142. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  12143. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  12144. }
  12145. this._cachedCoordinatesMode = this.coordinatesMode;
  12146. switch (this.coordinatesMode) {
  12147. case BABYLON.Texture.SPHERICAL_MODE:
  12148. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  12149. this._cachedTextureMatrix[0] = -0.5 * this.uScale;
  12150. this._cachedTextureMatrix[5] = -0.5 * this.vScale;
  12151. this._cachedTextureMatrix[12] = 0.5 + this.uOffset;
  12152. this._cachedTextureMatrix[13] = 0.5 + this.vOffset;
  12153. break;
  12154. case BABYLON.Texture.PLANAR_MODE:
  12155. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  12156. this._cachedTextureMatrix[0] = this.uScale;
  12157. this._cachedTextureMatrix[5] = this.vScale;
  12158. this._cachedTextureMatrix[12] = this.uOffset;
  12159. this._cachedTextureMatrix[13] = this.vOffset;
  12160. break;
  12161. case BABYLON.Texture.PROJECTION_MODE:
  12162. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  12163. this._projectionModeMatrix.m[0] = 0.5;
  12164. this._projectionModeMatrix.m[5] = -0.5;
  12165. this._projectionModeMatrix.m[10] = 0.0;
  12166. this._projectionModeMatrix.m[12] = 0.5;
  12167. this._projectionModeMatrix.m[13] = 0.5;
  12168. this._projectionModeMatrix.m[14] = 1.0;
  12169. this._projectionModeMatrix.m[15] = 1.0;
  12170. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  12171. break;
  12172. default:
  12173. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  12174. break;
  12175. }
  12176. return this._cachedTextureMatrix;
  12177. };
  12178. Texture.prototype.clone = function () {
  12179. var newTexture = new BABYLON.Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY, this._samplingMode);
  12180. // Base texture
  12181. newTexture.hasAlpha = this.hasAlpha;
  12182. newTexture.level = this.level;
  12183. newTexture.wrapU = this.wrapU;
  12184. newTexture.wrapV = this.wrapV;
  12185. newTexture.coordinatesIndex = this.coordinatesIndex;
  12186. newTexture.coordinatesMode = this.coordinatesMode;
  12187. // Texture
  12188. newTexture.uOffset = this.uOffset;
  12189. newTexture.vOffset = this.vOffset;
  12190. newTexture.uScale = this.uScale;
  12191. newTexture.vScale = this.vScale;
  12192. newTexture.uAng = this.uAng;
  12193. newTexture.vAng = this.vAng;
  12194. newTexture.wAng = this.wAng;
  12195. return newTexture;
  12196. };
  12197. // Statics
  12198. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  12199. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  12200. if (onLoad === void 0) { onLoad = null; }
  12201. if (onError === void 0) { onError = null; }
  12202. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  12203. };
  12204. // Constants
  12205. Texture.NEAREST_SAMPLINGMODE = 1;
  12206. Texture.BILINEAR_SAMPLINGMODE = 2;
  12207. Texture.TRILINEAR_SAMPLINGMODE = 3;
  12208. Texture.EXPLICIT_MODE = 0;
  12209. Texture.SPHERICAL_MODE = 1;
  12210. Texture.PLANAR_MODE = 2;
  12211. Texture.CUBIC_MODE = 3;
  12212. Texture.PROJECTION_MODE = 4;
  12213. Texture.SKYBOX_MODE = 5;
  12214. Texture.CLAMP_ADDRESSMODE = 0;
  12215. Texture.WRAP_ADDRESSMODE = 1;
  12216. Texture.MIRROR_ADDRESSMODE = 2;
  12217. return Texture;
  12218. })(BABYLON.BaseTexture);
  12219. BABYLON.Texture = Texture;
  12220. })(BABYLON || (BABYLON = {}));
  12221. //# sourceMappingURL=babylon.texture.js.map
  12222. var BABYLON;
  12223. (function (BABYLON) {
  12224. var CubeTexture = (function (_super) {
  12225. __extends(CubeTexture, _super);
  12226. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  12227. _super.call(this, scene);
  12228. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  12229. this.name = rootUrl;
  12230. this.url = rootUrl;
  12231. this._noMipmap = noMipmap;
  12232. this.hasAlpha = false;
  12233. this._texture = this._getFromCache(rootUrl, noMipmap);
  12234. if (!extensions) {
  12235. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  12236. }
  12237. this._extensions = extensions;
  12238. if (!this._texture) {
  12239. if (!scene.useDelayedTextureLoading) {
  12240. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  12241. }
  12242. else {
  12243. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  12244. }
  12245. }
  12246. this.isCube = true;
  12247. this._textureMatrix = BABYLON.Matrix.Identity();
  12248. }
  12249. CubeTexture.prototype.clone = function () {
  12250. var newTexture = new CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  12251. // Base texture
  12252. newTexture.level = this.level;
  12253. newTexture.wrapU = this.wrapU;
  12254. newTexture.wrapV = this.wrapV;
  12255. newTexture.coordinatesIndex = this.coordinatesIndex;
  12256. newTexture.coordinatesMode = this.coordinatesMode;
  12257. return newTexture;
  12258. };
  12259. // Methods
  12260. CubeTexture.prototype.delayLoad = function () {
  12261. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  12262. return;
  12263. }
  12264. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  12265. this._texture = this._getFromCache(this.url, this._noMipmap);
  12266. if (!this._texture) {
  12267. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  12268. }
  12269. };
  12270. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  12271. return this._textureMatrix;
  12272. };
  12273. return CubeTexture;
  12274. })(BABYLON.BaseTexture);
  12275. BABYLON.CubeTexture = CubeTexture;
  12276. })(BABYLON || (BABYLON = {}));
  12277. //# sourceMappingURL=babylon.cubeTexture.js.map
  12278. var BABYLON;
  12279. (function (BABYLON) {
  12280. var RenderTargetTexture = (function (_super) {
  12281. __extends(RenderTargetTexture, _super);
  12282. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type) {
  12283. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  12284. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  12285. _super.call(this, null, scene, !generateMipMaps);
  12286. this.renderList = new Array();
  12287. this.renderParticles = true;
  12288. this.renderSprites = false;
  12289. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  12290. this._currentRefreshId = -1;
  12291. this._refreshRate = 1;
  12292. this.name = name;
  12293. this.isRenderTarget = true;
  12294. this._size = size;
  12295. this._generateMipMaps = generateMipMaps;
  12296. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  12297. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  12298. // Rendering groups
  12299. this._renderingManager = new BABYLON.RenderingManager(scene);
  12300. }
  12301. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  12302. this._currentRefreshId = -1;
  12303. };
  12304. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  12305. get: function () {
  12306. return this._refreshRate;
  12307. },
  12308. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  12309. set: function (value) {
  12310. this._refreshRate = value;
  12311. this.resetRefreshCounter();
  12312. },
  12313. enumerable: true,
  12314. configurable: true
  12315. });
  12316. RenderTargetTexture.prototype._shouldRender = function () {
  12317. if (this._currentRefreshId === -1) {
  12318. this._currentRefreshId = 1;
  12319. return true;
  12320. }
  12321. if (this.refreshRate === this._currentRefreshId) {
  12322. this._currentRefreshId = 1;
  12323. return true;
  12324. }
  12325. this._currentRefreshId++;
  12326. return false;
  12327. };
  12328. RenderTargetTexture.prototype.isReady = function () {
  12329. if (!this.getScene().renderTargetsEnabled) {
  12330. return false;
  12331. }
  12332. return _super.prototype.isReady.call(this);
  12333. };
  12334. RenderTargetTexture.prototype.getRenderSize = function () {
  12335. return this._size;
  12336. };
  12337. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  12338. get: function () {
  12339. return true;
  12340. },
  12341. enumerable: true,
  12342. configurable: true
  12343. });
  12344. RenderTargetTexture.prototype.scale = function (ratio) {
  12345. var newSize = this._size * ratio;
  12346. this.resize(newSize, this._generateMipMaps);
  12347. };
  12348. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  12349. this.releaseInternalTexture();
  12350. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  12351. };
  12352. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  12353. var scene = this.getScene();
  12354. var engine = scene.getEngine();
  12355. if (this._waitingRenderList) {
  12356. this.renderList = [];
  12357. for (var index = 0; index < this._waitingRenderList.length; index++) {
  12358. var id = this._waitingRenderList[index];
  12359. this.renderList.push(scene.getMeshByID(id));
  12360. }
  12361. delete this._waitingRenderList;
  12362. }
  12363. if (this.renderList && this.renderList.length === 0) {
  12364. return;
  12365. }
  12366. // Bind
  12367. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  12368. engine.bindFramebuffer(this._texture);
  12369. }
  12370. this._renderingManager.reset();
  12371. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  12372. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  12373. var mesh = currentRenderList[meshIndex];
  12374. if (mesh) {
  12375. if (!mesh.isReady()) {
  12376. // Reset _currentRefreshId
  12377. this.resetRefreshCounter();
  12378. continue;
  12379. }
  12380. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  12381. mesh._activate(scene.getRenderId());
  12382. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  12383. var subMesh = mesh.subMeshes[subIndex];
  12384. scene._activeVertices += subMesh.indexCount;
  12385. this._renderingManager.dispatch(subMesh);
  12386. }
  12387. }
  12388. }
  12389. }
  12390. if (this.onBeforeRender) {
  12391. this.onBeforeRender();
  12392. }
  12393. // Clear
  12394. engine.clear(scene.clearColor, true, true);
  12395. if (!this._doNotChangeAspectRatio) {
  12396. scene.updateTransformMatrix(true);
  12397. }
  12398. // Render
  12399. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  12400. if (useCameraPostProcess) {
  12401. scene.postProcessManager._finalizeFrame(false, this._texture);
  12402. }
  12403. if (!this._doNotChangeAspectRatio) {
  12404. scene.updateTransformMatrix(true);
  12405. }
  12406. if (this.onAfterRender) {
  12407. this.onAfterRender();
  12408. }
  12409. // Dump ?
  12410. if (dumpForDebug) {
  12411. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  12412. }
  12413. // Unbind
  12414. engine.unBindFramebuffer(this._texture);
  12415. if (this.onAfterUnbind) {
  12416. this.onAfterUnbind();
  12417. }
  12418. };
  12419. RenderTargetTexture.prototype.clone = function () {
  12420. var textureSize = this.getSize();
  12421. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  12422. // Base texture
  12423. newTexture.hasAlpha = this.hasAlpha;
  12424. newTexture.level = this.level;
  12425. // RenderTarget Texture
  12426. newTexture.coordinatesMode = this.coordinatesMode;
  12427. newTexture.renderList = this.renderList.slice(0);
  12428. return newTexture;
  12429. };
  12430. return RenderTargetTexture;
  12431. })(BABYLON.Texture);
  12432. BABYLON.RenderTargetTexture = RenderTargetTexture;
  12433. })(BABYLON || (BABYLON = {}));
  12434. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  12435. var BABYLON;
  12436. (function (BABYLON) {
  12437. var ProceduralTexture = (function (_super) {
  12438. __extends(ProceduralTexture, _super);
  12439. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps) {
  12440. if (generateMipMaps === void 0) { generateMipMaps = true; }
  12441. _super.call(this, null, scene, !generateMipMaps);
  12442. this._currentRefreshId = -1;
  12443. this._refreshRate = 1;
  12444. this._vertexDeclaration = [2];
  12445. this._vertexStrideSize = 2 * 4;
  12446. this._uniforms = new Array();
  12447. this._samplers = new Array();
  12448. this._textures = new Array();
  12449. this._floats = new Array();
  12450. this._floatsArrays = {};
  12451. this._colors3 = new Array();
  12452. this._colors4 = new Array();
  12453. this._vectors2 = new Array();
  12454. this._vectors3 = new Array();
  12455. this._matrices = new Array();
  12456. this._fallbackTextureUsed = false;
  12457. scene._proceduralTextures.push(this);
  12458. this.name = name;
  12459. this.isRenderTarget = true;
  12460. this._size = size;
  12461. this._generateMipMaps = generateMipMaps;
  12462. this.setFragment(fragment);
  12463. this._fallbackTexture = fallbackTexture;
  12464. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  12465. // VBO
  12466. var vertices = [];
  12467. vertices.push(1, 1);
  12468. vertices.push(-1, 1);
  12469. vertices.push(-1, -1);
  12470. vertices.push(1, -1);
  12471. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  12472. // Indices
  12473. var indices = [];
  12474. indices.push(0);
  12475. indices.push(1);
  12476. indices.push(2);
  12477. indices.push(0);
  12478. indices.push(2);
  12479. indices.push(3);
  12480. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  12481. }
  12482. ProceduralTexture.prototype.reset = function () {
  12483. if (this._effect === undefined) {
  12484. return;
  12485. }
  12486. var engine = this.getScene().getEngine();
  12487. engine._releaseEffect(this._effect);
  12488. };
  12489. ProceduralTexture.prototype.isReady = function () {
  12490. var _this = this;
  12491. var engine = this.getScene().getEngine();
  12492. var shaders;
  12493. if (!this._fragment) {
  12494. return false;
  12495. }
  12496. if (this._fallbackTextureUsed) {
  12497. return true;
  12498. }
  12499. if (this._fragment.fragmentElement !== undefined) {
  12500. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  12501. }
  12502. else {
  12503. shaders = { vertex: "procedural", fragment: this._fragment };
  12504. }
  12505. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  12506. _this.releaseInternalTexture();
  12507. if (_this._fallbackTexture) {
  12508. _this._texture = _this._fallbackTexture._texture;
  12509. _this._texture.references++;
  12510. }
  12511. _this._fallbackTextureUsed = true;
  12512. });
  12513. return this._effect.isReady();
  12514. };
  12515. ProceduralTexture.prototype.resetRefreshCounter = function () {
  12516. this._currentRefreshId = -1;
  12517. };
  12518. ProceduralTexture.prototype.setFragment = function (fragment) {
  12519. this._fragment = fragment;
  12520. };
  12521. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  12522. get: function () {
  12523. return this._refreshRate;
  12524. },
  12525. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  12526. set: function (value) {
  12527. this._refreshRate = value;
  12528. this.resetRefreshCounter();
  12529. },
  12530. enumerable: true,
  12531. configurable: true
  12532. });
  12533. ProceduralTexture.prototype._shouldRender = function () {
  12534. if (!this.isReady() || !this._texture) {
  12535. return false;
  12536. }
  12537. if (this._fallbackTextureUsed) {
  12538. return false;
  12539. }
  12540. if (this._currentRefreshId === -1) {
  12541. this._currentRefreshId = 1;
  12542. return true;
  12543. }
  12544. if (this.refreshRate === this._currentRefreshId) {
  12545. this._currentRefreshId = 1;
  12546. return true;
  12547. }
  12548. this._currentRefreshId++;
  12549. return false;
  12550. };
  12551. ProceduralTexture.prototype.getRenderSize = function () {
  12552. return this._size;
  12553. };
  12554. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  12555. if (this._fallbackTextureUsed) {
  12556. return;
  12557. }
  12558. this.releaseInternalTexture();
  12559. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  12560. };
  12561. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  12562. if (this._uniforms.indexOf(uniformName) === -1) {
  12563. this._uniforms.push(uniformName);
  12564. }
  12565. };
  12566. ProceduralTexture.prototype.setTexture = function (name, texture) {
  12567. if (this._samplers.indexOf(name) === -1) {
  12568. this._samplers.push(name);
  12569. }
  12570. this._textures[name] = texture;
  12571. return this;
  12572. };
  12573. ProceduralTexture.prototype.setFloat = function (name, value) {
  12574. this._checkUniform(name);
  12575. this._floats[name] = value;
  12576. return this;
  12577. };
  12578. ProceduralTexture.prototype.setFloats = function (name, value) {
  12579. this._checkUniform(name);
  12580. this._floatsArrays[name] = value;
  12581. return this;
  12582. };
  12583. ProceduralTexture.prototype.setColor3 = function (name, value) {
  12584. this._checkUniform(name);
  12585. this._colors3[name] = value;
  12586. return this;
  12587. };
  12588. ProceduralTexture.prototype.setColor4 = function (name, value) {
  12589. this._checkUniform(name);
  12590. this._colors4[name] = value;
  12591. return this;
  12592. };
  12593. ProceduralTexture.prototype.setVector2 = function (name, value) {
  12594. this._checkUniform(name);
  12595. this._vectors2[name] = value;
  12596. return this;
  12597. };
  12598. ProceduralTexture.prototype.setVector3 = function (name, value) {
  12599. this._checkUniform(name);
  12600. this._vectors3[name] = value;
  12601. return this;
  12602. };
  12603. ProceduralTexture.prototype.setMatrix = function (name, value) {
  12604. this._checkUniform(name);
  12605. this._matrices[name] = value;
  12606. return this;
  12607. };
  12608. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  12609. var scene = this.getScene();
  12610. var engine = scene.getEngine();
  12611. engine.bindFramebuffer(this._texture);
  12612. // Clear
  12613. engine.clear(scene.clearColor, true, true);
  12614. // Render
  12615. engine.enableEffect(this._effect);
  12616. engine.setState(false);
  12617. for (var name in this._textures) {
  12618. this._effect.setTexture(name, this._textures[name]);
  12619. }
  12620. for (name in this._floats) {
  12621. this._effect.setFloat(name, this._floats[name]);
  12622. }
  12623. for (name in this._floatsArrays) {
  12624. this._effect.setArray(name, this._floatsArrays[name]);
  12625. }
  12626. for (name in this._colors3) {
  12627. this._effect.setColor3(name, this._colors3[name]);
  12628. }
  12629. for (name in this._colors4) {
  12630. var color = this._colors4[name];
  12631. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  12632. }
  12633. for (name in this._vectors2) {
  12634. this._effect.setVector2(name, this._vectors2[name]);
  12635. }
  12636. for (name in this._vectors3) {
  12637. this._effect.setVector3(name, this._vectors3[name]);
  12638. }
  12639. for (name in this._matrices) {
  12640. this._effect.setMatrix(name, this._matrices[name]);
  12641. }
  12642. // VBOs
  12643. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  12644. // Draw order
  12645. engine.draw(true, 0, 6);
  12646. // Unbind
  12647. engine.unBindFramebuffer(this._texture);
  12648. };
  12649. ProceduralTexture.prototype.clone = function () {
  12650. var textureSize = this.getSize();
  12651. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  12652. // Base texture
  12653. newTexture.hasAlpha = this.hasAlpha;
  12654. newTexture.level = this.level;
  12655. // RenderTarget Texture
  12656. newTexture.coordinatesMode = this.coordinatesMode;
  12657. return newTexture;
  12658. };
  12659. ProceduralTexture.prototype.dispose = function () {
  12660. var index = this.getScene()._proceduralTextures.indexOf(this);
  12661. if (index >= 0) {
  12662. this.getScene()._proceduralTextures.splice(index, 1);
  12663. }
  12664. _super.prototype.dispose.call(this);
  12665. };
  12666. return ProceduralTexture;
  12667. })(BABYLON.Texture);
  12668. BABYLON.ProceduralTexture = ProceduralTexture;
  12669. })(BABYLON || (BABYLON = {}));
  12670. //# sourceMappingURL=babylon.proceduralTexture.js.map
  12671. var BABYLON;
  12672. (function (BABYLON) {
  12673. var WoodProceduralTexture = (function (_super) {
  12674. __extends(WoodProceduralTexture, _super);
  12675. function WoodProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12676. _super.call(this, name, size, "wood", scene, fallbackTexture, generateMipMaps);
  12677. this._ampScale = 100.0;
  12678. this._woodColor = new BABYLON.Color3(0.32, 0.17, 0.09);
  12679. this.updateShaderUniforms();
  12680. this.refreshRate = 0;
  12681. }
  12682. WoodProceduralTexture.prototype.updateShaderUniforms = function () {
  12683. this.setFloat("ampScale", this._ampScale);
  12684. this.setColor3("woodColor", this._woodColor);
  12685. };
  12686. Object.defineProperty(WoodProceduralTexture.prototype, "ampScale", {
  12687. get: function () {
  12688. return this._ampScale;
  12689. },
  12690. set: function (value) {
  12691. this._ampScale = value;
  12692. this.updateShaderUniforms();
  12693. },
  12694. enumerable: true,
  12695. configurable: true
  12696. });
  12697. Object.defineProperty(WoodProceduralTexture.prototype, "woodColor", {
  12698. get: function () {
  12699. return this._woodColor;
  12700. },
  12701. set: function (value) {
  12702. this._woodColor = value;
  12703. this.updateShaderUniforms();
  12704. },
  12705. enumerable: true,
  12706. configurable: true
  12707. });
  12708. return WoodProceduralTexture;
  12709. })(BABYLON.ProceduralTexture);
  12710. BABYLON.WoodProceduralTexture = WoodProceduralTexture;
  12711. var FireProceduralTexture = (function (_super) {
  12712. __extends(FireProceduralTexture, _super);
  12713. function FireProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12714. _super.call(this, name, size, "fire", scene, fallbackTexture, generateMipMaps);
  12715. this._time = 0.0;
  12716. this._speed = new BABYLON.Vector2(0.5, 0.3);
  12717. this._shift = 1.6;
  12718. this._autoGenerateTime = true;
  12719. this._alphaThreshold = 0.5;
  12720. this._fireColors = FireProceduralTexture.RedFireColors;
  12721. this.updateShaderUniforms();
  12722. this.refreshRate = 1;
  12723. }
  12724. FireProceduralTexture.prototype.updateShaderUniforms = function () {
  12725. this.setFloat("time", this._time);
  12726. this.setVector2("speed", this._speed);
  12727. this.setFloat("shift", this._shift);
  12728. this.setColor3("c1", this._fireColors[0]);
  12729. this.setColor3("c2", this._fireColors[1]);
  12730. this.setColor3("c3", this._fireColors[2]);
  12731. this.setColor3("c4", this._fireColors[3]);
  12732. this.setColor3("c5", this._fireColors[4]);
  12733. this.setColor3("c6", this._fireColors[5]);
  12734. this.setFloat("alphaThreshold", this._alphaThreshold);
  12735. };
  12736. FireProceduralTexture.prototype.render = function (useCameraPostProcess) {
  12737. if (this._autoGenerateTime) {
  12738. this._time += this.getScene().getAnimationRatio() * 0.03;
  12739. this.updateShaderUniforms();
  12740. }
  12741. _super.prototype.render.call(this, useCameraPostProcess);
  12742. };
  12743. Object.defineProperty(FireProceduralTexture, "PurpleFireColors", {
  12744. get: function () {
  12745. return [
  12746. new BABYLON.Color3(0.5, 0.0, 1.0),
  12747. new BABYLON.Color3(0.9, 0.0, 1.0),
  12748. new BABYLON.Color3(0.2, 0.0, 1.0),
  12749. new BABYLON.Color3(1.0, 0.9, 1.0),
  12750. new BABYLON.Color3(0.1, 0.1, 1.0),
  12751. new BABYLON.Color3(0.9, 0.9, 1.0)
  12752. ];
  12753. },
  12754. enumerable: true,
  12755. configurable: true
  12756. });
  12757. Object.defineProperty(FireProceduralTexture, "GreenFireColors", {
  12758. get: function () {
  12759. return [
  12760. new BABYLON.Color3(0.5, 1.0, 0.0),
  12761. new BABYLON.Color3(0.5, 1.0, 0.0),
  12762. new BABYLON.Color3(0.3, 0.4, 0.0),
  12763. new BABYLON.Color3(0.5, 1.0, 0.0),
  12764. new BABYLON.Color3(0.2, 0.0, 0.0),
  12765. new BABYLON.Color3(0.5, 1.0, 0.0)
  12766. ];
  12767. },
  12768. enumerable: true,
  12769. configurable: true
  12770. });
  12771. Object.defineProperty(FireProceduralTexture, "RedFireColors", {
  12772. get: function () {
  12773. return [
  12774. new BABYLON.Color3(0.5, 0.0, 0.1),
  12775. new BABYLON.Color3(0.9, 0.0, 0.0),
  12776. new BABYLON.Color3(0.2, 0.0, 0.0),
  12777. new BABYLON.Color3(1.0, 0.9, 0.0),
  12778. new BABYLON.Color3(0.1, 0.1, 0.1),
  12779. new BABYLON.Color3(0.9, 0.9, 0.9)
  12780. ];
  12781. },
  12782. enumerable: true,
  12783. configurable: true
  12784. });
  12785. Object.defineProperty(FireProceduralTexture, "BlueFireColors", {
  12786. get: function () {
  12787. return [
  12788. new BABYLON.Color3(0.1, 0.0, 0.5),
  12789. new BABYLON.Color3(0.0, 0.0, 0.5),
  12790. new BABYLON.Color3(0.1, 0.0, 0.2),
  12791. new BABYLON.Color3(0.0, 0.0, 1.0),
  12792. new BABYLON.Color3(0.1, 0.2, 0.3),
  12793. new BABYLON.Color3(0.0, 0.2, 0.9)
  12794. ];
  12795. },
  12796. enumerable: true,
  12797. configurable: true
  12798. });
  12799. Object.defineProperty(FireProceduralTexture.prototype, "fireColors", {
  12800. get: function () {
  12801. return this._fireColors;
  12802. },
  12803. set: function (value) {
  12804. this._fireColors = value;
  12805. this.updateShaderUniforms();
  12806. },
  12807. enumerable: true,
  12808. configurable: true
  12809. });
  12810. Object.defineProperty(FireProceduralTexture.prototype, "time", {
  12811. get: function () {
  12812. return this._time;
  12813. },
  12814. set: function (value) {
  12815. this._time = value;
  12816. this.updateShaderUniforms();
  12817. },
  12818. enumerable: true,
  12819. configurable: true
  12820. });
  12821. Object.defineProperty(FireProceduralTexture.prototype, "speed", {
  12822. get: function () {
  12823. return this._speed;
  12824. },
  12825. set: function (value) {
  12826. this._speed = value;
  12827. this.updateShaderUniforms();
  12828. },
  12829. enumerable: true,
  12830. configurable: true
  12831. });
  12832. Object.defineProperty(FireProceduralTexture.prototype, "shift", {
  12833. get: function () {
  12834. return this._shift;
  12835. },
  12836. set: function (value) {
  12837. this._shift = value;
  12838. this.updateShaderUniforms();
  12839. },
  12840. enumerable: true,
  12841. configurable: true
  12842. });
  12843. Object.defineProperty(FireProceduralTexture.prototype, "alphaThreshold", {
  12844. get: function () {
  12845. return this._alphaThreshold;
  12846. },
  12847. set: function (value) {
  12848. this._alphaThreshold = value;
  12849. this.updateShaderUniforms();
  12850. },
  12851. enumerable: true,
  12852. configurable: true
  12853. });
  12854. return FireProceduralTexture;
  12855. })(BABYLON.ProceduralTexture);
  12856. BABYLON.FireProceduralTexture = FireProceduralTexture;
  12857. var CloudProceduralTexture = (function (_super) {
  12858. __extends(CloudProceduralTexture, _super);
  12859. function CloudProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12860. _super.call(this, name, size, "cloud", scene, fallbackTexture, generateMipMaps);
  12861. this._skyColor = new BABYLON.Color3(0.15, 0.68, 1.0);
  12862. this._cloudColor = new BABYLON.Color3(1, 1, 1);
  12863. this.updateShaderUniforms();
  12864. this.refreshRate = 0;
  12865. }
  12866. CloudProceduralTexture.prototype.updateShaderUniforms = function () {
  12867. this.setColor3("skyColor", this._skyColor);
  12868. this.setColor3("cloudColor", this._cloudColor);
  12869. };
  12870. Object.defineProperty(CloudProceduralTexture.prototype, "skyColor", {
  12871. get: function () {
  12872. return this._skyColor;
  12873. },
  12874. set: function (value) {
  12875. this._skyColor = value;
  12876. this.updateShaderUniforms();
  12877. },
  12878. enumerable: true,
  12879. configurable: true
  12880. });
  12881. Object.defineProperty(CloudProceduralTexture.prototype, "cloudColor", {
  12882. get: function () {
  12883. return this._cloudColor;
  12884. },
  12885. set: function (value) {
  12886. this._cloudColor = value;
  12887. this.updateShaderUniforms();
  12888. },
  12889. enumerable: true,
  12890. configurable: true
  12891. });
  12892. return CloudProceduralTexture;
  12893. })(BABYLON.ProceduralTexture);
  12894. BABYLON.CloudProceduralTexture = CloudProceduralTexture;
  12895. var GrassProceduralTexture = (function (_super) {
  12896. __extends(GrassProceduralTexture, _super);
  12897. function GrassProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12898. _super.call(this, name, size, "grass", scene, fallbackTexture, generateMipMaps);
  12899. this._herb1 = new BABYLON.Color3(0.29, 0.38, 0.02);
  12900. this._herb2 = new BABYLON.Color3(0.36, 0.49, 0.09);
  12901. this._herb3 = new BABYLON.Color3(0.51, 0.6, 0.28);
  12902. this._groundColor = new BABYLON.Color3(1, 1, 1);
  12903. this._grassColors = [
  12904. new BABYLON.Color3(0.29, 0.38, 0.02),
  12905. new BABYLON.Color3(0.36, 0.49, 0.09),
  12906. new BABYLON.Color3(0.51, 0.6, 0.28)
  12907. ];
  12908. this.updateShaderUniforms();
  12909. this.refreshRate = 0;
  12910. }
  12911. GrassProceduralTexture.prototype.updateShaderUniforms = function () {
  12912. this.setColor3("herb1Color", this._grassColors[0]);
  12913. this.setColor3("herb2Color", this._grassColors[1]);
  12914. this.setColor3("herb3Color", this._grassColors[2]);
  12915. this.setColor3("groundColor", this._groundColor);
  12916. };
  12917. Object.defineProperty(GrassProceduralTexture.prototype, "grassColors", {
  12918. get: function () {
  12919. return this._grassColors;
  12920. },
  12921. set: function (value) {
  12922. this._grassColors = value;
  12923. this.updateShaderUniforms();
  12924. },
  12925. enumerable: true,
  12926. configurable: true
  12927. });
  12928. Object.defineProperty(GrassProceduralTexture.prototype, "groundColor", {
  12929. get: function () {
  12930. return this._groundColor;
  12931. },
  12932. set: function (value) {
  12933. this.groundColor = value;
  12934. this.updateShaderUniforms();
  12935. },
  12936. enumerable: true,
  12937. configurable: true
  12938. });
  12939. return GrassProceduralTexture;
  12940. })(BABYLON.ProceduralTexture);
  12941. BABYLON.GrassProceduralTexture = GrassProceduralTexture;
  12942. var RoadProceduralTexture = (function (_super) {
  12943. __extends(RoadProceduralTexture, _super);
  12944. function RoadProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12945. _super.call(this, name, size, "road", scene, fallbackTexture, generateMipMaps);
  12946. this._roadColor = new BABYLON.Color3(0.53, 0.53, 0.53);
  12947. this.updateShaderUniforms();
  12948. this.refreshRate = 0;
  12949. }
  12950. RoadProceduralTexture.prototype.updateShaderUniforms = function () {
  12951. this.setColor3("roadColor", this._roadColor);
  12952. };
  12953. Object.defineProperty(RoadProceduralTexture.prototype, "roadColor", {
  12954. get: function () {
  12955. return this._roadColor;
  12956. },
  12957. set: function (value) {
  12958. this._roadColor = value;
  12959. this.updateShaderUniforms();
  12960. },
  12961. enumerable: true,
  12962. configurable: true
  12963. });
  12964. return RoadProceduralTexture;
  12965. })(BABYLON.ProceduralTexture);
  12966. BABYLON.RoadProceduralTexture = RoadProceduralTexture;
  12967. var BrickProceduralTexture = (function (_super) {
  12968. __extends(BrickProceduralTexture, _super);
  12969. function BrickProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12970. _super.call(this, name, size, "brick", scene, fallbackTexture, generateMipMaps);
  12971. this._numberOfBricksHeight = 15;
  12972. this._numberOfBricksWidth = 5;
  12973. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  12974. this._brickColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  12975. this.updateShaderUniforms();
  12976. this.refreshRate = 0;
  12977. }
  12978. BrickProceduralTexture.prototype.updateShaderUniforms = function () {
  12979. this.setFloat("numberOfBricksHeight", this._numberOfBricksHeight);
  12980. this.setFloat("numberOfBricksWidth", this._numberOfBricksWidth);
  12981. this.setColor3("brickColor", this._brickColor);
  12982. this.setColor3("jointColor", this._jointColor);
  12983. };
  12984. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksHeight", {
  12985. get: function () {
  12986. return this._numberOfBricksHeight;
  12987. },
  12988. enumerable: true,
  12989. configurable: true
  12990. });
  12991. Object.defineProperty(BrickProceduralTexture.prototype, "cloudColor", {
  12992. set: function (value) {
  12993. this._numberOfBricksHeight = value;
  12994. this.updateShaderUniforms();
  12995. },
  12996. enumerable: true,
  12997. configurable: true
  12998. });
  12999. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksWidth", {
  13000. get: function () {
  13001. return this._numberOfBricksWidth;
  13002. },
  13003. set: function (value) {
  13004. this._numberOfBricksHeight = value;
  13005. this.updateShaderUniforms();
  13006. },
  13007. enumerable: true,
  13008. configurable: true
  13009. });
  13010. Object.defineProperty(BrickProceduralTexture.prototype, "jointColor", {
  13011. get: function () {
  13012. return this._jointColor;
  13013. },
  13014. set: function (value) {
  13015. this._jointColor = value;
  13016. this.updateShaderUniforms();
  13017. },
  13018. enumerable: true,
  13019. configurable: true
  13020. });
  13021. Object.defineProperty(BrickProceduralTexture.prototype, "brickColor", {
  13022. get: function () {
  13023. return this._brickColor;
  13024. },
  13025. set: function (value) {
  13026. this._brickColor = value;
  13027. this.updateShaderUniforms();
  13028. },
  13029. enumerable: true,
  13030. configurable: true
  13031. });
  13032. return BrickProceduralTexture;
  13033. })(BABYLON.ProceduralTexture);
  13034. BABYLON.BrickProceduralTexture = BrickProceduralTexture;
  13035. var MarbleProceduralTexture = (function (_super) {
  13036. __extends(MarbleProceduralTexture, _super);
  13037. function MarbleProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13038. _super.call(this, name, size, "marble", scene, fallbackTexture, generateMipMaps);
  13039. this._numberOfTilesHeight = 3;
  13040. this._numberOfTilesWidth = 3;
  13041. this._amplitude = 9.0;
  13042. this._marbleColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  13043. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  13044. this.updateShaderUniforms();
  13045. this.refreshRate = 0;
  13046. }
  13047. MarbleProceduralTexture.prototype.updateShaderUniforms = function () {
  13048. this.setFloat("numberOfTilesHeight", this._numberOfTilesHeight);
  13049. this.setFloat("numberOfTilesWidth", this._numberOfTilesWidth);
  13050. this.setFloat("amplitude", this._amplitude);
  13051. this.setColor3("marbleColor", this._marbleColor);
  13052. this.setColor3("jointColor", this._jointColor);
  13053. };
  13054. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesHeight", {
  13055. get: function () {
  13056. return this._numberOfTilesHeight;
  13057. },
  13058. set: function (value) {
  13059. this._numberOfTilesHeight = value;
  13060. this.updateShaderUniforms();
  13061. },
  13062. enumerable: true,
  13063. configurable: true
  13064. });
  13065. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesWidth", {
  13066. get: function () {
  13067. return this._numberOfTilesWidth;
  13068. },
  13069. set: function (value) {
  13070. this._numberOfTilesWidth = value;
  13071. this.updateShaderUniforms();
  13072. },
  13073. enumerable: true,
  13074. configurable: true
  13075. });
  13076. Object.defineProperty(MarbleProceduralTexture.prototype, "jointColor", {
  13077. get: function () {
  13078. return this._jointColor;
  13079. },
  13080. set: function (value) {
  13081. this._jointColor = value;
  13082. this.updateShaderUniforms();
  13083. },
  13084. enumerable: true,
  13085. configurable: true
  13086. });
  13087. Object.defineProperty(MarbleProceduralTexture.prototype, "marbleColor", {
  13088. get: function () {
  13089. return this._marbleColor;
  13090. },
  13091. set: function (value) {
  13092. this._marbleColor = value;
  13093. this.updateShaderUniforms();
  13094. },
  13095. enumerable: true,
  13096. configurable: true
  13097. });
  13098. return MarbleProceduralTexture;
  13099. })(BABYLON.ProceduralTexture);
  13100. BABYLON.MarbleProceduralTexture = MarbleProceduralTexture;
  13101. })(BABYLON || (BABYLON = {}));
  13102. //# sourceMappingURL=babylon.standardProceduralTexture.js.map
  13103. var BABYLON;
  13104. (function (BABYLON) {
  13105. var CustomProceduralTexture = (function (_super) {
  13106. __extends(CustomProceduralTexture, _super);
  13107. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  13108. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  13109. this._animate = true;
  13110. this._time = 0;
  13111. this._texturePath = texturePath;
  13112. //Try to load json
  13113. this.loadJson(texturePath);
  13114. this.refreshRate = 1;
  13115. }
  13116. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  13117. var _this = this;
  13118. var that = this;
  13119. function noConfigFile() {
  13120. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  13121. try {
  13122. that.setFragment(that._texturePath);
  13123. }
  13124. catch (ex) {
  13125. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  13126. }
  13127. }
  13128. var configFileUrl = jsonUrl + "/config.json";
  13129. var xhr = new XMLHttpRequest();
  13130. xhr.open("GET", configFileUrl, true);
  13131. xhr.addEventListener("load", function () {
  13132. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  13133. try {
  13134. _this._config = JSON.parse(xhr.response);
  13135. _this.updateShaderUniforms();
  13136. _this.updateTextures();
  13137. _this.setFragment(_this._texturePath + "/custom");
  13138. _this._animate = _this._config.animate;
  13139. _this.refreshRate = _this._config.refreshrate;
  13140. }
  13141. catch (ex) {
  13142. noConfigFile();
  13143. }
  13144. }
  13145. else {
  13146. noConfigFile();
  13147. }
  13148. }, false);
  13149. xhr.addEventListener("error", function () {
  13150. noConfigFile();
  13151. }, false);
  13152. try {
  13153. xhr.send();
  13154. }
  13155. catch (ex) {
  13156. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  13157. }
  13158. };
  13159. CustomProceduralTexture.prototype.isReady = function () {
  13160. if (!_super.prototype.isReady.call(this)) {
  13161. return false;
  13162. }
  13163. for (var name in this._textures) {
  13164. var texture = this._textures[name];
  13165. if (!texture.isReady()) {
  13166. return false;
  13167. }
  13168. }
  13169. return true;
  13170. };
  13171. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  13172. if (this._animate) {
  13173. this._time += this.getScene().getAnimationRatio() * 0.03;
  13174. this.updateShaderUniforms();
  13175. }
  13176. _super.prototype.render.call(this, useCameraPostProcess);
  13177. };
  13178. CustomProceduralTexture.prototype.updateTextures = function () {
  13179. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  13180. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  13181. }
  13182. };
  13183. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  13184. if (this._config) {
  13185. for (var j = 0; j < this._config.uniforms.length; j++) {
  13186. var uniform = this._config.uniforms[j];
  13187. switch (uniform.type) {
  13188. case "float":
  13189. this.setFloat(uniform.name, uniform.value);
  13190. break;
  13191. case "color3":
  13192. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  13193. break;
  13194. case "color4":
  13195. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  13196. break;
  13197. case "vector2":
  13198. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  13199. break;
  13200. case "vector3":
  13201. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  13202. break;
  13203. }
  13204. }
  13205. }
  13206. this.setFloat("time", this._time);
  13207. };
  13208. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  13209. get: function () {
  13210. return this._animate;
  13211. },
  13212. set: function (value) {
  13213. this._animate = value;
  13214. },
  13215. enumerable: true,
  13216. configurable: true
  13217. });
  13218. return CustomProceduralTexture;
  13219. })(BABYLON.ProceduralTexture);
  13220. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  13221. })(BABYLON || (BABYLON = {}));
  13222. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  13223. var BABYLON;
  13224. (function (BABYLON) {
  13225. var MirrorTexture = (function (_super) {
  13226. __extends(MirrorTexture, _super);
  13227. function MirrorTexture(name, size, scene, generateMipMaps) {
  13228. var _this = this;
  13229. _super.call(this, name, size, scene, generateMipMaps, true);
  13230. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  13231. this._transformMatrix = BABYLON.Matrix.Zero();
  13232. this._mirrorMatrix = BABYLON.Matrix.Zero();
  13233. this.onBeforeRender = function () {
  13234. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  13235. _this._savedViewMatrix = scene.getViewMatrix();
  13236. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  13237. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  13238. scene.clipPlane = _this.mirrorPlane;
  13239. scene.getEngine().cullBackFaces = false;
  13240. };
  13241. this.onAfterRender = function () {
  13242. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  13243. scene.getEngine().cullBackFaces = true;
  13244. delete scene.clipPlane;
  13245. };
  13246. }
  13247. MirrorTexture.prototype.clone = function () {
  13248. var textureSize = this.getSize();
  13249. var newTexture = new BABYLON.MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  13250. // Base texture
  13251. newTexture.hasAlpha = this.hasAlpha;
  13252. newTexture.level = this.level;
  13253. // Mirror Texture
  13254. newTexture.mirrorPlane = this.mirrorPlane.clone();
  13255. newTexture.renderList = this.renderList.slice(0);
  13256. return newTexture;
  13257. };
  13258. return MirrorTexture;
  13259. })(BABYLON.RenderTargetTexture);
  13260. BABYLON.MirrorTexture = MirrorTexture;
  13261. })(BABYLON || (BABYLON = {}));
  13262. //# sourceMappingURL=babylon.mirrorTexture.js.map
  13263. var BABYLON;
  13264. (function (BABYLON) {
  13265. var DynamicTexture = (function (_super) {
  13266. __extends(DynamicTexture, _super);
  13267. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  13268. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  13269. _super.call(this, null, scene, !generateMipMaps);
  13270. this.name = name;
  13271. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  13272. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  13273. this._generateMipMaps = generateMipMaps;
  13274. if (options.getContext) {
  13275. this._canvas = options;
  13276. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  13277. }
  13278. else {
  13279. this._canvas = document.createElement("canvas");
  13280. if (options.width) {
  13281. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  13282. }
  13283. else {
  13284. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  13285. }
  13286. }
  13287. var textureSize = this.getSize();
  13288. this._canvas.width = textureSize.width;
  13289. this._canvas.height = textureSize.height;
  13290. this._context = this._canvas.getContext("2d");
  13291. }
  13292. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  13293. get: function () {
  13294. return true;
  13295. },
  13296. enumerable: true,
  13297. configurable: true
  13298. });
  13299. DynamicTexture.prototype.scale = function (ratio) {
  13300. var textureSize = this.getSize();
  13301. textureSize.width *= ratio;
  13302. textureSize.height *= ratio;
  13303. this._canvas.width = textureSize.width;
  13304. this._canvas.height = textureSize.height;
  13305. this.releaseInternalTexture();
  13306. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  13307. };
  13308. DynamicTexture.prototype.getContext = function () {
  13309. return this._context;
  13310. };
  13311. DynamicTexture.prototype.clear = function () {
  13312. var size = this.getSize();
  13313. this._context.fillRect(0, 0, size.width, size.height);
  13314. };
  13315. DynamicTexture.prototype.update = function (invertY) {
  13316. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  13317. };
  13318. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  13319. if (update === void 0) { update = true; }
  13320. var size = this.getSize();
  13321. if (clearColor) {
  13322. this._context.fillStyle = clearColor;
  13323. this._context.fillRect(0, 0, size.width, size.height);
  13324. }
  13325. this._context.font = font;
  13326. if (x === null) {
  13327. var textSize = this._context.measureText(text);
  13328. x = (size.width - textSize.width) / 2;
  13329. }
  13330. this._context.fillStyle = color;
  13331. this._context.fillText(text, x, y);
  13332. if (update) {
  13333. this.update(invertY);
  13334. }
  13335. };
  13336. DynamicTexture.prototype.clone = function () {
  13337. var textureSize = this.getSize();
  13338. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  13339. // Base texture
  13340. newTexture.hasAlpha = this.hasAlpha;
  13341. newTexture.level = this.level;
  13342. // Dynamic Texture
  13343. newTexture.wrapU = this.wrapU;
  13344. newTexture.wrapV = this.wrapV;
  13345. return newTexture;
  13346. };
  13347. return DynamicTexture;
  13348. })(BABYLON.Texture);
  13349. BABYLON.DynamicTexture = DynamicTexture;
  13350. })(BABYLON || (BABYLON = {}));
  13351. //# sourceMappingURL=babylon.dynamicTexture.js.map
  13352. var BABYLON;
  13353. (function (BABYLON) {
  13354. var VideoTexture = (function (_super) {
  13355. __extends(VideoTexture, _super);
  13356. function VideoTexture(name, urls, size, scene, generateMipMaps, invertY, samplingMode) {
  13357. var _this = this;
  13358. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  13359. _super.call(this, null, scene, !generateMipMaps, invertY);
  13360. this._autoLaunch = true;
  13361. this.name = name;
  13362. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  13363. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  13364. var requiredWidth = size.width || size;
  13365. var requiredHeight = size.height || size;
  13366. this._texture = scene.getEngine().createDynamicTexture(requiredWidth, requiredHeight, generateMipMaps, samplingMode);
  13367. var textureSize = this.getSize();
  13368. this.video = document.createElement("video");
  13369. this.video.width = textureSize.width;
  13370. this.video.height = textureSize.height;
  13371. this.video.autoplay = false;
  13372. this.video.loop = true;
  13373. this.video.addEventListener("canplaythrough", function () {
  13374. if (_this._texture) {
  13375. _this._texture.isReady = true;
  13376. }
  13377. });
  13378. urls.forEach(function (url) {
  13379. //Backwards-compatibility for typescript 1. from 1.3 it should say "SOURCE". see here - https://github.com/Microsoft/TypeScript/issues/1850
  13380. var source = document.createElement("source");
  13381. source.src = url;
  13382. _this.video.appendChild(source);
  13383. });
  13384. this._lastUpdate = BABYLON.Tools.Now;
  13385. }
  13386. VideoTexture.prototype.update = function () {
  13387. if (this._autoLaunch) {
  13388. this._autoLaunch = false;
  13389. this.video.play();
  13390. }
  13391. var now = BABYLON.Tools.Now;
  13392. if (now - this._lastUpdate < 15) {
  13393. return false;
  13394. }
  13395. this._lastUpdate = now;
  13396. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  13397. return true;
  13398. };
  13399. return VideoTexture;
  13400. })(BABYLON.Texture);
  13401. BABYLON.VideoTexture = VideoTexture;
  13402. })(BABYLON || (BABYLON = {}));
  13403. //# sourceMappingURL=babylon.videoTexture.js.mapvar BABYLON;
  13404. (function (BABYLON) {
  13405. var EffectFallbacks = (function () {
  13406. function EffectFallbacks() {
  13407. this._defines = {};
  13408. this._currentRank = 32;
  13409. this._maxRank = -1;
  13410. }
  13411. EffectFallbacks.prototype.addFallback = function (rank, define) {
  13412. if (!this._defines[rank]) {
  13413. if (rank < this._currentRank) {
  13414. this._currentRank = rank;
  13415. }
  13416. if (rank > this._maxRank) {
  13417. this._maxRank = rank;
  13418. }
  13419. this._defines[rank] = new Array();
  13420. }
  13421. this._defines[rank].push(define);
  13422. };
  13423. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  13424. get: function () {
  13425. return this._currentRank <= this._maxRank;
  13426. },
  13427. enumerable: true,
  13428. configurable: true
  13429. });
  13430. EffectFallbacks.prototype.reduce = function (currentDefines) {
  13431. var currentFallbacks = this._defines[this._currentRank];
  13432. for (var index = 0; index < currentFallbacks.length; index++) {
  13433. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  13434. }
  13435. this._currentRank++;
  13436. return currentDefines;
  13437. };
  13438. return EffectFallbacks;
  13439. })();
  13440. BABYLON.EffectFallbacks = EffectFallbacks;
  13441. var Effect = (function () {
  13442. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  13443. var _this = this;
  13444. this._isReady = false;
  13445. this._compilationError = "";
  13446. this._valueCache = [];
  13447. this._engine = engine;
  13448. this.name = baseName;
  13449. this.defines = defines;
  13450. this._uniformsNames = uniformsNames.concat(samplers);
  13451. this._samplers = samplers;
  13452. this._attributesNames = attributesNames;
  13453. this.onError = onError;
  13454. this.onCompiled = onCompiled;
  13455. var vertexSource;
  13456. var fragmentSource;
  13457. if (baseName.vertexElement) {
  13458. vertexSource = document.getElementById(baseName.vertexElement);
  13459. if (!vertexSource) {
  13460. vertexSource = baseName.vertexElement;
  13461. }
  13462. }
  13463. else {
  13464. vertexSource = baseName.vertex || baseName;
  13465. }
  13466. if (baseName.fragmentElement) {
  13467. fragmentSource = document.getElementById(baseName.fragmentElement);
  13468. if (!fragmentSource) {
  13469. fragmentSource = baseName.fragmentElement;
  13470. }
  13471. }
  13472. else {
  13473. fragmentSource = baseName.fragment || baseName;
  13474. }
  13475. this._loadVertexShader(vertexSource, function (vertexCode) {
  13476. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  13477. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  13478. });
  13479. });
  13480. }
  13481. // Properties
  13482. Effect.prototype.isReady = function () {
  13483. return this._isReady;
  13484. };
  13485. Effect.prototype.getProgram = function () {
  13486. return this._program;
  13487. };
  13488. Effect.prototype.getAttributesNames = function () {
  13489. return this._attributesNames;
  13490. };
  13491. Effect.prototype.getAttributeLocation = function (index) {
  13492. return this._attributes[index];
  13493. };
  13494. Effect.prototype.getAttributeLocationByName = function (name) {
  13495. var index = this._attributesNames.indexOf(name);
  13496. return this._attributes[index];
  13497. };
  13498. Effect.prototype.getAttributesCount = function () {
  13499. return this._attributes.length;
  13500. };
  13501. Effect.prototype.getUniformIndex = function (uniformName) {
  13502. return this._uniformsNames.indexOf(uniformName);
  13503. };
  13504. Effect.prototype.getUniform = function (uniformName) {
  13505. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  13506. };
  13507. Effect.prototype.getSamplers = function () {
  13508. return this._samplers;
  13509. };
  13510. Effect.prototype.getCompilationError = function () {
  13511. return this._compilationError;
  13512. };
  13513. // Methods
  13514. Effect.prototype._loadVertexShader = function (vertex, callback) {
  13515. // DOM element ?
  13516. if (vertex instanceof HTMLElement) {
  13517. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  13518. callback(vertexCode);
  13519. return;
  13520. }
  13521. // Is in local store ?
  13522. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  13523. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  13524. return;
  13525. }
  13526. var vertexShaderUrl;
  13527. if (vertex[0] === ".") {
  13528. vertexShaderUrl = vertex;
  13529. }
  13530. else {
  13531. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  13532. }
  13533. // Vertex shader
  13534. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  13535. };
  13536. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  13537. // DOM element ?
  13538. if (fragment instanceof HTMLElement) {
  13539. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  13540. callback(fragmentCode);
  13541. return;
  13542. }
  13543. // Is in local store ?
  13544. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  13545. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  13546. return;
  13547. }
  13548. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  13549. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  13550. return;
  13551. }
  13552. var fragmentShaderUrl;
  13553. if (fragment[0] === ".") {
  13554. fragmentShaderUrl = fragment;
  13555. }
  13556. else {
  13557. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  13558. }
  13559. // Fragment shader
  13560. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  13561. };
  13562. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  13563. try {
  13564. var engine = this._engine;
  13565. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  13566. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  13567. this._attributes = engine.getAttributes(this._program, attributesNames);
  13568. for (var index = 0; index < this._samplers.length; index++) {
  13569. var sampler = this.getUniform(this._samplers[index]);
  13570. if (sampler == null) {
  13571. this._samplers.splice(index, 1);
  13572. index--;
  13573. }
  13574. }
  13575. engine.bindSamplers(this);
  13576. this._isReady = true;
  13577. if (this.onCompiled) {
  13578. this.onCompiled(this);
  13579. }
  13580. }
  13581. catch (e) {
  13582. // Is it a problem with precision?
  13583. if (e.message.indexOf("highp") !== -1) {
  13584. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  13585. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  13586. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  13587. return;
  13588. }
  13589. // Let's go through fallbacks then
  13590. if (fallbacks && fallbacks.isMoreFallbacks) {
  13591. defines = fallbacks.reduce(defines);
  13592. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  13593. }
  13594. else {
  13595. BABYLON.Tools.Error("Unable to compile effect: " + this.name);
  13596. BABYLON.Tools.Error("Defines: " + defines);
  13597. BABYLON.Tools.Error("Error: " + e.message);
  13598. this._compilationError = e.message;
  13599. if (this.onError) {
  13600. this.onError(this, this._compilationError);
  13601. }
  13602. }
  13603. }
  13604. };
  13605. Effect.prototype._bindTexture = function (channel, texture) {
  13606. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  13607. };
  13608. Effect.prototype.setTexture = function (channel, texture) {
  13609. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  13610. };
  13611. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  13612. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  13613. };
  13614. //public _cacheMatrix(uniformName, matrix) {
  13615. // if (!this._valueCache[uniformName]) {
  13616. // this._valueCache[uniformName] = new BABYLON.Matrix();
  13617. // }
  13618. // for (var index = 0; index < 16; index++) {
  13619. // this._valueCache[uniformName].m[index] = matrix.m[index];
  13620. // }
  13621. //};
  13622. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  13623. if (!this._valueCache[uniformName]) {
  13624. this._valueCache[uniformName] = [x, y];
  13625. return;
  13626. }
  13627. this._valueCache[uniformName][0] = x;
  13628. this._valueCache[uniformName][1] = y;
  13629. };
  13630. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  13631. if (!this._valueCache[uniformName]) {
  13632. this._valueCache[uniformName] = [x, y, z];
  13633. return;
  13634. }
  13635. this._valueCache[uniformName][0] = x;
  13636. this._valueCache[uniformName][1] = y;
  13637. this._valueCache[uniformName][2] = z;
  13638. };
  13639. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  13640. if (!this._valueCache[uniformName]) {
  13641. this._valueCache[uniformName] = [x, y, z, w];
  13642. return;
  13643. }
  13644. this._valueCache[uniformName][0] = x;
  13645. this._valueCache[uniformName][1] = y;
  13646. this._valueCache[uniformName][2] = z;
  13647. this._valueCache[uniformName][3] = w;
  13648. };
  13649. Effect.prototype.setArray = function (uniformName, array) {
  13650. this._engine.setArray(this.getUniform(uniformName), array);
  13651. return this;
  13652. };
  13653. Effect.prototype.setArray2 = function (uniformName, array) {
  13654. this._engine.setArray2(this.getUniform(uniformName), array);
  13655. return this;
  13656. };
  13657. Effect.prototype.setArray3 = function (uniformName, array) {
  13658. this._engine.setArray3(this.getUniform(uniformName), array);
  13659. return this;
  13660. };
  13661. Effect.prototype.setArray4 = function (uniformName, array) {
  13662. this._engine.setArray4(this.getUniform(uniformName), array);
  13663. return this;
  13664. };
  13665. Effect.prototype.setMatrices = function (uniformName, matrices) {
  13666. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  13667. return this;
  13668. };
  13669. Effect.prototype.setMatrix = function (uniformName, matrix) {
  13670. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  13671. // return;
  13672. //this._cacheMatrix(uniformName, matrix);
  13673. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  13674. return this;
  13675. };
  13676. Effect.prototype.setFloat = function (uniformName, value) {
  13677. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  13678. return this;
  13679. this._valueCache[uniformName] = value;
  13680. this._engine.setFloat(this.getUniform(uniformName), value);
  13681. return this;
  13682. };
  13683. Effect.prototype.setBool = function (uniformName, bool) {
  13684. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  13685. return this;
  13686. this._valueCache[uniformName] = bool;
  13687. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  13688. return this;
  13689. };
  13690. Effect.prototype.setVector2 = function (uniformName, vector2) {
  13691. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  13692. return this;
  13693. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  13694. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  13695. return this;
  13696. };
  13697. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  13698. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  13699. return this;
  13700. this._cacheFloat2(uniformName, x, y);
  13701. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  13702. return this;
  13703. };
  13704. Effect.prototype.setVector3 = function (uniformName, vector3) {
  13705. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  13706. return this;
  13707. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  13708. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  13709. return this;
  13710. };
  13711. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  13712. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  13713. return this;
  13714. this._cacheFloat3(uniformName, x, y, z);
  13715. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  13716. return this;
  13717. };
  13718. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  13719. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  13720. return this;
  13721. this._cacheFloat4(uniformName, x, y, z, w);
  13722. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  13723. return this;
  13724. };
  13725. Effect.prototype.setColor3 = function (uniformName, color3) {
  13726. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  13727. return this;
  13728. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  13729. this._engine.setColor3(this.getUniform(uniformName), color3);
  13730. return this;
  13731. };
  13732. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  13733. 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)
  13734. return this;
  13735. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  13736. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  13737. return this;
  13738. };
  13739. // Statics
  13740. 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}",
  13741. 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}",
  13742. 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}",
  13743. 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}",
  13744. chromaticAberrationPixelShader:"/*\n BABYLON.JS Chromatic Aberration GLSL Shader\n Author: Olivier Guyot\n Separates very slightly R, G and B colors on the edges of the screen\n Inspired by Francois Tarlier & Martins Upitis \n*/\n\n#ifdef GL_ES\nprecision highp float;\n#endif\n\n// samplers\nuniform sampler2D textureSampler; // original color\n\n// uniforms\nuniform float chromatic_aberration;\nuniform float screen_width;\nuniform float screen_height;\n\n// varyings\nvarying vec2 vUV;\n\nvoid main(void)\n{\n vec2 centered_screen_pos = vec2(vUV.x-0.5, vUV.y-0.5);\n float radius2 = centered_screen_pos.x*centered_screen_pos.x\n + centered_screen_pos.y*centered_screen_pos.y;\n float radius = sqrt(radius2);\n\n vec4 original = texture2D(textureSampler, vUV);\n\n if(chromatic_aberration > 0.0) {\n //index of refraction of each color channel, causing chromatic dispersion\n vec3 ref_indices = vec3(0.6, 0.3, 0.0);\n float ref_shiftX = chromatic_aberration * radius * 12.0 / screen_width;\n float ref_shiftY = chromatic_aberration * radius * 12.0 / screen_height;\n\n // shifts for red, green & blue\n vec2 ref_coords_r = vec2(vUV.x + ref_indices.r*ref_shiftX, vUV.y + ref_indices.r*ref_shiftY*0.5);\n vec2 ref_coords_g = vec2(vUV.x + ref_indices.g*ref_shiftX, vUV.y + ref_indices.g*ref_shiftY*0.5);\n vec2 ref_coords_b = vec2(vUV.x + ref_indices.b*ref_shiftX, vUV.y + ref_indices.b*ref_shiftY*0.5);\n\n original.r = texture2D(textureSampler, ref_coords_r).r;\n original.g = texture2D(textureSampler, ref_coords_g).g;\n original.b = texture2D(textureSampler, ref_coords_b).b;\n }\n\n gl_FragColor = original;\n}",
  13745. 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}",
  13746. colorPixelShader:"precision highp float;\n\nuniform vec4 color;\n\nvoid main(void) {\n gl_FragColor = color;\n}",
  13747. 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}",
  13748. 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}",
  13749. 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;\n\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\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 vec4 shadowsInfo0;\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 vec4 shadowsInfo1;\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 vec4 shadowsInfo2;\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 vec4 shadowsInfo3;\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 bit_shift = vec4(1.0 / (255.0 * 255.0 * 255.0), 1.0 / (255.0 * 255.0), 1.0 / 255.0, 1.0);\n return dot(color, bit_shift);\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, float bias)\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)) + bias;\n\n if (depth.z > shadow)\n {\n return darkness;\n }\n return 1.;\n}\n\nfloat computeShadowWithPCF(vec4 vPositionFromLight, sampler2D shadowSampler, float mapSize, float bias)\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] / mapSize)) + bias < depth.z) visibility -= 0.25;\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[1] / mapSize)) + bias < depth.z) visibility -= 0.25;\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[2] / mapSize)) + bias < depth.z) visibility -= 0.25;\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[3] / mapSize)) + bias < depth.z) visibility -= 0.25;\n\n return visibility;\n}\n\n// Thanks to http://devmaster.net/\nfloat ChebychevInequality(vec2 moments, float t, float offset)\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.02);\n\n float d = t - moments.x;\n return clamp(variance / (variance + d * d) - offset, 0., 1.0);\n}\n\nfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler, float offset)\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 || depth.z > 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 1.0 - ChebychevInequality(moments, depth.z, offset);\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 = clamp((cosAngle - lightDirection.w) / (1. - cosAngle), 0.0, 1.0);\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#ifdef NORMAL\n vec3 normalW = normalize(vNormalW);\n#else\n vec3 normalW = vec3(1.0, 1.0, 1.0);\n#endif\n\n\n#ifdef BUMP\n normalW = perturbNormal(viewDirectionW);\n#endif\n\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, shadowsInfo0.w);\n#else\n #ifdef SHADOWPCF0\n shadow = computeShadowWithPCF(vPositionFromLight0, shadowSampler0, shadowsInfo0.y, shadowsInfo0.z);\n #else\n shadow = computeShadow(vPositionFromLight0, shadowSampler0, shadowsInfo0.x, shadowsInfo0.z);\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, shadowsInfo1.w);\n#else\n #ifdef SHADOWPCF1\n shadow = computeShadowWithPCF(vPositionFromLight1, shadowSampler1, shadowsInfo1.y, shadowsInfo1.z);\n #else\n shadow = computeShadow(vPositionFromLight1, shadowSampler1, shadowsInfo1.x, shadowsInfo1.z);\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, shadowsInfo2.w);\n#else\n #ifdef SHADOWPCF2\n shadow = computeShadowWithPCF(vPositionFromLight2, shadowSampler2, shadowsInfo2.y, shadowsInfo2.z);\n #else\n shadow = computeShadow(vPositionFromLight2, shadowSampler2, shadowsInfo2.x, shadowsInfo2.z);\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, shadowsInfo3.w);\n#else\n #ifdef SHADOWPCF3\n shadow = computeShadowWithPCF(vPositionFromLight3, shadowSampler3, shadowsInfo3.y, shadowsInfo3.z);\n #else\n shadow = computeShadow(vPositionFromLight3, shadowSampler3, shadowsInfo3.x, shadowsInfo3.z);\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}",
  13750. defaultVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attributes\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#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;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\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\n#ifdef NORMAL\n vNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\n#endif\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}",
  13751. depthPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n\nuniform float far;\n\nvoid main(void)\n{\n#ifdef ALPHATEST\n if (texture2D(diffuseSampler, vUV).a < 0.4)\n discard;\n#endif\n\n float depth = (gl_FragCoord.z / gl_FragCoord.w) / far;\n gl_FragColor = vec4(depth, depth * depth, 0.0, 1.0);\n}",
  13752. depthVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attribute\nattribute vec3 position;\n#ifdef BONES\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#endif\n\n// Uniform\n#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif\n\nuniform mat4 viewProjection;\n#ifdef BONES\nuniform mat4 mBones[BonesPerMesh];\n#endif\n\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n\nvoid main(void)\n{\n#ifdef INSTANCES\n mat4 finalWorld = mat4(world0, world1, world2, world3);\n#else\n mat4 finalWorld = world;\n#endif\n\n#ifdef BONES\n mat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\n mat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\n mat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\n mat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\n finalWorld = finalWorld * (m0 + m1 + m2 + m3);\n gl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n#else\n gl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n#endif\n\n#ifdef ALPHATEST\n#ifdef UV1\n vUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\n#endif\n#ifdef UV2\n vUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\n#endif\n#endif\n}",
  13753. depthBoxBlurPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#define OFFSET 1\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\n// Parameters\nuniform vec2 screenSize;\n\nvec4 pack(float depth)\n{\n const vec4 bit_shift = vec4(256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0);\n const vec4 bit_mask = vec4(0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0);\n\n vec4 res = fract(depth * bit_shift);\n res -= res.xxyz * bit_mask;\n\n return res;\n}\n\nfloat unpack(vec4 color)\n{\n const vec4 bit_shift = vec4(1.0 / (256.0 * 256.0 * 256.0), 1.0 / (256.0 * 256.0), 1.0 / 256.0, 1.0);\n return dot(color, bit_shift);\n}\n\nvoid main(void)\n{\n vec4 colorDepth = vec4(0.0);\n\n for (int x = -OFFSET; x <= OFFSET; x++)\n for (int y = -OFFSET; y <= OFFSET; y++)\n colorDepth += texture2D(textureSampler, vUV + vec2(x, y) / screenSize);\n\n gl_FragColor = (colorDepth / float((OFFSET * 2 + 1) * (OFFSET * 2 + 1)));\n}",
  13754. depthOfFieldPixelShader:"/*\n BABYLON.JS Depth-of-field GLSL Shader\n Author: Olivier Guyot\n Does depth-of-field blur, edge blur, highlights enhancing\n Inspired by Francois Tarlier & Martins Upitis\n*/\n\n#ifdef GL_ES\nprecision highp float;\n#endif\n\n\n// samplers\nuniform sampler2D textureSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\n// uniforms\nuniform float grain_amount;\nuniform bool pentagon;\nuniform float maxZ;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform float focus_depth;\nuniform float aperture;\nuniform float gain;\nuniform float threshold;\nuniform float edge_blur;\n\n// varyings\nvarying vec2 vUV;\n\n// constants\n#define PI 3.14159265\nconst int RING_1_SAMPLES = 4;\nconst int RING_2_SAMPLES = 6;\nconst int RING_3_SAMPLES = 9;\nconst int RING_4_SAMPLES = 12;\nconst int RING_5_SAMPLES = 16;\n//const int RING_6_SAMPLES = 15;\nconst float RING_STEP_DIST = 0.4; // a new blur ring is added each time this distance is passed\nconst float PENTAGON_ANGLE_SUB = 1.2566; // 2PI / 5\nconst float PENTAGON_ANGLE_SUB_HALF = 0.6283; // 2PI / 10\n\n// common calculations\nvec2 centered_screen_pos;\nfloat radius2;\nfloat radius;\n\n\n// applies edge distortion on texture coords\nvec2 getDistortedCoords(vec2 coords) {\n\n if(distortion == 0.0) { return coords; }\n\n vec2 direction = 1.0 * normalize(centered_screen_pos);\n vec2 dist_coords = vec2(0.5, 0.5);\n dist_coords.x = 0.5 + direction.x * radius2 * 1.0;\n dist_coords.y = 0.5 + direction.y * radius2 * 1.0;\n float dist_amount = clamp(distortion*0.23, 0.0, 1.0);\n\n dist_coords = mix(coords, dist_coords, dist_amount);\n\n return dist_coords;\n}\n\n// picks either original screen color or highlights only\nvec4 getColor(vec2 coords, bool highlight) {\n\n vec4 color = texture2D(textureSampler, coords);\n\n if(highlight) {\n float luminance = dot(color.rgb, vec3(0.2125, 0.7154, 0.0721));\n float lum_threshold;\n if(threshold > 1.0) { lum_threshold = 0.94 + 0.01 * threshold; }\n else { lum_threshold = 0.5 + 0.44 * threshold; }\n if(luminance < lum_threshold) {\n color.rgb = vec3(0.0, 0.0, 0.0);\n color.a = 1.0;\n }\n }\n\n return color;\n}\n\n// returns a modifier to be applied on the radius, in order to simulate a pentagon\nfloat pentagonShape(float angle) {\n float a1 = mod(angle, PENTAGON_ANGLE_SUB) / PENTAGON_ANGLE_SUB - 0.5;\n float a2 = 0.5 - a1 * a1;\n return 1.35 - 0.94 * a2;\n}\n\n// returns original screen color after blur\nvec4 getBlurColor(vec2 coords, float size, bool highlight) {\n\n float w = (size/screen_width);\n float h = (size/screen_height);\n\n vec4 col = getColor(coords, highlight);\n if(size == 0.0) { return col; }\n\n float s = 1.0;\n float pw; // sample x relative coord\n float ph; // sample y relative coord\n float bias = 0.65; // inner/outer ring bias\n if(highlight) { bias = 0.95; }\n float sample_angle;\n float ratio_rings;\n float ring_radius;\n float penta; // pentagon shape modifier\n\n int ring_count;\n if(size >= 6.0 * RING_STEP_DIST) { ring_count = 6; }\n else if(size >= 5.0 * RING_STEP_DIST) { ring_count = 5; }\n else if(size >= 4.0 * RING_STEP_DIST) { ring_count = 4; }\n else if(size >= 3.0 * RING_STEP_DIST) { ring_count = 3; }\n else if(size >= 2.0 * RING_STEP_DIST) { ring_count = 2; }\n else { ring_count = 1; }\n \n // RING 1\n if(size > RING_STEP_DIST) {\n ring_radius = size / float(ring_count);\n ratio_rings = 1.0 / float(ring_count);\n for(int i = 0; i < RING_1_SAMPLES; i++) {\n sample_angle = PI *2.0 * float(i) / float(RING_1_SAMPLES);\n if(pentagon) { penta = pentagonShape(sample_angle); }\n else { penta = 1.0; }\n pw = cos( sample_angle ) * penta * ring_radius;\n ph = sin( sample_angle ) * penta * ring_radius;\n col += getColor(coords + vec2(pw*w,ph*h), highlight) * mix( 1.0, ratio_rings, bias );\n s += 1.0 * mix(1.0, ratio_rings, bias);\n }\n } \n\n // RING 2\n if(size > RING_STEP_DIST * 2.0) {\n ring_radius = 2.0 * size / float(ring_count);\n ratio_rings = 2.0 / float(ring_count);\n for(int i = 0; i < RING_2_SAMPLES; i++) {\n sample_angle = PI *2.0 * float(i) / float(RING_2_SAMPLES);\n if(pentagon) { penta = pentagonShape(sample_angle); }\n else { penta = 1.0; }\n pw = cos( sample_angle ) * penta * ring_radius;\n ph = sin( sample_angle ) * penta * ring_radius;\n col += getColor(coords + vec2(pw*w,ph*h), highlight) * mix( 1.0, ratio_rings, bias );\n s += 1.0 * mix(1.0, ratio_rings, bias); \n }\n } \n\n // RING 3\n if(size > RING_STEP_DIST * 3.0) {\n ring_radius = 3.0 * size / float(ring_count);\n ratio_rings = 3.0 / float(ring_count);\n for(int i = 0; i < RING_3_SAMPLES; i++) {\n sample_angle = PI *2.0 * float(i) / float(RING_3_SAMPLES);\n if(pentagon) { penta = pentagonShape(sample_angle); }\n else { penta = 1.0; }\n pw = cos( sample_angle ) * penta * ring_radius;\n ph = sin( sample_angle ) * penta * ring_radius;\n col += getColor(coords + vec2(pw*w,ph*h), highlight) * mix( 1.0, ratio_rings, bias );\n s += 1.0 * mix(1.0, ratio_rings, bias); \n }\n } \n\n // RING 4\n if(size > RING_STEP_DIST * 4.0) {\n ring_radius = 4.0 * size / float(ring_count);\n ratio_rings = 4.0 / float(ring_count);\n for(int i = 0; i < RING_4_SAMPLES; i++) {\n sample_angle = PI *2.0 * float(i) / float(RING_4_SAMPLES);\n if(pentagon) { penta = pentagonShape(sample_angle); }\n else { penta = 1.0; }\n pw = cos( sample_angle ) * penta * ring_radius;\n ph = sin( sample_angle ) * penta * ring_radius;\n col += getColor(coords + vec2(pw*w,ph*h), highlight) * mix( 1.0, ratio_rings, bias );\n s += 1.0 * mix(1.0, ratio_rings, bias); \n }\n } \n\n // RING 5\n if(size > RING_STEP_DIST * 5.0) {\n ring_radius = 5.0 * size / float(ring_count);\n ratio_rings = 5.0 / float(ring_count);\n for(int i = 0; i < RING_5_SAMPLES; i++) {\n sample_angle = PI *2.0 * float(i) / float(RING_5_SAMPLES);\n if(pentagon) { penta = pentagonShape(sample_angle); }\n else { penta = 1.0; }\n pw = cos( sample_angle ) * penta * ring_radius;\n ph = sin( sample_angle ) * penta * ring_radius;\n col += getColor(coords + vec2(pw*w,ph*h), highlight) * mix( 1.0, ratio_rings, bias );\n s += 1.0 * mix(1.0, ratio_rings, bias); \n }\n } \n\n col /= s; // scales color according to samples taken\n col.a = 1.0;\n\n return col;\n}\n\n// on-the-fly constant noise\nvec2 rand(vec2 co)\n{\n float noise1 = (fract(sin(dot(co ,vec2(12.9898,78.233))) * 43758.5453));\n float noise2 = (fract(sin(dot(co ,vec2(12.9898,78.233)*2.0)) * 43758.5453));\n return clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvoid main(void)\n{\n\n // Common calc\n centered_screen_pos = vec2(vUV.x-0.5, vUV.y-0.5);\n radius2 = centered_screen_pos.x*centered_screen_pos.x + centered_screen_pos.y*centered_screen_pos.y;\n radius = sqrt(radius2);\n\n vec4 final_color;\n vec2 distorted_coords = getDistortedCoords(vUV);\n vec2 texels_coords = vec2(vUV.x * screen_width, vUV.y * screen_height); // varies from 0 to SCREEN_WIDTH or _HEIGHT\n\n // blur from depth of field effect\n float dof_blur_amount = 0.0;\n if(focus_depth != -1.0) {\n vec4 depth_sample = texture2D(depthSampler, distorted_coords);\n float depth = depth_sample.r;\n dof_blur_amount = abs(depth - focus_depth) * aperture * 3.5;\n if(dof_blur_amount < 0.05) { dof_blur_amount = 0.0; } // no blur at all\n else if( depth - focus_depth < 0.0 ) { dof_blur_amount *= 2.0; } // blur more when close to camera\n dof_blur_amount = clamp(dof_blur_amount, 0.0, 1.0);\n }\n\n // blur from edge blur effect\n float edge_blur_amount = 0.0;\n if(edge_blur > 0.0) {\n edge_blur_amount = clamp( ( radius*2.0 - 1.0 + 0.15*edge_blur ) * 1.5 , 0.0 , 1.0 ) * 1.3;\n }\n\n // total blur amount\n float blur_amount = max(edge_blur_amount, dof_blur_amount);\n\n // apply blur if necessary\n if(blur_amount == 0.0) {\n gl_FragColor = getColor(distorted_coords, false);\n } else {\n gl_FragColor = getBlurColor(distorted_coords, blur_amount * 1.7, false)\n + gain * blur_amount*getBlurColor(distorted_coords, blur_amount * 2.75, true);\n\n if(blur_noise) {\n // we put a slight amount of noise in the blurred color\n vec2 noise = rand(distorted_coords) * 0.01 * blur_amount;\n vec2 blurred_coord = vec2(distorted_coords.x + noise.x, distorted_coords.y + noise.y);\n gl_FragColor = 0.04 * getColor(blurred_coord, false) + 0.96 * gl_FragColor;\n }\n }\n\n if(grain_amount > 0.0) {\n vec4 grain_color = texture2D(grainSampler, texels_coords*0.003);\n gl_FragColor.rgb += ( -0.5 + grain_color.rgb ) * 0.20;\n }\n}",
  13755. 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}",
  13756. 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}",
  13757. 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}",
  13758. 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}",
  13759. 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}",
  13760. 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}",
  13761. 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}",
  13762. 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}",
  13763. 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}",
  13764. 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}",
  13765. 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}",
  13766. 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}",
  13767. 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}",
  13768. 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}",
  13769. 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}",
  13770. 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}",
  13771. 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}",
  13772. 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}",
  13773. 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}",
  13774. 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}",
  13775. 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}",
  13776. 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}",
  13777. shadowMapPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvec4 pack(float depth)\n{\n const vec4 bit_shift = vec4(255.0 * 255.0 * 255.0, 255.0 * 255.0, 255.0, 1.0);\n const vec4 bit_mask = vec4(0.0, 1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0);\n\n vec4 res = fract(depth * bit_shift);\n res -= res.xxyz * bit_mask;\n\n return res;\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;\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}",
  13778. 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#endif\n\n#ifndef VSM\n vPosition = viewProjection * finalWorld * vec4(position, 1.0);\n#endif\n gl_Position = viewProjection * finalWorld * vec4(position, 1.0);\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}",
  13779. 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}",
  13780. 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}",
  13781. ssaoPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#define SAMPLES 16\n\nuniform sampler2D textureSampler;\nuniform sampler2D randomSampler;\n\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[16];\n\nvarying vec2 vUV;\n\nconst vec2 offset1 = vec2(0.0, 0.01);\nconst vec2 offset2 = vec2(0.01, 0.0);\n\nvec3 normalFromDepth(const float depth, const vec2 coords) {\n float depth1 = texture2D(textureSampler, coords + offset1).r;\n float depth2 = texture2D(textureSampler, coords + offset2).r;\n\n vec3 p1 = vec3(offset1, depth1 - depth);\n vec3 p2 = vec3(offset2, depth2 - depth);\n\n vec3 normal = cross(p1, p2);\n normal.z = -normal.z;\n\n return normalize(normal);\n}\n\nvoid main(void)\n{\n const float totalStrength = 1.0;\n const float base = 0.2;\n const float area = 0.0075;\n const float fallOff = 0.000001;\n const float radius = 0.0005;\n\n vec3 random = texture2D(randomSampler, vUV * randTextureTiles).rgb;\n float depth = texture2D(textureSampler, vUV).r;\n vec3 position = vec3(vUV, depth);\n vec3 normal = normalFromDepth(depth, vUV);\n float radiusDepth = radius / depth;\n float occlusion = 0.0;\n\n vec3 ray;\n vec3 hemiRay;\n float occlusionDepth;\n float difference;\n\n for (int i = 0; i < SAMPLES; i++)\n {\n ray = radiusDepth * reflect(sampleSphere[i], random);\n hemiRay = position + dot(ray, normal) * ray;\n\n occlusionDepth = texture2D(textureSampler, clamp(hemiRay.xy, 0.0, 1.0)).r;\n difference = depth - occlusionDepth;\n\n occlusion += step(fallOff, difference) * (1.0 - smoothstep(fallOff, area, difference));\n }\n\n float ao = 1.0 - totalStrength * occlusion * samplesFactor;\n\n float result = clamp(ao + base, 0.0, 1.0);\n gl_FragColor.r = result;\n gl_FragColor.g = result;\n gl_FragColor.b = result;\n gl_FragColor.a = 1.0;\n}",
  13782. ssaoCombinePixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nuniform sampler2D textureSampler;\nuniform sampler2D originalColor;\n\nvarying vec2 vUV;\n\nvoid main(void) {\n gl_FragColor = texture2D(originalColor, vUV) * texture2D(textureSampler, vUV);\n}",
  13783. volumetricLightScatteringPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nuniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\n\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\n\nvarying vec2 vUV;\n\nvoid main(void) {\n vec2 tc = vUV;\n vec2 deltaTexCoord = (tc - meshPositionOnScreen.xy);\n deltaTexCoord *= 1.0 / float(NUM_SAMPLES) * density;\n\n float illuminationDecay = 1.0;\n\n vec4 color = texture2D(lightScatteringSampler, tc) * 0.4;\n\n for(int i=0; i < NUM_SAMPLES; i++) {\n tc -= deltaTexCoord;\n vec4 sample = texture2D(lightScatteringSampler, tc) * 0.4;\n sample *= illuminationDecay * weight;\n color += sample;\n illuminationDecay *= decay;\n }\n\n vec4 realColor = texture2D(textureSampler, vUV);\n gl_FragColor = ((vec4((vec3(color.r, color.g, color.b) * exposure), 1)) + (realColor * (1.5 - 0.4)));\n}",
  13784. volumetricLightScatteringPassPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#if defined(ALPHATEST) || defined(BASIC_RENDER) || defined(OPACITY)\nvarying vec2 vUV;\n#endif\n\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\nuniform sampler2D diffuseSampler;\n#endif\n\n#if defined(OPACITY)\nuniform sampler2D opacitySampler;\n#endif\n\nvoid main(void)\n{\n#if defined(ALPHATEST) || defined(OPACITY) || defined(BASIC_RENDER)\n vec4 diffuseColor = texture2D(diffuseSampler, vUV);\n#endif\n\n#ifdef ALPHATEST\n if (diffuseColor.a < 0.4)\n discard;\n#endif\n\n#ifdef BASIC_RENDER\n#ifdef OPACITY\n gl_FragColor = diffuseColor * texture2D(opacitySampler, vUV);\n#else\n gl_FragColor = diffuseColor;\n#endif\n#else\n gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\n#endif\n\n}",
  13785. 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}",
  13786. };
  13787. return Effect;
  13788. })();
  13789. BABYLON.Effect = Effect;
  13790. })(BABYLON || (BABYLON = {}));
  13791. //# sourceMappingURL=babylon.effect.js.mapvar BABYLON;
  13792. (function (BABYLON) {
  13793. var Material = (function () {
  13794. function Material(name, scene, doNotAdd) {
  13795. this.name = name;
  13796. this.checkReadyOnEveryCall = true;
  13797. this.checkReadyOnlyOnce = false;
  13798. this.state = "";
  13799. this.alpha = 1.0;
  13800. this.backFaceCulling = true;
  13801. this._wasPreviouslyReady = false;
  13802. this._fillMode = Material.TriangleFillMode;
  13803. this.pointSize = 1.0;
  13804. this.id = name;
  13805. this._scene = scene;
  13806. if (!doNotAdd) {
  13807. scene.materials.push(this);
  13808. }
  13809. }
  13810. Object.defineProperty(Material, "TriangleFillMode", {
  13811. get: function () {
  13812. return Material._TriangleFillMode;
  13813. },
  13814. enumerable: true,
  13815. configurable: true
  13816. });
  13817. Object.defineProperty(Material, "WireFrameFillMode", {
  13818. get: function () {
  13819. return Material._WireFrameFillMode;
  13820. },
  13821. enumerable: true,
  13822. configurable: true
  13823. });
  13824. Object.defineProperty(Material, "PointFillMode", {
  13825. get: function () {
  13826. return Material._PointFillMode;
  13827. },
  13828. enumerable: true,
  13829. configurable: true
  13830. });
  13831. Object.defineProperty(Material.prototype, "wireframe", {
  13832. get: function () {
  13833. return this._fillMode === Material.WireFrameFillMode;
  13834. },
  13835. set: function (value) {
  13836. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  13837. },
  13838. enumerable: true,
  13839. configurable: true
  13840. });
  13841. Object.defineProperty(Material.prototype, "pointsCloud", {
  13842. get: function () {
  13843. return this._fillMode === Material.PointFillMode;
  13844. },
  13845. set: function (value) {
  13846. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  13847. },
  13848. enumerable: true,
  13849. configurable: true
  13850. });
  13851. Object.defineProperty(Material.prototype, "fillMode", {
  13852. get: function () {
  13853. return this._fillMode;
  13854. },
  13855. set: function (value) {
  13856. this._fillMode = value;
  13857. },
  13858. enumerable: true,
  13859. configurable: true
  13860. });
  13861. Material.prototype.isReady = function (mesh, useInstances) {
  13862. return true;
  13863. };
  13864. Material.prototype.getEffect = function () {
  13865. return this._effect;
  13866. };
  13867. Material.prototype.getScene = function () {
  13868. return this._scene;
  13869. };
  13870. Material.prototype.needAlphaBlending = function () {
  13871. return (this.alpha < 1.0);
  13872. };
  13873. Material.prototype.needAlphaTesting = function () {
  13874. return false;
  13875. };
  13876. Material.prototype.getAlphaTestTexture = function () {
  13877. return null;
  13878. };
  13879. Material.prototype.trackCreation = function (onCompiled, onError) {
  13880. };
  13881. Material.prototype._preBind = function () {
  13882. var engine = this._scene.getEngine();
  13883. engine.enableEffect(this._effect);
  13884. engine.setState(this.backFaceCulling);
  13885. };
  13886. Material.prototype.bind = function (world, mesh) {
  13887. this._scene._cachedMaterial = this;
  13888. if (this.onBind) {
  13889. this.onBind(this);
  13890. }
  13891. };
  13892. Material.prototype.bindOnlyWorldMatrix = function (world) {
  13893. };
  13894. Material.prototype.unbind = function () {
  13895. };
  13896. Material.prototype.dispose = function (forceDisposeEffect) {
  13897. // Remove from scene
  13898. var index = this._scene.materials.indexOf(this);
  13899. this._scene.materials.splice(index, 1);
  13900. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  13901. if (forceDisposeEffect && this._effect) {
  13902. this._scene.getEngine()._releaseEffect(this._effect);
  13903. this._effect = null;
  13904. }
  13905. // Callback
  13906. if (this.onDispose) {
  13907. this.onDispose();
  13908. }
  13909. };
  13910. Material._TriangleFillMode = 0;
  13911. Material._WireFrameFillMode = 1;
  13912. Material._PointFillMode = 2;
  13913. return Material;
  13914. })();
  13915. BABYLON.Material = Material;
  13916. })(BABYLON || (BABYLON = {}));
  13917. //# sourceMappingURL=babylon.material.js.map
  13918. var BABYLON;
  13919. (function (BABYLON) {
  13920. var maxSimultaneousLights = 4;
  13921. var FresnelParameters = (function () {
  13922. function FresnelParameters() {
  13923. this.isEnabled = true;
  13924. this.leftColor = BABYLON.Color3.White();
  13925. this.rightColor = BABYLON.Color3.Black();
  13926. this.bias = 0;
  13927. this.power = 1;
  13928. }
  13929. return FresnelParameters;
  13930. })();
  13931. BABYLON.FresnelParameters = FresnelParameters;
  13932. var StandardMaterial = (function (_super) {
  13933. __extends(StandardMaterial, _super);
  13934. function StandardMaterial(name, scene) {
  13935. var _this = this;
  13936. _super.call(this, name, scene);
  13937. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  13938. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  13939. this.specularColor = new BABYLON.Color3(1, 1, 1);
  13940. this.specularPower = 64;
  13941. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  13942. this.useAlphaFromDiffuseTexture = false;
  13943. this.useSpecularOverAlpha = true;
  13944. this.fogEnabled = true;
  13945. this._cachedDefines = null;
  13946. this._renderTargets = new BABYLON.SmartArray(16);
  13947. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  13948. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  13949. this._scaledDiffuse = new BABYLON.Color3();
  13950. this._scaledSpecular = new BABYLON.Color3();
  13951. this.getRenderTargetTextures = function () {
  13952. _this._renderTargets.reset();
  13953. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  13954. _this._renderTargets.push(_this.reflectionTexture);
  13955. }
  13956. return _this._renderTargets;
  13957. };
  13958. }
  13959. StandardMaterial.prototype.needAlphaBlending = function () {
  13960. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  13961. };
  13962. StandardMaterial.prototype.needAlphaTesting = function () {
  13963. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && !this.diffuseTexture.getAlphaFromRGB;
  13964. };
  13965. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  13966. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  13967. };
  13968. StandardMaterial.prototype.getAlphaTestTexture = function () {
  13969. return this.diffuseTexture;
  13970. };
  13971. // Methods
  13972. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  13973. if (this.checkReadyOnlyOnce) {
  13974. if (this._wasPreviouslyReady) {
  13975. return true;
  13976. }
  13977. }
  13978. var scene = this.getScene();
  13979. if (!this.checkReadyOnEveryCall) {
  13980. if (this._renderId === scene.getRenderId()) {
  13981. return true;
  13982. }
  13983. }
  13984. var engine = scene.getEngine();
  13985. var defines = [];
  13986. var fallbacks = new BABYLON.EffectFallbacks();
  13987. var needNormals = false;
  13988. var needUVs = false;
  13989. // Textures
  13990. if (scene.texturesEnabled) {
  13991. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  13992. if (!this.diffuseTexture.isReady()) {
  13993. return false;
  13994. }
  13995. else {
  13996. needUVs = true;
  13997. defines.push("#define DIFFUSE");
  13998. }
  13999. }
  14000. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  14001. if (!this.ambientTexture.isReady()) {
  14002. return false;
  14003. }
  14004. else {
  14005. needUVs = true;
  14006. defines.push("#define AMBIENT");
  14007. }
  14008. }
  14009. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  14010. if (!this.opacityTexture.isReady()) {
  14011. return false;
  14012. }
  14013. else {
  14014. needUVs = true;
  14015. defines.push("#define OPACITY");
  14016. if (this.opacityTexture.getAlphaFromRGB) {
  14017. defines.push("#define OPACITYRGB");
  14018. }
  14019. }
  14020. }
  14021. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  14022. if (!this.reflectionTexture.isReady()) {
  14023. return false;
  14024. }
  14025. else {
  14026. needNormals = true;
  14027. needUVs = true;
  14028. defines.push("#define REFLECTION");
  14029. fallbacks.addFallback(0, "REFLECTION");
  14030. }
  14031. }
  14032. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  14033. if (!this.emissiveTexture.isReady()) {
  14034. return false;
  14035. }
  14036. else {
  14037. needUVs = true;
  14038. defines.push("#define EMISSIVE");
  14039. }
  14040. }
  14041. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  14042. if (!this.specularTexture.isReady()) {
  14043. return false;
  14044. }
  14045. else {
  14046. needUVs = true;
  14047. defines.push("#define SPECULAR");
  14048. fallbacks.addFallback(0, "SPECULAR");
  14049. }
  14050. }
  14051. }
  14052. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  14053. if (!this.bumpTexture.isReady()) {
  14054. return false;
  14055. }
  14056. else {
  14057. needUVs = true;
  14058. defines.push("#define BUMP");
  14059. fallbacks.addFallback(0, "BUMP");
  14060. }
  14061. }
  14062. // Effect
  14063. if (this.useSpecularOverAlpha) {
  14064. defines.push("#define SPECULAROVERALPHA");
  14065. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  14066. }
  14067. if (scene.clipPlane) {
  14068. defines.push("#define CLIPPLANE");
  14069. }
  14070. if (engine.getAlphaTesting()) {
  14071. defines.push("#define ALPHATEST");
  14072. }
  14073. if (this._shouldUseAlphaFromDiffuseTexture()) {
  14074. defines.push("#define ALPHAFROMDIFFUSE");
  14075. }
  14076. // Point size
  14077. if (this.pointsCloud || scene.forcePointsCloud) {
  14078. defines.push("#define POINTSIZE");
  14079. }
  14080. // Fog
  14081. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  14082. defines.push("#define FOG");
  14083. fallbacks.addFallback(1, "FOG");
  14084. }
  14085. var shadowsActivated = false;
  14086. var lightIndex = 0;
  14087. if (scene.lightsEnabled) {
  14088. for (var index = 0; index < scene.lights.length; index++) {
  14089. var light = scene.lights[index];
  14090. if (!light.isEnabled()) {
  14091. continue;
  14092. }
  14093. // Excluded check
  14094. if (light._excludedMeshesIds.length > 0) {
  14095. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  14096. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  14097. if (excludedMesh) {
  14098. light.excludedMeshes.push(excludedMesh);
  14099. }
  14100. }
  14101. light._excludedMeshesIds = [];
  14102. }
  14103. // Included check
  14104. if (light._includedOnlyMeshesIds.length > 0) {
  14105. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  14106. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  14107. if (includedOnlyMesh) {
  14108. light.includedOnlyMeshes.push(includedOnlyMesh);
  14109. }
  14110. }
  14111. light._includedOnlyMeshesIds = [];
  14112. }
  14113. if (!light.canAffectMesh(mesh)) {
  14114. continue;
  14115. }
  14116. needNormals = true;
  14117. defines.push("#define LIGHT" + lightIndex);
  14118. if (lightIndex > 0) {
  14119. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  14120. }
  14121. var type;
  14122. if (light instanceof BABYLON.SpotLight) {
  14123. type = "#define SPOTLIGHT" + lightIndex;
  14124. }
  14125. else if (light instanceof BABYLON.HemisphericLight) {
  14126. type = "#define HEMILIGHT" + lightIndex;
  14127. }
  14128. else {
  14129. type = "#define POINTDIRLIGHT" + lightIndex;
  14130. }
  14131. defines.push(type);
  14132. if (lightIndex > 0) {
  14133. fallbacks.addFallback(lightIndex, type.replace("#define ", ""));
  14134. }
  14135. // Shadows
  14136. if (scene.shadowsEnabled) {
  14137. var shadowGenerator = light.getShadowGenerator();
  14138. if (mesh && mesh.receiveShadows && shadowGenerator) {
  14139. defines.push("#define SHADOW" + lightIndex);
  14140. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  14141. if (!shadowsActivated) {
  14142. defines.push("#define SHADOWS");
  14143. shadowsActivated = true;
  14144. }
  14145. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  14146. defines.push("#define SHADOWVSM" + lightIndex);
  14147. if (lightIndex > 0) {
  14148. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  14149. }
  14150. }
  14151. if (shadowGenerator.usePoissonSampling) {
  14152. defines.push("#define SHADOWPCF" + lightIndex);
  14153. if (lightIndex > 0) {
  14154. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  14155. }
  14156. }
  14157. }
  14158. }
  14159. lightIndex++;
  14160. if (lightIndex === maxSimultaneousLights)
  14161. break;
  14162. }
  14163. }
  14164. if (StandardMaterial.FresnelEnabled) {
  14165. // Fresnel
  14166. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled || this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled || this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  14167. var fresnelRank = 1;
  14168. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  14169. defines.push("#define DIFFUSEFRESNEL");
  14170. fallbacks.addFallback(fresnelRank, "DIFFUSEFRESNEL");
  14171. fresnelRank++;
  14172. }
  14173. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  14174. defines.push("#define OPACITYFRESNEL");
  14175. fallbacks.addFallback(fresnelRank, "OPACITYFRESNEL");
  14176. fresnelRank++;
  14177. }
  14178. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  14179. defines.push("#define REFLECTIONFRESNEL");
  14180. fallbacks.addFallback(fresnelRank, "REFLECTIONFRESNEL");
  14181. fresnelRank++;
  14182. }
  14183. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  14184. defines.push("#define EMISSIVEFRESNEL");
  14185. fallbacks.addFallback(fresnelRank, "EMISSIVEFRESNEL");
  14186. fresnelRank++;
  14187. }
  14188. needNormals = true;
  14189. defines.push("#define FRESNEL");
  14190. fallbacks.addFallback(fresnelRank - 1, "FRESNEL");
  14191. }
  14192. }
  14193. // Attribs
  14194. var attribs = [BABYLON.VertexBuffer.PositionKind];
  14195. if (mesh) {
  14196. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  14197. attribs.push(BABYLON.VertexBuffer.NormalKind);
  14198. defines.push("#define NORMAL");
  14199. }
  14200. if (needUVs) {
  14201. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  14202. attribs.push(BABYLON.VertexBuffer.UVKind);
  14203. defines.push("#define UV1");
  14204. }
  14205. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  14206. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  14207. defines.push("#define UV2");
  14208. }
  14209. }
  14210. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  14211. attribs.push(BABYLON.VertexBuffer.ColorKind);
  14212. defines.push("#define VERTEXCOLOR");
  14213. if (mesh.hasVertexAlpha) {
  14214. defines.push("#define VERTEXALPHA");
  14215. }
  14216. }
  14217. if (mesh.useBones) {
  14218. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  14219. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  14220. defines.push("#define BONES");
  14221. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  14222. defines.push("#define BONES4");
  14223. fallbacks.addFallback(0, "BONES4");
  14224. }
  14225. // Instances
  14226. if (useInstances) {
  14227. defines.push("#define INSTANCES");
  14228. attribs.push("world0");
  14229. attribs.push("world1");
  14230. attribs.push("world2");
  14231. attribs.push("world3");
  14232. }
  14233. }
  14234. // Get correct effect
  14235. var join = defines.join("\n");
  14236. if (this._cachedDefines !== join) {
  14237. this._cachedDefines = join;
  14238. scene.resetCachedMaterial();
  14239. // Legacy browser patch
  14240. var shaderName = "default";
  14241. if (!scene.getEngine().getCaps().standardDerivatives) {
  14242. shaderName = "legacydefault";
  14243. }
  14244. this._effect = scene.getEngine().createEffect(shaderName, attribs, ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor", "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0", "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1", "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2", "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3", "vFogInfos", "vFogColor", "pointSize", "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "mBones", "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "shadowsInfo0", "shadowsInfo1", "shadowsInfo2", "shadowsInfo3", "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor"], ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"], join, fallbacks, this.onCompiled, this.onError);
  14245. }
  14246. if (!this._effect.isReady()) {
  14247. return false;
  14248. }
  14249. this._renderId = scene.getRenderId();
  14250. this._wasPreviouslyReady = true;
  14251. return true;
  14252. };
  14253. StandardMaterial.prototype.unbind = function () {
  14254. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  14255. this._effect.setTexture("reflection2DSampler", null);
  14256. }
  14257. };
  14258. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  14259. this._effect.setMatrix("world", world);
  14260. };
  14261. StandardMaterial.prototype.bind = function (world, mesh) {
  14262. var scene = this.getScene();
  14263. // Matrices
  14264. this.bindOnlyWorldMatrix(world);
  14265. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  14266. // Bones
  14267. if (mesh.useBones) {
  14268. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  14269. }
  14270. if (scene.getCachedMaterial() !== this) {
  14271. if (StandardMaterial.FresnelEnabled) {
  14272. // Fresnel
  14273. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  14274. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  14275. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  14276. }
  14277. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  14278. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  14279. }
  14280. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  14281. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  14282. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  14283. }
  14284. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  14285. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  14286. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  14287. }
  14288. }
  14289. // Textures
  14290. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  14291. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  14292. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  14293. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  14294. }
  14295. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  14296. this._effect.setTexture("ambientSampler", this.ambientTexture);
  14297. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  14298. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  14299. }
  14300. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  14301. this._effect.setTexture("opacitySampler", this.opacityTexture);
  14302. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  14303. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  14304. }
  14305. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  14306. if (this.reflectionTexture.isCube) {
  14307. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  14308. }
  14309. else {
  14310. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  14311. }
  14312. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  14313. this._effect.setFloat3("vReflectionInfos", this.reflectionTexture.coordinatesMode, this.reflectionTexture.level, this.reflectionTexture.isCube ? 1 : 0);
  14314. }
  14315. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  14316. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  14317. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  14318. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  14319. }
  14320. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  14321. this._effect.setTexture("specularSampler", this.specularTexture);
  14322. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  14323. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  14324. }
  14325. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  14326. this._effect.setTexture("bumpSampler", this.bumpTexture);
  14327. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level);
  14328. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  14329. }
  14330. // Clip plane
  14331. if (scene.clipPlane) {
  14332. var clipPlane = scene.clipPlane;
  14333. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  14334. }
  14335. // Point size
  14336. if (this.pointsCloud) {
  14337. this._effect.setFloat("pointSize", this.pointSize);
  14338. }
  14339. // Colors
  14340. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  14341. // Scaling down color according to emissive
  14342. this._scaledSpecular.r = this.specularColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  14343. this._scaledSpecular.g = this.specularColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  14344. this._scaledSpecular.b = this.specularColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  14345. this._effect.setVector3("vEyePosition", scene.activeCamera.position);
  14346. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  14347. this._effect.setColor4("vSpecularColor", this._scaledSpecular, this.specularPower);
  14348. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  14349. }
  14350. // Scaling down color according to emissive
  14351. this._scaledDiffuse.r = this.diffuseColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  14352. this._scaledDiffuse.g = this.diffuseColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  14353. this._scaledDiffuse.b = this.diffuseColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  14354. this._effect.setColor4("vDiffuseColor", this._scaledDiffuse, this.alpha * mesh.visibility);
  14355. if (scene.lightsEnabled) {
  14356. var lightIndex = 0;
  14357. for (var index = 0; index < scene.lights.length; index++) {
  14358. var light = scene.lights[index];
  14359. if (!light.isEnabled()) {
  14360. continue;
  14361. }
  14362. if (!light.canAffectMesh(mesh)) {
  14363. continue;
  14364. }
  14365. if (light instanceof BABYLON.PointLight) {
  14366. // Point Light
  14367. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  14368. }
  14369. else if (light instanceof BABYLON.DirectionalLight) {
  14370. // Directional Light
  14371. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  14372. }
  14373. else if (light instanceof BABYLON.SpotLight) {
  14374. // Spot Light
  14375. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  14376. }
  14377. else if (light instanceof BABYLON.HemisphericLight) {
  14378. // Hemispheric Light
  14379. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  14380. }
  14381. light.diffuse.scaleToRef(light.intensity, this._scaledDiffuse);
  14382. light.specular.scaleToRef(light.intensity, this._scaledSpecular);
  14383. this._effect.setColor4("vLightDiffuse" + lightIndex, this._scaledDiffuse, light.range);
  14384. this._effect.setColor3("vLightSpecular" + lightIndex, this._scaledSpecular);
  14385. // Shadows
  14386. if (scene.shadowsEnabled) {
  14387. var shadowGenerator = light.getShadowGenerator();
  14388. if (mesh.receiveShadows && shadowGenerator) {
  14389. this._effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  14390. this._effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  14391. this._effect.setFloat4("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.getShadowMap().getSize().width, shadowGenerator.getBias(), shadowGenerator.getLight().getVSMOffset());
  14392. }
  14393. }
  14394. lightIndex++;
  14395. if (lightIndex === maxSimultaneousLights)
  14396. break;
  14397. }
  14398. }
  14399. // View
  14400. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  14401. this._effect.setMatrix("view", scene.getViewMatrix());
  14402. }
  14403. // Fog
  14404. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  14405. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  14406. this._effect.setColor3("vFogColor", scene.fogColor);
  14407. }
  14408. _super.prototype.bind.call(this, world, mesh);
  14409. };
  14410. StandardMaterial.prototype.getAnimatables = function () {
  14411. var results = [];
  14412. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  14413. results.push(this.diffuseTexture);
  14414. }
  14415. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  14416. results.push(this.ambientTexture);
  14417. }
  14418. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  14419. results.push(this.opacityTexture);
  14420. }
  14421. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  14422. results.push(this.reflectionTexture);
  14423. }
  14424. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  14425. results.push(this.emissiveTexture);
  14426. }
  14427. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  14428. results.push(this.specularTexture);
  14429. }
  14430. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  14431. results.push(this.bumpTexture);
  14432. }
  14433. return results;
  14434. };
  14435. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  14436. if (this.diffuseTexture) {
  14437. this.diffuseTexture.dispose();
  14438. }
  14439. if (this.ambientTexture) {
  14440. this.ambientTexture.dispose();
  14441. }
  14442. if (this.opacityTexture) {
  14443. this.opacityTexture.dispose();
  14444. }
  14445. if (this.reflectionTexture) {
  14446. this.reflectionTexture.dispose();
  14447. }
  14448. if (this.emissiveTexture) {
  14449. this.emissiveTexture.dispose();
  14450. }
  14451. if (this.specularTexture) {
  14452. this.specularTexture.dispose();
  14453. }
  14454. if (this.bumpTexture) {
  14455. this.bumpTexture.dispose();
  14456. }
  14457. _super.prototype.dispose.call(this, forceDisposeEffect);
  14458. };
  14459. StandardMaterial.prototype.clone = function (name) {
  14460. var newStandardMaterial = new StandardMaterial(name, this.getScene());
  14461. // Base material
  14462. newStandardMaterial.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  14463. newStandardMaterial.alpha = this.alpha;
  14464. newStandardMaterial.fillMode = this.fillMode;
  14465. newStandardMaterial.backFaceCulling = this.backFaceCulling;
  14466. // Standard material
  14467. if (this.diffuseTexture && this.diffuseTexture.clone) {
  14468. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  14469. }
  14470. if (this.ambientTexture && this.ambientTexture.clone) {
  14471. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  14472. }
  14473. if (this.opacityTexture && this.opacityTexture.clone) {
  14474. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  14475. }
  14476. if (this.reflectionTexture && this.reflectionTexture.clone) {
  14477. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  14478. }
  14479. if (this.emissiveTexture && this.emissiveTexture.clone) {
  14480. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  14481. }
  14482. if (this.specularTexture && this.specularTexture.clone) {
  14483. newStandardMaterial.specularTexture = this.specularTexture.clone();
  14484. }
  14485. if (this.bumpTexture && this.bumpTexture.clone) {
  14486. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  14487. }
  14488. newStandardMaterial.ambientColor = this.ambientColor.clone();
  14489. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  14490. newStandardMaterial.specularColor = this.specularColor.clone();
  14491. newStandardMaterial.specularPower = this.specularPower;
  14492. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  14493. return newStandardMaterial;
  14494. };
  14495. // Statics
  14496. // Flags used to enable or disable a type of texture for all Standard Materials
  14497. StandardMaterial.DiffuseTextureEnabled = true;
  14498. StandardMaterial.AmbientTextureEnabled = true;
  14499. StandardMaterial.OpacityTextureEnabled = true;
  14500. StandardMaterial.ReflectionTextureEnabled = true;
  14501. StandardMaterial.EmissiveTextureEnabled = true;
  14502. StandardMaterial.SpecularTextureEnabled = true;
  14503. StandardMaterial.BumpTextureEnabled = true;
  14504. StandardMaterial.FresnelEnabled = true;
  14505. return StandardMaterial;
  14506. })(BABYLON.Material);
  14507. BABYLON.StandardMaterial = StandardMaterial;
  14508. })(BABYLON || (BABYLON = {}));
  14509. //# sourceMappingURL=babylon.standardMaterial.js.map
  14510. var BABYLON;
  14511. (function (BABYLON) {
  14512. var MultiMaterial = (function (_super) {
  14513. __extends(MultiMaterial, _super);
  14514. function MultiMaterial(name, scene) {
  14515. _super.call(this, name, scene, true);
  14516. this.subMaterials = new Array();
  14517. scene.multiMaterials.push(this);
  14518. }
  14519. // Properties
  14520. MultiMaterial.prototype.getSubMaterial = function (index) {
  14521. if (index < 0 || index >= this.subMaterials.length) {
  14522. return this.getScene().defaultMaterial;
  14523. }
  14524. return this.subMaterials[index];
  14525. };
  14526. // Methods
  14527. MultiMaterial.prototype.isReady = function (mesh) {
  14528. for (var index = 0; index < this.subMaterials.length; index++) {
  14529. var subMaterial = this.subMaterials[index];
  14530. if (subMaterial) {
  14531. if (!this.subMaterials[index].isReady(mesh)) {
  14532. return false;
  14533. }
  14534. }
  14535. }
  14536. return true;
  14537. };
  14538. return MultiMaterial;
  14539. })(BABYLON.Material);
  14540. BABYLON.MultiMaterial = MultiMaterial;
  14541. })(BABYLON || (BABYLON = {}));
  14542. //# sourceMappingURL=babylon.multiMaterial.js.mapvar BABYLON;
  14543. (function (BABYLON) {
  14544. var Database = (function () {
  14545. function Database(urlToScene, callbackManifestChecked) {
  14546. // Handling various flavors of prefixed version of IndexedDB
  14547. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  14548. this.callbackManifestChecked = callbackManifestChecked;
  14549. this.currentSceneUrl = BABYLON.Database.ReturnFullUrlLocation(urlToScene);
  14550. this.db = null;
  14551. this.enableSceneOffline = false;
  14552. this.enableTexturesOffline = false;
  14553. this.manifestVersionFound = 0;
  14554. this.mustUpdateRessources = false;
  14555. this.hasReachedQuota = false;
  14556. this.checkManifestFile();
  14557. }
  14558. Database.prototype.checkManifestFile = function () {
  14559. var _this = this;
  14560. function noManifestFile() {
  14561. //BABYLON.Tools.Log("Valid manifest file not found. Scene & textures will be loaded directly from the web server.");
  14562. that.enableSceneOffline = false;
  14563. that.enableTexturesOffline = false;
  14564. that.callbackManifestChecked(false);
  14565. }
  14566. var that = this;
  14567. var manifestURL = this.currentSceneUrl + ".manifest";
  14568. var xhr = new XMLHttpRequest();
  14569. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  14570. xhr.open("GET", manifestURLTimeStamped, true);
  14571. xhr.addEventListener("load", function () {
  14572. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  14573. try {
  14574. var manifestFile = JSON.parse(xhr.response);
  14575. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  14576. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  14577. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  14578. _this.manifestVersionFound = manifestFile.version;
  14579. }
  14580. if (_this.callbackManifestChecked) {
  14581. _this.callbackManifestChecked(true);
  14582. }
  14583. }
  14584. catch (ex) {
  14585. noManifestFile();
  14586. }
  14587. }
  14588. else {
  14589. noManifestFile();
  14590. }
  14591. }, false);
  14592. xhr.addEventListener("error", function (event) {
  14593. noManifestFile();
  14594. }, false);
  14595. try {
  14596. xhr.send();
  14597. }
  14598. catch (ex) {
  14599. BABYLON.Tools.Error("Error on XHR send request.");
  14600. that.callbackManifestChecked(false);
  14601. }
  14602. };
  14603. Database.prototype.openAsync = function (successCallback, errorCallback) {
  14604. var _this = this;
  14605. function handleError() {
  14606. that.isSupported = false;
  14607. if (errorCallback)
  14608. errorCallback();
  14609. }
  14610. var that = this;
  14611. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  14612. // Your browser doesn't support IndexedDB
  14613. this.isSupported = false;
  14614. if (errorCallback)
  14615. errorCallback();
  14616. }
  14617. else {
  14618. // If the DB hasn't been opened or created yet
  14619. if (!this.db) {
  14620. this.hasReachedQuota = false;
  14621. this.isSupported = true;
  14622. var request = this.idbFactory.open("babylonjs", 1);
  14623. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  14624. request.onerror = function (event) {
  14625. handleError();
  14626. };
  14627. // executes when a version change transaction cannot complete due to other active transactions
  14628. request.onblocked = function (event) {
  14629. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  14630. handleError();
  14631. };
  14632. // DB has been opened successfully
  14633. request.onsuccess = function (event) {
  14634. _this.db = request.result;
  14635. successCallback();
  14636. };
  14637. // Initialization of the DB. Creating Scenes & Textures stores
  14638. request.onupgradeneeded = function (event) {
  14639. _this.db = (event.target).result;
  14640. try {
  14641. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  14642. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  14643. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  14644. }
  14645. catch (ex) {
  14646. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  14647. handleError();
  14648. }
  14649. };
  14650. }
  14651. else {
  14652. if (successCallback)
  14653. successCallback();
  14654. }
  14655. }
  14656. };
  14657. Database.prototype.loadImageFromDB = function (url, image) {
  14658. var _this = this;
  14659. var completeURL = Database.ReturnFullUrlLocation(url);
  14660. var saveAndLoadImage = function () {
  14661. if (!_this.hasReachedQuota && _this.db !== null) {
  14662. // the texture is not yet in the DB, let's try to save it
  14663. _this._saveImageIntoDBAsync(completeURL, image);
  14664. }
  14665. else {
  14666. image.src = url;
  14667. }
  14668. };
  14669. if (!this.mustUpdateRessources) {
  14670. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  14671. }
  14672. else {
  14673. saveAndLoadImage();
  14674. }
  14675. };
  14676. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  14677. if (this.isSupported && this.db !== null) {
  14678. var texture;
  14679. var transaction = this.db.transaction(["textures"]);
  14680. transaction.onabort = function (event) {
  14681. image.src = url;
  14682. };
  14683. transaction.oncomplete = function (event) {
  14684. var blobTextureURL;
  14685. if (texture) {
  14686. var URL = window.URL || window.webkitURL;
  14687. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  14688. image.onerror = function () {
  14689. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  14690. image.src = url;
  14691. };
  14692. image.src = blobTextureURL;
  14693. }
  14694. else {
  14695. notInDBCallback();
  14696. }
  14697. };
  14698. var getRequest = transaction.objectStore("textures").get(url);
  14699. getRequest.onsuccess = function (event) {
  14700. texture = (event.target).result;
  14701. };
  14702. getRequest.onerror = function (event) {
  14703. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  14704. image.src = url;
  14705. };
  14706. }
  14707. else {
  14708. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  14709. image.src = url;
  14710. }
  14711. };
  14712. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  14713. var _this = this;
  14714. if (this.isSupported) {
  14715. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  14716. var generateBlobUrl = function () {
  14717. var blobTextureURL;
  14718. if (blob) {
  14719. var URL = window.URL || window.webkitURL;
  14720. try {
  14721. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  14722. }
  14723. catch (ex) {
  14724. blobTextureURL = URL.createObjectURL(blob);
  14725. }
  14726. }
  14727. image.src = blobTextureURL;
  14728. };
  14729. if (Database.isUASupportingBlobStorage) {
  14730. var xhr = new XMLHttpRequest(), blob;
  14731. xhr.open("GET", url, true);
  14732. xhr.responseType = "blob";
  14733. xhr.addEventListener("load", function () {
  14734. if (xhr.status === 200) {
  14735. // Blob as response (XHR2)
  14736. blob = xhr.response;
  14737. var transaction = _this.db.transaction(["textures"], "readwrite");
  14738. // the transaction could abort because of a QuotaExceededError error
  14739. transaction.onabort = function (event) {
  14740. try {
  14741. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  14742. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  14743. this.hasReachedQuota = true;
  14744. }
  14745. }
  14746. catch (ex) {
  14747. }
  14748. generateBlobUrl();
  14749. };
  14750. transaction.oncomplete = function (event) {
  14751. generateBlobUrl();
  14752. };
  14753. var newTexture = { textureUrl: url, data: blob };
  14754. try {
  14755. // Put the blob into the dabase
  14756. var addRequest = transaction.objectStore("textures").put(newTexture);
  14757. addRequest.onsuccess = function (event) {
  14758. };
  14759. addRequest.onerror = function (event) {
  14760. generateBlobUrl();
  14761. };
  14762. }
  14763. catch (ex) {
  14764. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  14765. if (ex.code === 25) {
  14766. Database.isUASupportingBlobStorage = false;
  14767. }
  14768. image.src = url;
  14769. }
  14770. }
  14771. else {
  14772. image.src = url;
  14773. }
  14774. }, false);
  14775. xhr.addEventListener("error", function (event) {
  14776. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  14777. image.src = url;
  14778. }, false);
  14779. xhr.send();
  14780. }
  14781. else {
  14782. image.src = url;
  14783. }
  14784. }
  14785. else {
  14786. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  14787. image.src = url;
  14788. }
  14789. };
  14790. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  14791. var _this = this;
  14792. var updateVersion = function (event) {
  14793. // the version is not yet in the DB or we need to update it
  14794. _this._saveVersionIntoDBAsync(url, versionLoaded);
  14795. };
  14796. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  14797. };
  14798. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  14799. var _this = this;
  14800. if (this.isSupported) {
  14801. var version;
  14802. try {
  14803. var transaction = this.db.transaction(["versions"]);
  14804. transaction.oncomplete = function (event) {
  14805. if (version) {
  14806. // If the version in the JSON file is > than the version in DB
  14807. if (_this.manifestVersionFound > version.data) {
  14808. _this.mustUpdateRessources = true;
  14809. updateInDBCallback();
  14810. }
  14811. else {
  14812. callback(version.data);
  14813. }
  14814. }
  14815. else {
  14816. _this.mustUpdateRessources = true;
  14817. updateInDBCallback();
  14818. }
  14819. };
  14820. transaction.onabort = function (event) {
  14821. callback(-1);
  14822. };
  14823. var getRequest = transaction.objectStore("versions").get(url);
  14824. getRequest.onsuccess = function (event) {
  14825. version = (event.target).result;
  14826. };
  14827. getRequest.onerror = function (event) {
  14828. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  14829. callback(-1);
  14830. };
  14831. }
  14832. catch (ex) {
  14833. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  14834. callback(-1);
  14835. }
  14836. }
  14837. else {
  14838. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  14839. callback(-1);
  14840. }
  14841. };
  14842. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  14843. var _this = this;
  14844. if (this.isSupported && !this.hasReachedQuota) {
  14845. try {
  14846. // Open a transaction to the database
  14847. var transaction = this.db.transaction(["versions"], "readwrite");
  14848. // the transaction could abort because of a QuotaExceededError error
  14849. transaction.onabort = function (event) {
  14850. try {
  14851. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  14852. _this.hasReachedQuota = true;
  14853. }
  14854. }
  14855. catch (ex) {
  14856. }
  14857. callback(-1);
  14858. };
  14859. transaction.oncomplete = function (event) {
  14860. callback(_this.manifestVersionFound);
  14861. };
  14862. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  14863. // Put the scene into the database
  14864. var addRequest = transaction.objectStore("versions").put(newVersion);
  14865. addRequest.onsuccess = function (event) {
  14866. };
  14867. addRequest.onerror = function (event) {
  14868. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  14869. };
  14870. }
  14871. catch (ex) {
  14872. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  14873. callback(-1);
  14874. }
  14875. }
  14876. else {
  14877. callback(-1);
  14878. }
  14879. };
  14880. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  14881. var _this = this;
  14882. var completeUrl = Database.ReturnFullUrlLocation(url);
  14883. var saveAndLoadFile = function (event) {
  14884. // the scene is not yet in the DB, let's try to save it
  14885. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  14886. };
  14887. this._checkVersionFromDB(completeUrl, function (version) {
  14888. if (version !== -1) {
  14889. if (!_this.mustUpdateRessources) {
  14890. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  14891. }
  14892. else {
  14893. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  14894. }
  14895. }
  14896. else {
  14897. errorCallback();
  14898. }
  14899. });
  14900. };
  14901. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  14902. if (this.isSupported) {
  14903. var targetStore;
  14904. if (url.indexOf(".babylon") !== -1) {
  14905. targetStore = "scenes";
  14906. }
  14907. else {
  14908. targetStore = "textures";
  14909. }
  14910. var file;
  14911. var transaction = this.db.transaction([targetStore]);
  14912. transaction.oncomplete = function (event) {
  14913. if (file) {
  14914. callback(file.data);
  14915. }
  14916. else {
  14917. notInDBCallback();
  14918. }
  14919. };
  14920. transaction.onabort = function (event) {
  14921. notInDBCallback();
  14922. };
  14923. var getRequest = transaction.objectStore(targetStore).get(url);
  14924. getRequest.onsuccess = function (event) {
  14925. file = (event.target).result;
  14926. };
  14927. getRequest.onerror = function (event) {
  14928. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  14929. notInDBCallback();
  14930. };
  14931. }
  14932. else {
  14933. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  14934. callback();
  14935. }
  14936. };
  14937. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  14938. var _this = this;
  14939. if (this.isSupported) {
  14940. var targetStore;
  14941. if (url.indexOf(".babylon") !== -1) {
  14942. targetStore = "scenes";
  14943. }
  14944. else {
  14945. targetStore = "textures";
  14946. }
  14947. // Create XHR
  14948. var xhr = new XMLHttpRequest(), fileData;
  14949. xhr.open("GET", url, true);
  14950. if (useArrayBuffer) {
  14951. xhr.responseType = "arraybuffer";
  14952. }
  14953. xhr.onprogress = progressCallback;
  14954. xhr.addEventListener("load", function () {
  14955. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  14956. // Blob as response (XHR2)
  14957. //fileData = xhr.responseText;
  14958. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  14959. if (!_this.hasReachedQuota) {
  14960. // Open a transaction to the database
  14961. var transaction = _this.db.transaction([targetStore], "readwrite");
  14962. // the transaction could abort because of a QuotaExceededError error
  14963. transaction.onabort = function (event) {
  14964. try {
  14965. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  14966. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  14967. this.hasReachedQuota = true;
  14968. }
  14969. }
  14970. catch (ex) {
  14971. }
  14972. callback(fileData);
  14973. };
  14974. transaction.oncomplete = function (event) {
  14975. callback(fileData);
  14976. };
  14977. var newFile;
  14978. if (targetStore === "scenes") {
  14979. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  14980. }
  14981. else {
  14982. newFile = { textureUrl: url, data: fileData };
  14983. }
  14984. try {
  14985. // Put the scene into the database
  14986. var addRequest = transaction.objectStore(targetStore).put(newFile);
  14987. addRequest.onsuccess = function (event) {
  14988. };
  14989. addRequest.onerror = function (event) {
  14990. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  14991. };
  14992. }
  14993. catch (ex) {
  14994. callback(fileData);
  14995. }
  14996. }
  14997. else {
  14998. callback(fileData);
  14999. }
  15000. }
  15001. else {
  15002. callback();
  15003. }
  15004. }, false);
  15005. xhr.addEventListener("error", function (event) {
  15006. BABYLON.Tools.Error("error on XHR request.");
  15007. callback();
  15008. }, false);
  15009. xhr.send();
  15010. }
  15011. else {
  15012. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  15013. callback();
  15014. }
  15015. };
  15016. Database.isUASupportingBlobStorage = true;
  15017. Database.parseURL = function (url) {
  15018. var a = document.createElement('a');
  15019. a.href = url;
  15020. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  15021. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  15022. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  15023. return absLocation;
  15024. };
  15025. Database.ReturnFullUrlLocation = function (url) {
  15026. if (url.indexOf("http:/") === -1) {
  15027. return (BABYLON.Database.parseURL(window.location.href) + url);
  15028. }
  15029. else {
  15030. return url;
  15031. }
  15032. };
  15033. return Database;
  15034. })();
  15035. BABYLON.Database = Database;
  15036. })(BABYLON || (BABYLON = {}));
  15037. //# sourceMappingURL=babylon.database.js.mapvar BABYLON;
  15038. (function (BABYLON) {
  15039. var SpriteManager = (function () {
  15040. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon) {
  15041. this.name = name;
  15042. this.cellSize = cellSize;
  15043. this.sprites = new Array();
  15044. this.renderingGroupId = 0;
  15045. this.fogEnabled = true;
  15046. this._vertexDeclaration = [3, 4, 4, 4];
  15047. this._vertexStrideSize = 15 * 4; // 15 floats per sprite (x, y, z, angle, size, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  15048. this._capacity = capacity;
  15049. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false);
  15050. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  15051. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  15052. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  15053. this._scene = scene;
  15054. this._scene.spriteManagers.push(this);
  15055. // VBO
  15056. this._vertexDeclaration = [3, 4, 4, 4];
  15057. this._vertexStrideSize = 15 * 4;
  15058. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  15059. var indices = [];
  15060. var index = 0;
  15061. for (var count = 0; count < capacity; count++) {
  15062. indices.push(index);
  15063. indices.push(index + 1);
  15064. indices.push(index + 2);
  15065. indices.push(index);
  15066. indices.push(index + 2);
  15067. indices.push(index + 3);
  15068. index += 4;
  15069. }
  15070. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  15071. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  15072. // Effects
  15073. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  15074. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  15075. }
  15076. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  15077. var arrayOffset = index * 15;
  15078. if (offsetX == 0)
  15079. offsetX = this._epsilon;
  15080. else if (offsetX == 1)
  15081. offsetX = 1 - this._epsilon;
  15082. if (offsetY == 0)
  15083. offsetY = this._epsilon;
  15084. else if (offsetY == 1)
  15085. offsetY = 1 - this._epsilon;
  15086. this._vertices[arrayOffset] = sprite.position.x;
  15087. this._vertices[arrayOffset + 1] = sprite.position.y;
  15088. this._vertices[arrayOffset + 2] = sprite.position.z;
  15089. this._vertices[arrayOffset + 3] = sprite.angle;
  15090. this._vertices[arrayOffset + 4] = sprite.size;
  15091. this._vertices[arrayOffset + 5] = offsetX;
  15092. this._vertices[arrayOffset + 6] = offsetY;
  15093. this._vertices[arrayOffset + 7] = sprite.invertU ? 1 : 0;
  15094. this._vertices[arrayOffset + 8] = sprite.invertV ? 1 : 0;
  15095. var offset = (sprite.cellIndex / rowSize) >> 0;
  15096. this._vertices[arrayOffset + 9] = sprite.cellIndex - offset * rowSize;
  15097. this._vertices[arrayOffset + 10] = offset;
  15098. // Color
  15099. this._vertices[arrayOffset + 11] = sprite.color.r;
  15100. this._vertices[arrayOffset + 12] = sprite.color.g;
  15101. this._vertices[arrayOffset + 13] = sprite.color.b;
  15102. this._vertices[arrayOffset + 14] = sprite.color.a;
  15103. };
  15104. SpriteManager.prototype.render = function () {
  15105. // Check
  15106. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  15107. return;
  15108. var engine = this._scene.getEngine();
  15109. var baseSize = this._spriteTexture.getBaseSize();
  15110. // Sprites
  15111. var deltaTime = engine.getDeltaTime();
  15112. var max = Math.min(this._capacity, this.sprites.length);
  15113. var rowSize = baseSize.width / this.cellSize;
  15114. var offset = 0;
  15115. for (var index = 0; index < max; index++) {
  15116. var sprite = this.sprites[index];
  15117. if (!sprite) {
  15118. continue;
  15119. }
  15120. sprite._animate(deltaTime);
  15121. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  15122. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  15123. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  15124. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  15125. }
  15126. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  15127. // Render
  15128. var effect = this._effectBase;
  15129. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  15130. effect = this._effectFog;
  15131. }
  15132. engine.enableEffect(effect);
  15133. var viewMatrix = this._scene.getViewMatrix();
  15134. effect.setTexture("diffuseSampler", this._spriteTexture);
  15135. effect.setMatrix("view", viewMatrix);
  15136. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  15137. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  15138. // Fog
  15139. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  15140. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  15141. effect.setColor3("vFogColor", this._scene.fogColor);
  15142. }
  15143. // VBOs
  15144. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  15145. // Draw order
  15146. effect.setBool("alphaTest", true);
  15147. engine.setColorWrite(false);
  15148. engine.draw(true, 0, max * 6);
  15149. engine.setColorWrite(true);
  15150. effect.setBool("alphaTest", false);
  15151. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  15152. engine.draw(true, 0, max * 6);
  15153. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  15154. };
  15155. SpriteManager.prototype.dispose = function () {
  15156. if (this._vertexBuffer) {
  15157. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  15158. this._vertexBuffer = null;
  15159. }
  15160. if (this._indexBuffer) {
  15161. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  15162. this._indexBuffer = null;
  15163. }
  15164. if (this._spriteTexture) {
  15165. this._spriteTexture.dispose();
  15166. this._spriteTexture = null;
  15167. }
  15168. // Remove from scene
  15169. var index = this._scene.spriteManagers.indexOf(this);
  15170. this._scene.spriteManagers.splice(index, 1);
  15171. // Callback
  15172. if (this.onDispose) {
  15173. this.onDispose();
  15174. }
  15175. };
  15176. return SpriteManager;
  15177. })();
  15178. BABYLON.SpriteManager = SpriteManager;
  15179. })(BABYLON || (BABYLON = {}));
  15180. //# sourceMappingURL=babylon.spriteManager.js.mapvar BABYLON;
  15181. (function (BABYLON) {
  15182. var Sprite = (function () {
  15183. function Sprite(name, manager) {
  15184. this.name = name;
  15185. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  15186. this.size = 1.0;
  15187. this.angle = 0;
  15188. this.cellIndex = 0;
  15189. this.invertU = 0;
  15190. this.invertV = 0;
  15191. this.animations = new Array();
  15192. this._animationStarted = false;
  15193. this._loopAnimation = false;
  15194. this._fromIndex = 0;
  15195. this._toIndex = 0;
  15196. this._delay = 0;
  15197. this._direction = 1;
  15198. this._frameCount = 0;
  15199. this._time = 0;
  15200. this._manager = manager;
  15201. this._manager.sprites.push(this);
  15202. this.position = BABYLON.Vector3.Zero();
  15203. }
  15204. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  15205. this._fromIndex = from;
  15206. this._toIndex = to;
  15207. this._loopAnimation = loop;
  15208. this._delay = delay;
  15209. this._animationStarted = true;
  15210. this._direction = from < to ? 1 : -1;
  15211. this.cellIndex = from;
  15212. this._time = 0;
  15213. };
  15214. Sprite.prototype.stopAnimation = function () {
  15215. this._animationStarted = false;
  15216. };
  15217. Sprite.prototype._animate = function (deltaTime) {
  15218. if (!this._animationStarted)
  15219. return;
  15220. this._time += deltaTime;
  15221. if (this._time > this._delay) {
  15222. this._time = this._time % this._delay;
  15223. this.cellIndex += this._direction;
  15224. if (this.cellIndex == this._toIndex) {
  15225. if (this._loopAnimation) {
  15226. this.cellIndex = this._fromIndex;
  15227. }
  15228. else {
  15229. this._animationStarted = false;
  15230. if (this.disposeWhenFinishedAnimating) {
  15231. this.dispose();
  15232. }
  15233. }
  15234. }
  15235. }
  15236. };
  15237. Sprite.prototype.dispose = function () {
  15238. for (var i = 0; i < this._manager.sprites.length; i++) {
  15239. if (this._manager.sprites[i] == this) {
  15240. this._manager.sprites.splice(i, 1);
  15241. }
  15242. }
  15243. };
  15244. return Sprite;
  15245. })();
  15246. BABYLON.Sprite = Sprite;
  15247. })(BABYLON || (BABYLON = {}));
  15248. //# sourceMappingURL=babylon.sprite.js.mapvar BABYLON;
  15249. (function (BABYLON) {
  15250. var Layer = (function () {
  15251. function Layer(name, imgUrl, scene, isBackground, color) {
  15252. this.name = name;
  15253. this._vertexDeclaration = [2];
  15254. this._vertexStrideSize = 2 * 4;
  15255. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  15256. this.isBackground = isBackground === undefined ? true : isBackground;
  15257. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  15258. this._scene = scene;
  15259. this._scene.layers.push(this);
  15260. // VBO
  15261. var vertices = [];
  15262. vertices.push(1, 1);
  15263. vertices.push(-1, 1);
  15264. vertices.push(-1, -1);
  15265. vertices.push(1, -1);
  15266. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  15267. // Indices
  15268. var indices = [];
  15269. indices.push(0);
  15270. indices.push(1);
  15271. indices.push(2);
  15272. indices.push(0);
  15273. indices.push(2);
  15274. indices.push(3);
  15275. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  15276. // Effects
  15277. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  15278. }
  15279. Layer.prototype.render = function () {
  15280. // Check
  15281. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  15282. return;
  15283. var engine = this._scene.getEngine();
  15284. // Render
  15285. engine.enableEffect(this._effect);
  15286. engine.setState(false);
  15287. // Texture
  15288. this._effect.setTexture("textureSampler", this.texture);
  15289. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  15290. // Color
  15291. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  15292. // VBOs
  15293. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  15294. // Draw order
  15295. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  15296. engine.draw(true, 0, 6);
  15297. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  15298. };
  15299. Layer.prototype.dispose = function () {
  15300. if (this._vertexBuffer) {
  15301. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  15302. this._vertexBuffer = null;
  15303. }
  15304. if (this._indexBuffer) {
  15305. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  15306. this._indexBuffer = null;
  15307. }
  15308. if (this.texture) {
  15309. this.texture.dispose();
  15310. this.texture = null;
  15311. }
  15312. // Remove from scene
  15313. var index = this._scene.layers.indexOf(this);
  15314. this._scene.layers.splice(index, 1);
  15315. // Callback
  15316. if (this.onDispose) {
  15317. this.onDispose();
  15318. }
  15319. };
  15320. return Layer;
  15321. })();
  15322. BABYLON.Layer = Layer;
  15323. })(BABYLON || (BABYLON = {}));
  15324. //# sourceMappingURL=babylon.layer.js.mapvar BABYLON;
  15325. (function (BABYLON) {
  15326. var Particle = (function () {
  15327. function Particle() {
  15328. this.position = BABYLON.Vector3.Zero();
  15329. this.direction = BABYLON.Vector3.Zero();
  15330. this.color = new BABYLON.Color4(0, 0, 0, 0);
  15331. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  15332. this.lifeTime = 1.0;
  15333. this.age = 0;
  15334. this.size = 0;
  15335. this.angle = 0;
  15336. this.angularSpeed = 0;
  15337. }
  15338. Particle.prototype.copyTo = function (other) {
  15339. other.position.copyFrom(this.position);
  15340. other.direction.copyFrom(this.direction);
  15341. other.color.copyFrom(this.color);
  15342. other.colorStep.copyFrom(this.colorStep);
  15343. other.lifeTime = this.lifeTime;
  15344. other.age = this.age;
  15345. other.size = this.size;
  15346. other.angle = this.angle;
  15347. other.angularSpeed = this.angularSpeed;
  15348. };
  15349. return Particle;
  15350. })();
  15351. BABYLON.Particle = Particle;
  15352. })(BABYLON || (BABYLON = {}));
  15353. //# sourceMappingURL=babylon.particle.js.mapvar BABYLON;
  15354. (function (BABYLON) {
  15355. var randomNumber = function (min, max) {
  15356. if (min === max) {
  15357. return (min);
  15358. }
  15359. var random = Math.random();
  15360. return ((random * (max - min)) + min);
  15361. };
  15362. var ParticleSystem = (function () {
  15363. function ParticleSystem(name, capacity, scene, customEffect) {
  15364. var _this = this;
  15365. this.name = name;
  15366. this.renderingGroupId = 0;
  15367. this.emitter = null;
  15368. this.emitRate = 10;
  15369. this.manualEmitCount = -1;
  15370. this.updateSpeed = 0.01;
  15371. this.targetStopDuration = 0;
  15372. this.disposeOnStop = false;
  15373. this.minEmitPower = 1;
  15374. this.maxEmitPower = 1;
  15375. this.minLifeTime = 1;
  15376. this.maxLifeTime = 1;
  15377. this.minSize = 1;
  15378. this.maxSize = 1;
  15379. this.minAngularSpeed = 0;
  15380. this.maxAngularSpeed = 0;
  15381. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  15382. this.forceDepthWrite = false;
  15383. this.gravity = BABYLON.Vector3.Zero();
  15384. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  15385. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  15386. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  15387. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  15388. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  15389. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  15390. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  15391. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  15392. this.particles = new Array();
  15393. this._vertexDeclaration = [3, 4, 4];
  15394. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  15395. this._stockParticles = new Array();
  15396. this._newPartsExcess = 0;
  15397. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  15398. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  15399. this._scaledDirection = BABYLON.Vector3.Zero();
  15400. this._scaledGravity = BABYLON.Vector3.Zero();
  15401. this._currentRenderId = -1;
  15402. this._started = false;
  15403. this._stopped = false;
  15404. this._actualFrame = 0;
  15405. this.id = name;
  15406. this._capacity = capacity;
  15407. this._scene = scene;
  15408. this._customEffect = customEffect;
  15409. scene.particleSystems.push(this);
  15410. // VBO
  15411. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  15412. var indices = [];
  15413. var index = 0;
  15414. for (var count = 0; count < capacity; count++) {
  15415. indices.push(index);
  15416. indices.push(index + 1);
  15417. indices.push(index + 2);
  15418. indices.push(index);
  15419. indices.push(index + 2);
  15420. indices.push(index + 3);
  15421. index += 4;
  15422. }
  15423. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  15424. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  15425. // Default behaviors
  15426. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate) {
  15427. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  15428. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  15429. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  15430. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  15431. };
  15432. this.startPositionFunction = function (worldMatrix, positionToUpdate) {
  15433. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  15434. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  15435. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  15436. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  15437. };
  15438. this.updateFunction = function (particles) {
  15439. for (var index = 0; index < particles.length; index++) {
  15440. var particle = particles[index];
  15441. particle.age += _this._scaledUpdateSpeed;
  15442. if (particle.age >= particle.lifeTime) {
  15443. _this.recycleParticle(particle);
  15444. index--;
  15445. continue;
  15446. }
  15447. else {
  15448. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  15449. particle.color.addInPlace(_this._scaledColorStep);
  15450. if (particle.color.a < 0)
  15451. particle.color.a = 0;
  15452. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  15453. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  15454. particle.position.addInPlace(_this._scaledDirection);
  15455. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  15456. particle.direction.addInPlace(_this._scaledGravity);
  15457. }
  15458. }
  15459. };
  15460. }
  15461. ParticleSystem.prototype.recycleParticle = function (particle) {
  15462. var lastParticle = this.particles.pop();
  15463. if (lastParticle !== particle) {
  15464. lastParticle.copyTo(particle);
  15465. this._stockParticles.push(lastParticle);
  15466. }
  15467. };
  15468. ParticleSystem.prototype.getCapacity = function () {
  15469. return this._capacity;
  15470. };
  15471. ParticleSystem.prototype.isAlive = function () {
  15472. return this._alive;
  15473. };
  15474. ParticleSystem.prototype.isStarted = function () {
  15475. return this._started;
  15476. };
  15477. ParticleSystem.prototype.start = function () {
  15478. this._started = true;
  15479. this._stopped = false;
  15480. this._actualFrame = 0;
  15481. };
  15482. ParticleSystem.prototype.stop = function () {
  15483. this._stopped = true;
  15484. };
  15485. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  15486. var offset = index * 11;
  15487. this._vertices[offset] = particle.position.x;
  15488. this._vertices[offset + 1] = particle.position.y;
  15489. this._vertices[offset + 2] = particle.position.z;
  15490. this._vertices[offset + 3] = particle.color.r;
  15491. this._vertices[offset + 4] = particle.color.g;
  15492. this._vertices[offset + 5] = particle.color.b;
  15493. this._vertices[offset + 6] = particle.color.a;
  15494. this._vertices[offset + 7] = particle.angle;
  15495. this._vertices[offset + 8] = particle.size;
  15496. this._vertices[offset + 9] = offsetX;
  15497. this._vertices[offset + 10] = offsetY;
  15498. };
  15499. ParticleSystem.prototype._update = function (newParticles) {
  15500. // Update current
  15501. this._alive = this.particles.length > 0;
  15502. this.updateFunction(this.particles);
  15503. // Add new ones
  15504. var worldMatrix;
  15505. if (this.emitter.position) {
  15506. worldMatrix = this.emitter.getWorldMatrix();
  15507. }
  15508. else {
  15509. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  15510. }
  15511. for (var index = 0; index < newParticles; index++) {
  15512. if (this.particles.length === this._capacity) {
  15513. break;
  15514. }
  15515. if (this._stockParticles.length !== 0) {
  15516. var particle = this._stockParticles.pop();
  15517. particle.age = 0;
  15518. }
  15519. else {
  15520. particle = new BABYLON.Particle();
  15521. }
  15522. this.particles.push(particle);
  15523. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  15524. this.startDirectionFunction(emitPower, worldMatrix, particle.direction);
  15525. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  15526. particle.size = randomNumber(this.minSize, this.maxSize);
  15527. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  15528. this.startPositionFunction(worldMatrix, particle.position);
  15529. var step = randomNumber(0, 1.0);
  15530. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  15531. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  15532. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  15533. }
  15534. };
  15535. ParticleSystem.prototype._getEffect = function () {
  15536. if (this._customEffect) {
  15537. return this._customEffect;
  15538. }
  15539. ;
  15540. var defines = [];
  15541. if (this._scene.clipPlane) {
  15542. defines.push("#define CLIPPLANE");
  15543. }
  15544. // Effect
  15545. var join = defines.join("\n");
  15546. if (this._cachedDefines !== join) {
  15547. this._cachedDefines = join;
  15548. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  15549. }
  15550. return this._effect;
  15551. };
  15552. ParticleSystem.prototype.animate = function () {
  15553. if (!this._started)
  15554. return;
  15555. var effect = this._getEffect();
  15556. // Check
  15557. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  15558. return;
  15559. if (this._currentRenderId === this._scene.getRenderId()) {
  15560. return;
  15561. }
  15562. this._currentRenderId = this._scene.getRenderId();
  15563. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  15564. // determine the number of particles we need to create
  15565. var emitCout;
  15566. if (this.manualEmitCount > -1) {
  15567. emitCout = this.manualEmitCount;
  15568. this.manualEmitCount = 0;
  15569. }
  15570. else {
  15571. emitCout = this.emitRate;
  15572. }
  15573. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  15574. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  15575. if (this._newPartsExcess > 1.0) {
  15576. newParticles += this._newPartsExcess >> 0;
  15577. this._newPartsExcess -= this._newPartsExcess >> 0;
  15578. }
  15579. this._alive = false;
  15580. if (!this._stopped) {
  15581. this._actualFrame += this._scaledUpdateSpeed;
  15582. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  15583. this.stop();
  15584. }
  15585. else {
  15586. newParticles = 0;
  15587. }
  15588. this._update(newParticles);
  15589. // Stopped?
  15590. if (this._stopped) {
  15591. if (!this._alive) {
  15592. this._started = false;
  15593. if (this.disposeOnStop) {
  15594. this._scene._toBeDisposed.push(this);
  15595. }
  15596. }
  15597. }
  15598. // Update VBO
  15599. var offset = 0;
  15600. for (var index = 0; index < this.particles.length; index++) {
  15601. var particle = this.particles[index];
  15602. this._appendParticleVertex(offset++, particle, 0, 0);
  15603. this._appendParticleVertex(offset++, particle, 1, 0);
  15604. this._appendParticleVertex(offset++, particle, 1, 1);
  15605. this._appendParticleVertex(offset++, particle, 0, 1);
  15606. }
  15607. var engine = this._scene.getEngine();
  15608. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  15609. };
  15610. ParticleSystem.prototype.render = function () {
  15611. var effect = this._getEffect();
  15612. // Check
  15613. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  15614. return 0;
  15615. var engine = this._scene.getEngine();
  15616. // Render
  15617. engine.enableEffect(effect);
  15618. engine.setState(false);
  15619. var viewMatrix = this._scene.getViewMatrix();
  15620. effect.setTexture("diffuseSampler", this.particleTexture);
  15621. effect.setMatrix("view", viewMatrix);
  15622. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  15623. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  15624. if (this._scene.clipPlane) {
  15625. var clipPlane = this._scene.clipPlane;
  15626. var invView = viewMatrix.clone();
  15627. invView.invert();
  15628. effect.setMatrix("invView", invView);
  15629. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  15630. }
  15631. // VBOs
  15632. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  15633. // Draw order
  15634. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  15635. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  15636. }
  15637. else {
  15638. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  15639. }
  15640. if (this.forceDepthWrite) {
  15641. engine.setDepthWrite(true);
  15642. }
  15643. engine.draw(true, 0, this.particles.length * 6);
  15644. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  15645. return this.particles.length;
  15646. };
  15647. ParticleSystem.prototype.dispose = function () {
  15648. if (this._vertexBuffer) {
  15649. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  15650. this._vertexBuffer = null;
  15651. }
  15652. if (this._indexBuffer) {
  15653. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  15654. this._indexBuffer = null;
  15655. }
  15656. if (this.particleTexture) {
  15657. this.particleTexture.dispose();
  15658. this.particleTexture = null;
  15659. }
  15660. // Remove from scene
  15661. var index = this._scene.particleSystems.indexOf(this);
  15662. this._scene.particleSystems.splice(index, 1);
  15663. // Callback
  15664. if (this.onDispose) {
  15665. this.onDispose();
  15666. }
  15667. };
  15668. // Clone
  15669. ParticleSystem.prototype.clone = function (name, newEmitter) {
  15670. var result = new ParticleSystem(name, this._capacity, this._scene);
  15671. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  15672. if (newEmitter === undefined) {
  15673. newEmitter = this.emitter;
  15674. }
  15675. result.emitter = newEmitter;
  15676. if (this.particleTexture) {
  15677. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  15678. }
  15679. result.start();
  15680. return result;
  15681. };
  15682. // Statics
  15683. ParticleSystem.BLENDMODE_ONEONE = 0;
  15684. ParticleSystem.BLENDMODE_STANDARD = 1;
  15685. return ParticleSystem;
  15686. })();
  15687. BABYLON.ParticleSystem = ParticleSystem;
  15688. })(BABYLON || (BABYLON = {}));
  15689. //# sourceMappingURL=babylon.particleSystem.js.mapvar BABYLON;
  15690. (function (BABYLON) {
  15691. var Animation = (function () {
  15692. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  15693. this.name = name;
  15694. this.targetProperty = targetProperty;
  15695. this.framePerSecond = framePerSecond;
  15696. this.dataType = dataType;
  15697. this.loopMode = loopMode;
  15698. this._offsetsCache = {};
  15699. this._highLimitsCache = {};
  15700. this._stopped = false;
  15701. this.targetPropertyPath = targetProperty.split(".");
  15702. this.dataType = dataType;
  15703. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  15704. }
  15705. Animation.CreateAndStartAnimation = function (name, mesh, tartgetProperty, framePerSecond, totalFrame, from, to, loopMode) {
  15706. var dataType = undefined;
  15707. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  15708. dataType = Animation.ANIMATIONTYPE_FLOAT;
  15709. }
  15710. else if (from instanceof BABYLON.Quaternion) {
  15711. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  15712. }
  15713. else if (from instanceof BABYLON.Vector3) {
  15714. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  15715. }
  15716. else if (from instanceof BABYLON.Vector2) {
  15717. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  15718. }
  15719. else if (from instanceof BABYLON.Color3) {
  15720. dataType = Animation.ANIMATIONTYPE_COLOR3;
  15721. }
  15722. if (dataType == undefined) {
  15723. return null;
  15724. }
  15725. var animation = new Animation(name, tartgetProperty, framePerSecond, dataType, loopMode);
  15726. var keys = [];
  15727. keys.push({ frame: 0, value: from });
  15728. keys.push({ frame: totalFrame, value: to });
  15729. animation.setKeys(keys);
  15730. mesh.animations.push(animation);
  15731. return mesh.getScene().beginAnimation(mesh, 0, totalFrame, (animation.loopMode === 1));
  15732. };
  15733. // Methods
  15734. Animation.prototype.isStopped = function () {
  15735. return this._stopped;
  15736. };
  15737. Animation.prototype.getKeys = function () {
  15738. return this._keys;
  15739. };
  15740. Animation.prototype.getEasingFunction = function () {
  15741. return this._easingFunction;
  15742. };
  15743. Animation.prototype.setEasingFunction = function (easingFunction) {
  15744. this._easingFunction = easingFunction;
  15745. };
  15746. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  15747. return startValue + (endValue - startValue) * gradient;
  15748. };
  15749. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  15750. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  15751. };
  15752. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  15753. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  15754. };
  15755. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  15756. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  15757. };
  15758. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  15759. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  15760. };
  15761. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  15762. var startScale = new BABYLON.Vector3(0, 0, 0);
  15763. var startRotation = new BABYLON.Quaternion();
  15764. var startTranslation = new BABYLON.Vector3(0, 0, 0);
  15765. startValue.decompose(startScale, startRotation, startTranslation);
  15766. var endScale = new BABYLON.Vector3(0, 0, 0);
  15767. var endRotation = new BABYLON.Quaternion();
  15768. var endTranslation = new BABYLON.Vector3(0, 0, 0);
  15769. endValue.decompose(endScale, endRotation, endTranslation);
  15770. var resultScale = this.vector3InterpolateFunction(startScale, endScale, gradient);
  15771. var resultRotation = this.quaternionInterpolateFunction(startRotation, endRotation, gradient);
  15772. var resultTranslation = this.vector3InterpolateFunction(startTranslation, endTranslation, gradient);
  15773. var result = BABYLON.Matrix.Compose(resultScale, resultRotation, resultTranslation);
  15774. return result;
  15775. };
  15776. Animation.prototype.clone = function () {
  15777. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  15778. clone.setKeys(this._keys);
  15779. return clone;
  15780. };
  15781. Animation.prototype.setKeys = function (values) {
  15782. this._keys = values.slice(0);
  15783. this._offsetsCache = {};
  15784. this._highLimitsCache = {};
  15785. };
  15786. Animation.prototype._getKeyValue = function (value) {
  15787. if (typeof value === "function") {
  15788. return value();
  15789. }
  15790. return value;
  15791. };
  15792. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  15793. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  15794. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  15795. }
  15796. this.currentFrame = currentFrame;
  15797. for (var key = 0; key < this._keys.length; key++) {
  15798. // for each frame, we need the key just before the frame superior
  15799. if (this._keys[key + 1].frame >= currentFrame) {
  15800. var startValue = this._getKeyValue(this._keys[key].value);
  15801. var endValue = this._getKeyValue(this._keys[key + 1].value);
  15802. // gradient : percent of currentFrame between the frame inf and the frame sup
  15803. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  15804. // check for easingFunction and correction of gradient
  15805. if (this._easingFunction != null) {
  15806. gradient = this._easingFunction.ease(gradient);
  15807. }
  15808. switch (this.dataType) {
  15809. case Animation.ANIMATIONTYPE_FLOAT:
  15810. switch (loopMode) {
  15811. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15812. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15813. return this.floatInterpolateFunction(startValue, endValue, gradient);
  15814. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15815. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  15816. }
  15817. break;
  15818. case Animation.ANIMATIONTYPE_QUATERNION:
  15819. var quaternion = null;
  15820. switch (loopMode) {
  15821. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15822. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15823. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  15824. break;
  15825. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15826. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  15827. break;
  15828. }
  15829. return quaternion;
  15830. case Animation.ANIMATIONTYPE_VECTOR3:
  15831. switch (loopMode) {
  15832. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15833. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15834. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  15835. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15836. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  15837. }
  15838. case Animation.ANIMATIONTYPE_VECTOR2:
  15839. switch (loopMode) {
  15840. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15841. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15842. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  15843. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15844. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  15845. }
  15846. case Animation.ANIMATIONTYPE_COLOR3:
  15847. switch (loopMode) {
  15848. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15849. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15850. return this.color3InterpolateFunction(startValue, endValue, gradient);
  15851. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15852. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  15853. }
  15854. case Animation.ANIMATIONTYPE_MATRIX:
  15855. switch (loopMode) {
  15856. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15857. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15858. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15859. return startValue;
  15860. }
  15861. default:
  15862. break;
  15863. }
  15864. break;
  15865. }
  15866. }
  15867. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  15868. };
  15869. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  15870. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  15871. this._stopped = true;
  15872. return false;
  15873. }
  15874. var returnValue = true;
  15875. // Adding a start key at frame 0 if missing
  15876. if (this._keys[0].frame !== 0) {
  15877. var newKey = { frame: 0, value: this._keys[0].value };
  15878. this._keys.splice(0, 0, newKey);
  15879. }
  15880. // Check limits
  15881. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  15882. from = this._keys[0].frame;
  15883. }
  15884. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  15885. to = this._keys[this._keys.length - 1].frame;
  15886. }
  15887. // Compute ratio
  15888. var range = to - from;
  15889. var offsetValue;
  15890. // ratio represents the frame delta between from and to
  15891. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  15892. var highLimitValue = 0;
  15893. if (ratio > range && !loop) {
  15894. returnValue = false;
  15895. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  15896. }
  15897. else {
  15898. // Get max value if required
  15899. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  15900. var keyOffset = to.toString() + from.toString();
  15901. if (!this._offsetsCache[keyOffset]) {
  15902. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  15903. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  15904. switch (this.dataType) {
  15905. case Animation.ANIMATIONTYPE_FLOAT:
  15906. this._offsetsCache[keyOffset] = toValue - fromValue;
  15907. break;
  15908. case Animation.ANIMATIONTYPE_QUATERNION:
  15909. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  15910. break;
  15911. case Animation.ANIMATIONTYPE_VECTOR3:
  15912. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  15913. case Animation.ANIMATIONTYPE_VECTOR2:
  15914. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  15915. case Animation.ANIMATIONTYPE_COLOR3:
  15916. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  15917. default:
  15918. break;
  15919. }
  15920. this._highLimitsCache[keyOffset] = toValue;
  15921. }
  15922. highLimitValue = this._highLimitsCache[keyOffset];
  15923. offsetValue = this._offsetsCache[keyOffset];
  15924. }
  15925. }
  15926. if (offsetValue === undefined) {
  15927. switch (this.dataType) {
  15928. case Animation.ANIMATIONTYPE_FLOAT:
  15929. offsetValue = 0;
  15930. break;
  15931. case Animation.ANIMATIONTYPE_QUATERNION:
  15932. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  15933. break;
  15934. case Animation.ANIMATIONTYPE_VECTOR3:
  15935. offsetValue = BABYLON.Vector3.Zero();
  15936. break;
  15937. case Animation.ANIMATIONTYPE_VECTOR2:
  15938. offsetValue = BABYLON.Vector2.Zero();
  15939. break;
  15940. case Animation.ANIMATIONTYPE_COLOR3:
  15941. offsetValue = BABYLON.Color3.Black();
  15942. }
  15943. }
  15944. // Compute value
  15945. var repeatCount = (ratio / range) >> 0;
  15946. var currentFrame = returnValue ? from + ratio % range : to;
  15947. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  15948. // Set value
  15949. if (this.targetPropertyPath.length > 1) {
  15950. var property = this._target[this.targetPropertyPath[0]];
  15951. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  15952. property = property[this.targetPropertyPath[index]];
  15953. }
  15954. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  15955. }
  15956. else {
  15957. this._target[this.targetPropertyPath[0]] = currentValue;
  15958. }
  15959. if (this._target.markAsDirty) {
  15960. this._target.markAsDirty(this.targetProperty);
  15961. }
  15962. if (!returnValue) {
  15963. this._stopped = true;
  15964. }
  15965. return returnValue;
  15966. };
  15967. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  15968. get: function () {
  15969. return Animation._ANIMATIONTYPE_FLOAT;
  15970. },
  15971. enumerable: true,
  15972. configurable: true
  15973. });
  15974. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  15975. get: function () {
  15976. return Animation._ANIMATIONTYPE_VECTOR3;
  15977. },
  15978. enumerable: true,
  15979. configurable: true
  15980. });
  15981. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  15982. get: function () {
  15983. return Animation._ANIMATIONTYPE_VECTOR2;
  15984. },
  15985. enumerable: true,
  15986. configurable: true
  15987. });
  15988. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  15989. get: function () {
  15990. return Animation._ANIMATIONTYPE_QUATERNION;
  15991. },
  15992. enumerable: true,
  15993. configurable: true
  15994. });
  15995. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  15996. get: function () {
  15997. return Animation._ANIMATIONTYPE_MATRIX;
  15998. },
  15999. enumerable: true,
  16000. configurable: true
  16001. });
  16002. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  16003. get: function () {
  16004. return Animation._ANIMATIONTYPE_COLOR3;
  16005. },
  16006. enumerable: true,
  16007. configurable: true
  16008. });
  16009. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  16010. get: function () {
  16011. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  16012. },
  16013. enumerable: true,
  16014. configurable: true
  16015. });
  16016. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  16017. get: function () {
  16018. return Animation._ANIMATIONLOOPMODE_CYCLE;
  16019. },
  16020. enumerable: true,
  16021. configurable: true
  16022. });
  16023. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  16024. get: function () {
  16025. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  16026. },
  16027. enumerable: true,
  16028. configurable: true
  16029. });
  16030. // Statics
  16031. Animation._ANIMATIONTYPE_FLOAT = 0;
  16032. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  16033. Animation._ANIMATIONTYPE_QUATERNION = 2;
  16034. Animation._ANIMATIONTYPE_MATRIX = 3;
  16035. Animation._ANIMATIONTYPE_COLOR3 = 4;
  16036. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  16037. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  16038. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  16039. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  16040. return Animation;
  16041. })();
  16042. BABYLON.Animation = Animation;
  16043. })(BABYLON || (BABYLON = {}));
  16044. //# sourceMappingURL=babylon.animation.js.mapvar BABYLON;
  16045. (function (BABYLON) {
  16046. var Animatable = (function () {
  16047. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  16048. if (fromFrame === void 0) { fromFrame = 0; }
  16049. if (toFrame === void 0) { toFrame = 100; }
  16050. if (loopAnimation === void 0) { loopAnimation = false; }
  16051. if (speedRatio === void 0) { speedRatio = 1.0; }
  16052. this.target = target;
  16053. this.fromFrame = fromFrame;
  16054. this.toFrame = toFrame;
  16055. this.loopAnimation = loopAnimation;
  16056. this.speedRatio = speedRatio;
  16057. this.onAnimationEnd = onAnimationEnd;
  16058. this._animations = new Array();
  16059. this._paused = false;
  16060. this.animationStarted = false;
  16061. if (animations) {
  16062. this.appendAnimations(target, animations);
  16063. }
  16064. this._scene = scene;
  16065. scene._activeAnimatables.push(this);
  16066. }
  16067. // Methods
  16068. Animatable.prototype.appendAnimations = function (target, animations) {
  16069. for (var index = 0; index < animations.length; index++) {
  16070. var animation = animations[index];
  16071. animation._target = target;
  16072. this._animations.push(animation);
  16073. }
  16074. };
  16075. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  16076. var animations = this._animations;
  16077. for (var index = 0; index < animations.length; index++) {
  16078. if (animations[index].targetProperty === property) {
  16079. return animations[index];
  16080. }
  16081. }
  16082. return null;
  16083. };
  16084. Animatable.prototype.pause = function () {
  16085. if (this._paused) {
  16086. return;
  16087. }
  16088. this._paused = true;
  16089. };
  16090. Animatable.prototype.restart = function () {
  16091. this._paused = false;
  16092. };
  16093. Animatable.prototype.stop = function () {
  16094. var index = this._scene._activeAnimatables.indexOf(this);
  16095. if (index > -1) {
  16096. this._scene._activeAnimatables.splice(index, 1);
  16097. }
  16098. if (this.onAnimationEnd) {
  16099. this.onAnimationEnd();
  16100. }
  16101. };
  16102. Animatable.prototype._animate = function (delay) {
  16103. if (this._paused) {
  16104. if (!this._pausedDelay) {
  16105. this._pausedDelay = delay;
  16106. }
  16107. return true;
  16108. }
  16109. if (!this._localDelayOffset) {
  16110. this._localDelayOffset = delay;
  16111. }
  16112. else if (this._pausedDelay) {
  16113. this._localDelayOffset += delay - this._pausedDelay;
  16114. this._pausedDelay = null;
  16115. }
  16116. // Animating
  16117. var running = false;
  16118. var animations = this._animations;
  16119. for (var index = 0; index < animations.length; index++) {
  16120. var animation = animations[index];
  16121. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  16122. running = running || isRunning;
  16123. }
  16124. if (!running && this.onAnimationEnd) {
  16125. this.onAnimationEnd();
  16126. }
  16127. return running;
  16128. };
  16129. return Animatable;
  16130. })();
  16131. BABYLON.Animatable = Animatable;
  16132. })(BABYLON || (BABYLON = {}));
  16133. //# sourceMappingURL=babylon.animatable.js.map
  16134. var BABYLON;
  16135. (function (BABYLON) {
  16136. var EasingFunction = (function () {
  16137. function EasingFunction() {
  16138. // Properties
  16139. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  16140. }
  16141. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  16142. get: function () {
  16143. return EasingFunction._EASINGMODE_EASEIN;
  16144. },
  16145. enumerable: true,
  16146. configurable: true
  16147. });
  16148. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  16149. get: function () {
  16150. return EasingFunction._EASINGMODE_EASEOUT;
  16151. },
  16152. enumerable: true,
  16153. configurable: true
  16154. });
  16155. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  16156. get: function () {
  16157. return EasingFunction._EASINGMODE_EASEINOUT;
  16158. },
  16159. enumerable: true,
  16160. configurable: true
  16161. });
  16162. EasingFunction.prototype.setEasingMode = function (easingMode) {
  16163. var n = Math.min(Math.max(easingMode, 0), 2);
  16164. this._easingMode = n;
  16165. };
  16166. EasingFunction.prototype.getEasingMode = function () {
  16167. return this._easingMode;
  16168. };
  16169. EasingFunction.prototype.easeInCore = function (gradient) {
  16170. throw new Error('You must implement this method');
  16171. };
  16172. EasingFunction.prototype.ease = function (gradient) {
  16173. switch (this._easingMode) {
  16174. case EasingFunction.EASINGMODE_EASEIN:
  16175. return this.easeInCore(gradient);
  16176. case EasingFunction.EASINGMODE_EASEOUT:
  16177. return (1 - this.easeInCore(1 - gradient));
  16178. }
  16179. if (gradient >= 0.5) {
  16180. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  16181. }
  16182. return (this.easeInCore(gradient * 2) * 0.5);
  16183. };
  16184. //Statics
  16185. EasingFunction._EASINGMODE_EASEIN = 0;
  16186. EasingFunction._EASINGMODE_EASEOUT = 1;
  16187. EasingFunction._EASINGMODE_EASEINOUT = 2;
  16188. return EasingFunction;
  16189. })();
  16190. BABYLON.EasingFunction = EasingFunction;
  16191. var CircleEase = (function (_super) {
  16192. __extends(CircleEase, _super);
  16193. function CircleEase() {
  16194. _super.apply(this, arguments);
  16195. }
  16196. CircleEase.prototype.easeInCore = function (gradient) {
  16197. gradient = Math.max(0, Math.min(1, gradient));
  16198. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  16199. };
  16200. return CircleEase;
  16201. })(EasingFunction);
  16202. BABYLON.CircleEase = CircleEase;
  16203. var BackEase = (function (_super) {
  16204. __extends(BackEase, _super);
  16205. function BackEase(amplitude) {
  16206. if (amplitude === void 0) { amplitude = 1; }
  16207. _super.call(this);
  16208. this.amplitude = amplitude;
  16209. }
  16210. BackEase.prototype.easeInCore = function (gradient) {
  16211. var num = Math.max(0, this.amplitude);
  16212. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  16213. };
  16214. return BackEase;
  16215. })(EasingFunction);
  16216. BABYLON.BackEase = BackEase;
  16217. var BounceEase = (function (_super) {
  16218. __extends(BounceEase, _super);
  16219. function BounceEase(bounces, bounciness) {
  16220. if (bounces === void 0) { bounces = 3; }
  16221. if (bounciness === void 0) { bounciness = 2; }
  16222. _super.call(this);
  16223. this.bounces = bounces;
  16224. this.bounciness = bounciness;
  16225. }
  16226. BounceEase.prototype.easeInCore = function (gradient) {
  16227. var y = Math.max(0.0, this.bounces);
  16228. var bounciness = this.bounciness;
  16229. if (bounciness <= 1.0) {
  16230. bounciness = 1.001;
  16231. }
  16232. var num9 = Math.pow(bounciness, y);
  16233. var num5 = 1.0 - bounciness;
  16234. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  16235. var num15 = gradient * num4;
  16236. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  16237. var num3 = Math.floor(num65);
  16238. var num13 = num3 + 1.0;
  16239. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  16240. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  16241. var num7 = (num8 + num12) * 0.5;
  16242. var num6 = gradient - num7;
  16243. var num2 = num7 - num8;
  16244. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  16245. };
  16246. return BounceEase;
  16247. })(EasingFunction);
  16248. BABYLON.BounceEase = BounceEase;
  16249. var CubicEase = (function (_super) {
  16250. __extends(CubicEase, _super);
  16251. function CubicEase() {
  16252. _super.apply(this, arguments);
  16253. }
  16254. CubicEase.prototype.easeInCore = function (gradient) {
  16255. return (gradient * gradient * gradient);
  16256. };
  16257. return CubicEase;
  16258. })(EasingFunction);
  16259. BABYLON.CubicEase = CubicEase;
  16260. var ElasticEase = (function (_super) {
  16261. __extends(ElasticEase, _super);
  16262. function ElasticEase(oscillations, springiness) {
  16263. if (oscillations === void 0) { oscillations = 3; }
  16264. if (springiness === void 0) { springiness = 3; }
  16265. _super.call(this);
  16266. this.oscillations = oscillations;
  16267. this.springiness = springiness;
  16268. }
  16269. ElasticEase.prototype.easeInCore = function (gradient) {
  16270. var num2;
  16271. var num3 = Math.max(0.0, this.oscillations);
  16272. var num = Math.max(0.0, this.springiness);
  16273. if (num == 0) {
  16274. num2 = gradient;
  16275. }
  16276. else {
  16277. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  16278. }
  16279. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  16280. };
  16281. return ElasticEase;
  16282. })(EasingFunction);
  16283. BABYLON.ElasticEase = ElasticEase;
  16284. var ExponentialEase = (function (_super) {
  16285. __extends(ExponentialEase, _super);
  16286. function ExponentialEase(exponent) {
  16287. if (exponent === void 0) { exponent = 2; }
  16288. _super.call(this);
  16289. this.exponent = exponent;
  16290. }
  16291. ExponentialEase.prototype.easeInCore = function (gradient) {
  16292. if (this.exponent <= 0) {
  16293. return gradient;
  16294. }
  16295. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  16296. };
  16297. return ExponentialEase;
  16298. })(EasingFunction);
  16299. BABYLON.ExponentialEase = ExponentialEase;
  16300. var PowerEase = (function (_super) {
  16301. __extends(PowerEase, _super);
  16302. function PowerEase(power) {
  16303. if (power === void 0) { power = 2; }
  16304. _super.call(this);
  16305. this.power = power;
  16306. }
  16307. PowerEase.prototype.easeInCore = function (gradient) {
  16308. var y = Math.max(0.0, this.power);
  16309. return Math.pow(gradient, y);
  16310. };
  16311. return PowerEase;
  16312. })(EasingFunction);
  16313. BABYLON.PowerEase = PowerEase;
  16314. var QuadraticEase = (function (_super) {
  16315. __extends(QuadraticEase, _super);
  16316. function QuadraticEase() {
  16317. _super.apply(this, arguments);
  16318. }
  16319. QuadraticEase.prototype.easeInCore = function (gradient) {
  16320. return (gradient * gradient);
  16321. };
  16322. return QuadraticEase;
  16323. })(EasingFunction);
  16324. BABYLON.QuadraticEase = QuadraticEase;
  16325. var QuarticEase = (function (_super) {
  16326. __extends(QuarticEase, _super);
  16327. function QuarticEase() {
  16328. _super.apply(this, arguments);
  16329. }
  16330. QuarticEase.prototype.easeInCore = function (gradient) {
  16331. return (gradient * gradient * gradient * gradient);
  16332. };
  16333. return QuarticEase;
  16334. })(EasingFunction);
  16335. BABYLON.QuarticEase = QuarticEase;
  16336. var QuinticEase = (function (_super) {
  16337. __extends(QuinticEase, _super);
  16338. function QuinticEase() {
  16339. _super.apply(this, arguments);
  16340. }
  16341. QuinticEase.prototype.easeInCore = function (gradient) {
  16342. return (gradient * gradient * gradient * gradient * gradient);
  16343. };
  16344. return QuinticEase;
  16345. })(EasingFunction);
  16346. BABYLON.QuinticEase = QuinticEase;
  16347. var SineEase = (function (_super) {
  16348. __extends(SineEase, _super);
  16349. function SineEase() {
  16350. _super.apply(this, arguments);
  16351. }
  16352. SineEase.prototype.easeInCore = function (gradient) {
  16353. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  16354. };
  16355. return SineEase;
  16356. })(EasingFunction);
  16357. BABYLON.SineEase = SineEase;
  16358. var BezierCurveEase = (function (_super) {
  16359. __extends(BezierCurveEase, _super);
  16360. function BezierCurveEase(x1, y1, x2, y2) {
  16361. if (x1 === void 0) { x1 = 0; }
  16362. if (y1 === void 0) { y1 = 0; }
  16363. if (x2 === void 0) { x2 = 1; }
  16364. if (y2 === void 0) { y2 = 1; }
  16365. _super.call(this);
  16366. this.x1 = x1;
  16367. this.y1 = y1;
  16368. this.x2 = x2;
  16369. this.y2 = y2;
  16370. }
  16371. BezierCurveEase.prototype.easeInCore = function (gradient) {
  16372. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  16373. };
  16374. return BezierCurveEase;
  16375. })(EasingFunction);
  16376. BABYLON.BezierCurveEase = BezierCurveEase;
  16377. })(BABYLON || (BABYLON = {}));
  16378. //# sourceMappingURL=babylon.easing.js.mapvar BABYLON;
  16379. (function (BABYLON) {
  16380. var Octree = (function () {
  16381. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  16382. if (maxDepth === void 0) { maxDepth = 2; }
  16383. this.maxDepth = maxDepth;
  16384. this.dynamicContent = new Array();
  16385. this._maxBlockCapacity = maxBlockCapacity || 64;
  16386. this._selectionContent = new BABYLON.SmartArray(1024);
  16387. this._creationFunc = creationFunc;
  16388. }
  16389. // Methods
  16390. Octree.prototype.update = function (worldMin, worldMax, entries) {
  16391. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  16392. };
  16393. Octree.prototype.addMesh = function (entry) {
  16394. for (var index = 0; index < this.blocks.length; index++) {
  16395. var block = this.blocks[index];
  16396. block.addEntry(entry);
  16397. }
  16398. };
  16399. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  16400. this._selectionContent.reset();
  16401. for (var index = 0; index < this.blocks.length; index++) {
  16402. var block = this.blocks[index];
  16403. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  16404. }
  16405. if (allowDuplicate) {
  16406. this._selectionContent.concat(this.dynamicContent);
  16407. }
  16408. else {
  16409. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  16410. }
  16411. return this._selectionContent;
  16412. };
  16413. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  16414. this._selectionContent.reset();
  16415. for (var index = 0; index < this.blocks.length; index++) {
  16416. var block = this.blocks[index];
  16417. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  16418. }
  16419. if (allowDuplicate) {
  16420. this._selectionContent.concat(this.dynamicContent);
  16421. }
  16422. else {
  16423. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  16424. }
  16425. return this._selectionContent;
  16426. };
  16427. Octree.prototype.intersectsRay = function (ray) {
  16428. this._selectionContent.reset();
  16429. for (var index = 0; index < this.blocks.length; index++) {
  16430. var block = this.blocks[index];
  16431. block.intersectsRay(ray, this._selectionContent);
  16432. }
  16433. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  16434. return this._selectionContent;
  16435. };
  16436. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  16437. target.blocks = new Array();
  16438. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  16439. for (var x = 0; x < 2; x++) {
  16440. for (var y = 0; y < 2; y++) {
  16441. for (var z = 0; z < 2; z++) {
  16442. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  16443. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  16444. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  16445. block.addEntries(entries);
  16446. target.blocks.push(block);
  16447. }
  16448. }
  16449. }
  16450. };
  16451. Octree.CreationFuncForMeshes = function (entry, block) {
  16452. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  16453. block.entries.push(entry);
  16454. }
  16455. };
  16456. Octree.CreationFuncForSubMeshes = function (entry, block) {
  16457. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  16458. block.entries.push(entry);
  16459. }
  16460. };
  16461. return Octree;
  16462. })();
  16463. BABYLON.Octree = Octree;
  16464. })(BABYLON || (BABYLON = {}));
  16465. //# sourceMappingURL=babylon.octree.js.mapvar BABYLON;
  16466. (function (BABYLON) {
  16467. var OctreeBlock = (function () {
  16468. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  16469. this.entries = new Array();
  16470. this._boundingVectors = new Array();
  16471. this._capacity = capacity;
  16472. this._depth = depth;
  16473. this._maxDepth = maxDepth;
  16474. this._creationFunc = creationFunc;
  16475. this._minPoint = minPoint;
  16476. this._maxPoint = maxPoint;
  16477. this._boundingVectors.push(minPoint.clone());
  16478. this._boundingVectors.push(maxPoint.clone());
  16479. this._boundingVectors.push(minPoint.clone());
  16480. this._boundingVectors[2].x = maxPoint.x;
  16481. this._boundingVectors.push(minPoint.clone());
  16482. this._boundingVectors[3].y = maxPoint.y;
  16483. this._boundingVectors.push(minPoint.clone());
  16484. this._boundingVectors[4].z = maxPoint.z;
  16485. this._boundingVectors.push(maxPoint.clone());
  16486. this._boundingVectors[5].z = minPoint.z;
  16487. this._boundingVectors.push(maxPoint.clone());
  16488. this._boundingVectors[6].x = minPoint.x;
  16489. this._boundingVectors.push(maxPoint.clone());
  16490. this._boundingVectors[7].y = minPoint.y;
  16491. }
  16492. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  16493. // Property
  16494. get: function () {
  16495. return this._capacity;
  16496. },
  16497. enumerable: true,
  16498. configurable: true
  16499. });
  16500. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  16501. get: function () {
  16502. return this._minPoint;
  16503. },
  16504. enumerable: true,
  16505. configurable: true
  16506. });
  16507. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  16508. get: function () {
  16509. return this._maxPoint;
  16510. },
  16511. enumerable: true,
  16512. configurable: true
  16513. });
  16514. // Methods
  16515. OctreeBlock.prototype.addEntry = function (entry) {
  16516. if (this.blocks) {
  16517. for (var index = 0; index < this.blocks.length; index++) {
  16518. var block = this.blocks[index];
  16519. block.addEntry(entry);
  16520. }
  16521. return;
  16522. }
  16523. this._creationFunc(entry, this);
  16524. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  16525. this.createInnerBlocks();
  16526. }
  16527. };
  16528. OctreeBlock.prototype.addEntries = function (entries) {
  16529. for (var index = 0; index < entries.length; index++) {
  16530. var mesh = entries[index];
  16531. this.addEntry(mesh);
  16532. }
  16533. };
  16534. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  16535. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  16536. if (this.blocks) {
  16537. for (var index = 0; index < this.blocks.length; index++) {
  16538. var block = this.blocks[index];
  16539. block.select(frustumPlanes, selection, allowDuplicate);
  16540. }
  16541. return;
  16542. }
  16543. if (allowDuplicate) {
  16544. selection.concat(this.entries);
  16545. }
  16546. else {
  16547. selection.concatWithNoDuplicate(this.entries);
  16548. }
  16549. }
  16550. };
  16551. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  16552. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  16553. if (this.blocks) {
  16554. for (var index = 0; index < this.blocks.length; index++) {
  16555. var block = this.blocks[index];
  16556. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  16557. }
  16558. return;
  16559. }
  16560. if (allowDuplicate) {
  16561. selection.concat(this.entries);
  16562. }
  16563. else {
  16564. selection.concatWithNoDuplicate(this.entries);
  16565. }
  16566. }
  16567. };
  16568. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  16569. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  16570. if (this.blocks) {
  16571. for (var index = 0; index < this.blocks.length; index++) {
  16572. var block = this.blocks[index];
  16573. block.intersectsRay(ray, selection);
  16574. }
  16575. return;
  16576. }
  16577. selection.concatWithNoDuplicate(this.entries);
  16578. }
  16579. };
  16580. OctreeBlock.prototype.createInnerBlocks = function () {
  16581. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  16582. };
  16583. return OctreeBlock;
  16584. })();
  16585. BABYLON.OctreeBlock = OctreeBlock;
  16586. })(BABYLON || (BABYLON = {}));
  16587. //# sourceMappingURL=babylon.octreeBlock.js.mapvar BABYLON;
  16588. (function (BABYLON) {
  16589. var Bone = (function () {
  16590. function Bone(name, skeleton, parentBone, matrix) {
  16591. this.name = name;
  16592. this.children = new Array();
  16593. this.animations = new Array();
  16594. this._worldTransform = new BABYLON.Matrix();
  16595. this._absoluteTransform = new BABYLON.Matrix();
  16596. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  16597. this._skeleton = skeleton;
  16598. this._matrix = matrix;
  16599. this._baseMatrix = matrix;
  16600. skeleton.bones.push(this);
  16601. if (parentBone) {
  16602. this._parent = parentBone;
  16603. parentBone.children.push(this);
  16604. }
  16605. else {
  16606. this._parent = null;
  16607. }
  16608. this._updateDifferenceMatrix();
  16609. }
  16610. // Members
  16611. Bone.prototype.getParent = function () {
  16612. return this._parent;
  16613. };
  16614. Bone.prototype.getLocalMatrix = function () {
  16615. return this._matrix;
  16616. };
  16617. Bone.prototype.getBaseMatrix = function () {
  16618. return this._baseMatrix;
  16619. };
  16620. Bone.prototype.getWorldMatrix = function () {
  16621. return this._worldTransform;
  16622. };
  16623. Bone.prototype.getInvertedAbsoluteTransform = function () {
  16624. return this._invertedAbsoluteTransform;
  16625. };
  16626. Bone.prototype.getAbsoluteMatrix = function () {
  16627. var matrix = this._matrix.clone();
  16628. var parent = this._parent;
  16629. while (parent) {
  16630. matrix = matrix.multiply(parent.getLocalMatrix());
  16631. parent = parent.getParent();
  16632. }
  16633. return matrix;
  16634. };
  16635. // Methods
  16636. Bone.prototype.updateMatrix = function (matrix) {
  16637. this._matrix = matrix;
  16638. this._skeleton._markAsDirty();
  16639. this._updateDifferenceMatrix();
  16640. };
  16641. Bone.prototype._updateDifferenceMatrix = function () {
  16642. if (this._parent) {
  16643. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  16644. }
  16645. else {
  16646. this._absoluteTransform.copyFrom(this._matrix);
  16647. }
  16648. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  16649. for (var index = 0; index < this.children.length; index++) {
  16650. this.children[index]._updateDifferenceMatrix();
  16651. }
  16652. };
  16653. Bone.prototype.markAsDirty = function () {
  16654. this._skeleton._markAsDirty();
  16655. };
  16656. return Bone;
  16657. })();
  16658. BABYLON.Bone = Bone;
  16659. })(BABYLON || (BABYLON = {}));
  16660. //# sourceMappingURL=babylon.bone.js.mapvar BABYLON;
  16661. (function (BABYLON) {
  16662. var Skeleton = (function () {
  16663. function Skeleton(name, id, scene) {
  16664. this.name = name;
  16665. this.id = id;
  16666. this.bones = new Array();
  16667. this._isDirty = true;
  16668. this._identity = BABYLON.Matrix.Identity();
  16669. this.bones = [];
  16670. this._scene = scene;
  16671. scene.skeletons.push(this);
  16672. }
  16673. // Members
  16674. Skeleton.prototype.getTransformMatrices = function () {
  16675. return this._transformMatrices;
  16676. };
  16677. // Methods
  16678. Skeleton.prototype._markAsDirty = function () {
  16679. this._isDirty = true;
  16680. };
  16681. Skeleton.prototype.prepare = function () {
  16682. if (!this._isDirty) {
  16683. return;
  16684. }
  16685. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  16686. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  16687. }
  16688. for (var index = 0; index < this.bones.length; index++) {
  16689. var bone = this.bones[index];
  16690. var parentBone = bone.getParent();
  16691. if (parentBone) {
  16692. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  16693. }
  16694. else {
  16695. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  16696. }
  16697. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  16698. }
  16699. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  16700. this._isDirty = false;
  16701. this._scene._activeBones += this.bones.length;
  16702. };
  16703. Skeleton.prototype.getAnimatables = function () {
  16704. if (!this._animatables || this._animatables.length !== this.bones.length) {
  16705. this._animatables = [];
  16706. for (var index = 0; index < this.bones.length; index++) {
  16707. this._animatables.push(this.bones[index]);
  16708. }
  16709. }
  16710. return this._animatables;
  16711. };
  16712. Skeleton.prototype.clone = function (name, id) {
  16713. var result = new Skeleton(name, id || name, this._scene);
  16714. for (var index = 0; index < this.bones.length; index++) {
  16715. var source = this.bones[index];
  16716. var parentBone = null;
  16717. if (source.getParent()) {
  16718. var parentIndex = this.bones.indexOf(source.getParent());
  16719. parentBone = result.bones[parentIndex];
  16720. }
  16721. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  16722. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  16723. }
  16724. return result;
  16725. };
  16726. return Skeleton;
  16727. })();
  16728. BABYLON.Skeleton = Skeleton;
  16729. })(BABYLON || (BABYLON = {}));
  16730. //# sourceMappingURL=babylon.skeleton.js.mapvar BABYLON;
  16731. (function (BABYLON) {
  16732. var PostProcess = (function () {
  16733. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable, defines) {
  16734. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  16735. this.name = name;
  16736. this.width = -1;
  16737. this.height = -1;
  16738. this._reusable = false;
  16739. this._textures = new BABYLON.SmartArray(2);
  16740. this._currentRenderTextureInd = 0;
  16741. if (camera != null) {
  16742. this._camera = camera;
  16743. this._scene = camera.getScene();
  16744. camera.attachPostProcess(this);
  16745. this._engine = this._scene.getEngine();
  16746. }
  16747. else {
  16748. this._engine = engine;
  16749. }
  16750. this._renderRatio = ratio;
  16751. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  16752. this._reusable = reusable || false;
  16753. samplers = samplers || [];
  16754. samplers.push("textureSampler");
  16755. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: fragmentUrl }, ["position"], parameters || [], samplers, defines !== undefined ? defines : "");
  16756. }
  16757. PostProcess.prototype.isReusable = function () {
  16758. return this._reusable;
  16759. };
  16760. PostProcess.prototype.activate = function (camera, sourceTexture) {
  16761. camera = camera || this._camera;
  16762. var scene = camera.getScene();
  16763. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  16764. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  16765. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  16766. desiredWidth = BABYLON.Tools.GetExponantOfTwo(desiredWidth, maxSize);
  16767. desiredHeight = BABYLON.Tools.GetExponantOfTwo(desiredHeight, maxSize);
  16768. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  16769. if (this._textures.length > 0) {
  16770. for (var i = 0; i < this._textures.length; i++) {
  16771. this._engine._releaseTexture(this._textures.data[i]);
  16772. }
  16773. this._textures.reset();
  16774. }
  16775. this.width = desiredWidth;
  16776. this.height = desiredHeight;
  16777. 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 }));
  16778. if (this._reusable) {
  16779. 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 }));
  16780. }
  16781. if (this.onSizeChanged) {
  16782. this.onSizeChanged();
  16783. }
  16784. }
  16785. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  16786. if (this.onActivate) {
  16787. this.onActivate(camera);
  16788. }
  16789. // Clear
  16790. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  16791. if (this._reusable) {
  16792. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  16793. }
  16794. };
  16795. PostProcess.prototype.apply = function () {
  16796. // Check
  16797. if (!this._effect.isReady())
  16798. return null;
  16799. // States
  16800. this._engine.enableEffect(this._effect);
  16801. this._engine.setState(false);
  16802. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16803. this._engine.setDepthBuffer(false);
  16804. this._engine.setDepthWrite(false);
  16805. // Texture
  16806. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  16807. // Parameters
  16808. if (this.onApply) {
  16809. this.onApply(this._effect);
  16810. }
  16811. return this._effect;
  16812. };
  16813. PostProcess.prototype.dispose = function (camera) {
  16814. camera = camera || this._camera;
  16815. if (this._textures.length > 0) {
  16816. for (var i = 0; i < this._textures.length; i++) {
  16817. this._engine._releaseTexture(this._textures.data[i]);
  16818. }
  16819. this._textures.reset();
  16820. }
  16821. if (!camera) {
  16822. return;
  16823. }
  16824. camera.detachPostProcess(this);
  16825. var index = camera._postProcesses.indexOf(this);
  16826. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  16827. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  16828. }
  16829. };
  16830. return PostProcess;
  16831. })();
  16832. BABYLON.PostProcess = PostProcess;
  16833. })(BABYLON || (BABYLON = {}));
  16834. //# sourceMappingURL=babylon.postProcess.js.mapvar BABYLON;
  16835. (function (BABYLON) {
  16836. var PostProcessManager = (function () {
  16837. function PostProcessManager(scene) {
  16838. this._vertexDeclaration = [2];
  16839. this._vertexStrideSize = 2 * 4;
  16840. this._scene = scene;
  16841. // VBO
  16842. var vertices = [];
  16843. vertices.push(1, 1);
  16844. vertices.push(-1, 1);
  16845. vertices.push(-1, -1);
  16846. vertices.push(1, -1);
  16847. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  16848. // Indices
  16849. var indices = [];
  16850. indices.push(0);
  16851. indices.push(1);
  16852. indices.push(2);
  16853. indices.push(0);
  16854. indices.push(2);
  16855. indices.push(3);
  16856. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  16857. }
  16858. // Methods
  16859. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  16860. var postProcesses = this._scene.activeCamera._postProcesses;
  16861. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  16862. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  16863. return false;
  16864. }
  16865. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  16866. return true;
  16867. };
  16868. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  16869. var engine = this._scene.getEngine();
  16870. for (var index = 0; index < postProcesses.length; index++) {
  16871. if (index < postProcesses.length - 1) {
  16872. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  16873. }
  16874. else {
  16875. if (targetTexture) {
  16876. engine.bindFramebuffer(targetTexture);
  16877. }
  16878. else {
  16879. engine.restoreDefaultFramebuffer();
  16880. }
  16881. }
  16882. var pp = postProcesses[index];
  16883. var effect = pp.apply();
  16884. if (effect) {
  16885. if (pp.onBeforeRender) {
  16886. pp.onBeforeRender(effect);
  16887. }
  16888. // VBOs
  16889. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  16890. // Draw order
  16891. engine.draw(true, 0, 6);
  16892. }
  16893. }
  16894. // Restore depth buffer
  16895. engine.setDepthBuffer(true);
  16896. engine.setDepthWrite(true);
  16897. };
  16898. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, postProcesses) {
  16899. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  16900. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  16901. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  16902. return;
  16903. }
  16904. var engine = this._scene.getEngine();
  16905. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  16906. if (index < postProcessesTakenIndices.length - 1) {
  16907. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  16908. }
  16909. else {
  16910. if (targetTexture) {
  16911. engine.bindFramebuffer(targetTexture);
  16912. }
  16913. else {
  16914. engine.restoreDefaultFramebuffer();
  16915. }
  16916. }
  16917. if (doNotPresent) {
  16918. break;
  16919. }
  16920. var pp = postProcesses[postProcessesTakenIndices[index]];
  16921. var effect = pp.apply();
  16922. if (effect) {
  16923. if (pp.onBeforeRender) {
  16924. pp.onBeforeRender(effect);
  16925. }
  16926. // VBOs
  16927. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  16928. // Draw order
  16929. engine.draw(true, 0, 6);
  16930. }
  16931. }
  16932. // Restore depth buffer
  16933. engine.setDepthBuffer(true);
  16934. engine.setDepthWrite(true);
  16935. };
  16936. PostProcessManager.prototype.dispose = function () {
  16937. if (this._vertexBuffer) {
  16938. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  16939. this._vertexBuffer = null;
  16940. }
  16941. if (this._indexBuffer) {
  16942. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  16943. this._indexBuffer = null;
  16944. }
  16945. };
  16946. return PostProcessManager;
  16947. })();
  16948. BABYLON.PostProcessManager = PostProcessManager;
  16949. })(BABYLON || (BABYLON = {}));
  16950. //# sourceMappingURL=babylon.postProcessManager.js.map
  16951. var BABYLON;
  16952. (function (BABYLON) {
  16953. var PassPostProcess = (function (_super) {
  16954. __extends(PassPostProcess, _super);
  16955. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  16956. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  16957. }
  16958. return PassPostProcess;
  16959. })(BABYLON.PostProcess);
  16960. BABYLON.PassPostProcess = PassPostProcess;
  16961. })(BABYLON || (BABYLON = {}));
  16962. //# sourceMappingURL=babylon.passPostProcess.js.map
  16963. var BABYLON;
  16964. (function (BABYLON) {
  16965. var BlurPostProcess = (function (_super) {
  16966. __extends(BlurPostProcess, _super);
  16967. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  16968. var _this = this;
  16969. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  16970. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  16971. this.direction = direction;
  16972. this.blurWidth = blurWidth;
  16973. this.onApply = function (effect) {
  16974. effect.setFloat2("screenSize", _this.width, _this.height);
  16975. effect.setVector2("direction", _this.direction);
  16976. effect.setFloat("blurWidth", _this.blurWidth);
  16977. };
  16978. }
  16979. return BlurPostProcess;
  16980. })(BABYLON.PostProcess);
  16981. BABYLON.BlurPostProcess = BlurPostProcess;
  16982. })(BABYLON || (BABYLON = {}));
  16983. //# sourceMappingURL=babylon.blurPostProcess.js.map
  16984. var BABYLON;
  16985. (function (BABYLON) {
  16986. var FilterPostProcess = (function (_super) {
  16987. __extends(FilterPostProcess, _super);
  16988. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  16989. var _this = this;
  16990. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  16991. this.kernelMatrix = kernelMatrix;
  16992. this.onApply = function (effect) {
  16993. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  16994. };
  16995. }
  16996. return FilterPostProcess;
  16997. })(BABYLON.PostProcess);
  16998. BABYLON.FilterPostProcess = FilterPostProcess;
  16999. })(BABYLON || (BABYLON = {}));
  17000. //# sourceMappingURL=babylon.filterPostProcess.js.map
  17001. var BABYLON;
  17002. (function (BABYLON) {
  17003. var RefractionPostProcess = (function (_super) {
  17004. __extends(RefractionPostProcess, _super);
  17005. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  17006. var _this = this;
  17007. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  17008. this.color = color;
  17009. this.depth = depth;
  17010. this.colorLevel = colorLevel;
  17011. this.onActivate = function (cam) {
  17012. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  17013. };
  17014. this.onApply = function (effect) {
  17015. effect.setColor3("baseColor", _this.color);
  17016. effect.setFloat("depth", _this.depth);
  17017. effect.setFloat("colorLevel", _this.colorLevel);
  17018. effect.setTexture("refractionSampler", _this._refRexture);
  17019. };
  17020. }
  17021. // Methods
  17022. RefractionPostProcess.prototype.dispose = function (camera) {
  17023. if (this._refRexture) {
  17024. this._refRexture.dispose();
  17025. }
  17026. _super.prototype.dispose.call(this, camera);
  17027. };
  17028. return RefractionPostProcess;
  17029. })(BABYLON.PostProcess);
  17030. BABYLON.RefractionPostProcess = RefractionPostProcess;
  17031. })(BABYLON || (BABYLON = {}));
  17032. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  17033. var BABYLON;
  17034. (function (BABYLON) {
  17035. var BlackAndWhitePostProcess = (function (_super) {
  17036. __extends(BlackAndWhitePostProcess, _super);
  17037. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  17038. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  17039. }
  17040. return BlackAndWhitePostProcess;
  17041. })(BABYLON.PostProcess);
  17042. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  17043. })(BABYLON || (BABYLON = {}));
  17044. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  17045. var BABYLON;
  17046. (function (BABYLON) {
  17047. var ConvolutionPostProcess = (function (_super) {
  17048. __extends(ConvolutionPostProcess, _super);
  17049. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  17050. var _this = this;
  17051. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  17052. this.kernel = kernel;
  17053. this.onApply = function (effect) {
  17054. effect.setFloat2("screenSize", _this.width, _this.height);
  17055. effect.setArray("kernel", _this.kernel);
  17056. };
  17057. }
  17058. // Statics
  17059. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  17060. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  17061. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  17062. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  17063. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  17064. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  17065. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  17066. return ConvolutionPostProcess;
  17067. })(BABYLON.PostProcess);
  17068. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  17069. })(BABYLON || (BABYLON = {}));
  17070. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  17071. var BABYLON;
  17072. (function (BABYLON) {
  17073. var FxaaPostProcess = (function (_super) {
  17074. __extends(FxaaPostProcess, _super);
  17075. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  17076. var _this = this;
  17077. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  17078. this.onSizeChanged = function () {
  17079. _this.texelWidth = 1.0 / _this.width;
  17080. _this.texelHeight = 1.0 / _this.height;
  17081. };
  17082. this.onApply = function (effect) {
  17083. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  17084. };
  17085. }
  17086. return FxaaPostProcess;
  17087. })(BABYLON.PostProcess);
  17088. BABYLON.FxaaPostProcess = FxaaPostProcess;
  17089. })(BABYLON || (BABYLON = {}));
  17090. //# sourceMappingURL=babylon.fxaaPostProcess.js.mapvar BABYLON;
  17091. (function (BABYLON) {
  17092. var LensFlare = (function () {
  17093. function LensFlare(size, position, color, imgUrl, system) {
  17094. this.size = size;
  17095. this.position = position;
  17096. this.dispose = function () {
  17097. if (this.texture) {
  17098. this.texture.dispose();
  17099. }
  17100. // Remove from scene
  17101. var index = this._system.lensFlares.indexOf(this);
  17102. this._system.lensFlares.splice(index, 1);
  17103. };
  17104. this.color = color || new BABYLON.Color3(1, 1, 1);
  17105. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  17106. this._system = system;
  17107. system.lensFlares.push(this);
  17108. }
  17109. return LensFlare;
  17110. })();
  17111. BABYLON.LensFlare = LensFlare;
  17112. })(BABYLON || (BABYLON = {}));
  17113. //# sourceMappingURL=babylon.lensFlare.js.mapvar BABYLON;
  17114. (function (BABYLON) {
  17115. var LensFlareSystem = (function () {
  17116. function LensFlareSystem(name, emitter, scene) {
  17117. this.name = name;
  17118. this.lensFlares = new Array();
  17119. this.borderLimit = 300;
  17120. this._vertexDeclaration = [2];
  17121. this._vertexStrideSize = 2 * 4;
  17122. this._isEnabled = true;
  17123. this._scene = scene;
  17124. this._emitter = emitter;
  17125. scene.lensFlareSystems.push(this);
  17126. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  17127. // VBO
  17128. var vertices = [];
  17129. vertices.push(1, 1);
  17130. vertices.push(-1, 1);
  17131. vertices.push(-1, -1);
  17132. vertices.push(1, -1);
  17133. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  17134. // Indices
  17135. var indices = [];
  17136. indices.push(0);
  17137. indices.push(1);
  17138. indices.push(2);
  17139. indices.push(0);
  17140. indices.push(2);
  17141. indices.push(3);
  17142. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  17143. // Effects
  17144. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  17145. }
  17146. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  17147. get: function () {
  17148. return this._isEnabled;
  17149. },
  17150. set: function (value) {
  17151. this._isEnabled = value;
  17152. },
  17153. enumerable: true,
  17154. configurable: true
  17155. });
  17156. LensFlareSystem.prototype.getScene = function () {
  17157. return this._scene;
  17158. };
  17159. LensFlareSystem.prototype.getEmitter = function () {
  17160. return this._emitter;
  17161. };
  17162. LensFlareSystem.prototype.getEmitterPosition = function () {
  17163. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  17164. };
  17165. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  17166. var position = this.getEmitterPosition();
  17167. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  17168. this._positionX = position.x;
  17169. this._positionY = position.y;
  17170. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  17171. if (position.z > 0) {
  17172. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  17173. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  17174. return true;
  17175. }
  17176. }
  17177. return false;
  17178. };
  17179. LensFlareSystem.prototype._isVisible = function () {
  17180. if (!this._isEnabled) {
  17181. return false;
  17182. }
  17183. var emitterPosition = this.getEmitterPosition();
  17184. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  17185. var distance = direction.length();
  17186. direction.normalize();
  17187. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  17188. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  17189. return !pickInfo.hit || pickInfo.distance > distance;
  17190. };
  17191. LensFlareSystem.prototype.render = function () {
  17192. if (!this._effect.isReady())
  17193. return false;
  17194. var engine = this._scene.getEngine();
  17195. var viewport = this._scene.activeCamera.viewport;
  17196. var globalViewport = viewport.toGlobal(engine);
  17197. // Position
  17198. if (!this.computeEffectivePosition(globalViewport)) {
  17199. return false;
  17200. }
  17201. // Visibility
  17202. if (!this._isVisible()) {
  17203. return false;
  17204. }
  17205. // Intensity
  17206. var awayX;
  17207. var awayY;
  17208. if (this._positionX < this.borderLimit + globalViewport.x) {
  17209. awayX = this.borderLimit + globalViewport.x - this._positionX;
  17210. }
  17211. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  17212. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  17213. }
  17214. else {
  17215. awayX = 0;
  17216. }
  17217. if (this._positionY < this.borderLimit + globalViewport.y) {
  17218. awayY = this.borderLimit + globalViewport.y - this._positionY;
  17219. }
  17220. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  17221. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  17222. }
  17223. else {
  17224. awayY = 0;
  17225. }
  17226. var away = (awayX > awayY) ? awayX : awayY;
  17227. if (away > this.borderLimit) {
  17228. away = this.borderLimit;
  17229. }
  17230. var intensity = 1.0 - (away / this.borderLimit);
  17231. if (intensity < 0) {
  17232. return false;
  17233. }
  17234. if (intensity > 1.0) {
  17235. intensity = 1.0;
  17236. }
  17237. // Position
  17238. var centerX = globalViewport.x + globalViewport.width / 2;
  17239. var centerY = globalViewport.y + globalViewport.height / 2;
  17240. var distX = centerX - this._positionX;
  17241. var distY = centerY - this._positionY;
  17242. // Effects
  17243. engine.enableEffect(this._effect);
  17244. engine.setState(false);
  17245. engine.setDepthBuffer(false);
  17246. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  17247. // VBOs
  17248. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  17249. for (var index = 0; index < this.lensFlares.length; index++) {
  17250. var flare = this.lensFlares[index];
  17251. var x = centerX - (distX * flare.position);
  17252. var y = centerY - (distY * flare.position);
  17253. var cw = flare.size;
  17254. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  17255. var cx = 2 * (x / globalViewport.width) - 1.0;
  17256. var cy = 1.0 - 2 * (y / globalViewport.height);
  17257. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  17258. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  17259. // Texture
  17260. this._effect.setTexture("textureSampler", flare.texture);
  17261. // Color
  17262. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  17263. // Draw order
  17264. engine.draw(true, 0, 6);
  17265. }
  17266. engine.setDepthBuffer(true);
  17267. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  17268. return true;
  17269. };
  17270. LensFlareSystem.prototype.dispose = function () {
  17271. if (this._vertexBuffer) {
  17272. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  17273. this._vertexBuffer = null;
  17274. }
  17275. if (this._indexBuffer) {
  17276. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  17277. this._indexBuffer = null;
  17278. }
  17279. while (this.lensFlares.length) {
  17280. this.lensFlares[0].dispose();
  17281. }
  17282. // Remove from scene
  17283. var index = this._scene.lensFlareSystems.indexOf(this);
  17284. this._scene.lensFlareSystems.splice(index, 1);
  17285. };
  17286. return LensFlareSystem;
  17287. })();
  17288. BABYLON.LensFlareSystem = LensFlareSystem;
  17289. })(BABYLON || (BABYLON = {}));
  17290. //# sourceMappingURL=babylon.lensFlareSystem.js.mapvar BABYLON;
  17291. (function (BABYLON) {
  17292. var IntersectionInfo = (function () {
  17293. function IntersectionInfo(bu, bv, distance) {
  17294. this.bu = bu;
  17295. this.bv = bv;
  17296. this.distance = distance;
  17297. this.faceId = 0;
  17298. this.subMeshId = 0;
  17299. }
  17300. return IntersectionInfo;
  17301. })();
  17302. BABYLON.IntersectionInfo = IntersectionInfo;
  17303. var PickingInfo = (function () {
  17304. function PickingInfo() {
  17305. this.hit = false;
  17306. this.distance = 0;
  17307. this.pickedPoint = null;
  17308. this.pickedMesh = null;
  17309. this.bu = 0;
  17310. this.bv = 0;
  17311. this.faceId = -1;
  17312. this.subMeshId = 0;
  17313. }
  17314. // Methods
  17315. PickingInfo.prototype.getNormal = function () {
  17316. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  17317. return null;
  17318. }
  17319. var indices = this.pickedMesh.getIndices();
  17320. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17321. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  17322. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  17323. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  17324. normal0 = normal0.scale(this.bu);
  17325. normal1 = normal1.scale(this.bv);
  17326. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  17327. return new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  17328. };
  17329. PickingInfo.prototype.getTextureCoordinates = function () {
  17330. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  17331. return null;
  17332. }
  17333. var indices = this.pickedMesh.getIndices();
  17334. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  17335. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  17336. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  17337. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  17338. uv0 = uv0.scale(this.bu);
  17339. uv1 = uv1.scale(this.bv);
  17340. uv2 = uv2.scale(1.0 - this.bu - this.bv);
  17341. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  17342. };
  17343. return PickingInfo;
  17344. })();
  17345. BABYLON.PickingInfo = PickingInfo;
  17346. })(BABYLON || (BABYLON = {}));
  17347. //# sourceMappingURL=babylon.pickingInfo.js.mapvar BABYLON;
  17348. (function (BABYLON) {
  17349. var FilesInput = (function () {
  17350. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  17351. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  17352. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  17353. this._engine = p_engine;
  17354. this._canvas = p_canvas;
  17355. this._currentScene = p_scene;
  17356. this._sceneLoadedCallback = p_sceneLoadedCallback;
  17357. this._progressCallback = p_progressCallback;
  17358. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  17359. this._textureLoadingCallback = p_textureLoadingCallback;
  17360. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  17361. }
  17362. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  17363. var _this = this;
  17364. if (p_elementToMonitor) {
  17365. this._elementToMonitor = p_elementToMonitor;
  17366. this._elementToMonitor.addEventListener("dragenter", function (e) {
  17367. _this.drag(e);
  17368. }, false);
  17369. this._elementToMonitor.addEventListener("dragover", function (e) {
  17370. _this.drag(e);
  17371. }, false);
  17372. this._elementToMonitor.addEventListener("drop", function (e) {
  17373. _this.drop(e);
  17374. }, false);
  17375. }
  17376. };
  17377. FilesInput.prototype.renderFunction = function () {
  17378. if (this._additionnalRenderLoopLogicCallback) {
  17379. this._additionnalRenderLoopLogicCallback();
  17380. }
  17381. if (this._currentScene) {
  17382. if (this._textureLoadingCallback) {
  17383. var remaining = this._currentScene.getWaitingItemsCount();
  17384. if (remaining > 0) {
  17385. this._textureLoadingCallback(remaining);
  17386. }
  17387. }
  17388. this._currentScene.render();
  17389. }
  17390. };
  17391. FilesInput.prototype.drag = function (e) {
  17392. e.stopPropagation();
  17393. e.preventDefault();
  17394. };
  17395. FilesInput.prototype.drop = function (eventDrop) {
  17396. eventDrop.stopPropagation();
  17397. eventDrop.preventDefault();
  17398. this.loadFiles(eventDrop);
  17399. };
  17400. FilesInput.prototype.loadFiles = function (event) {
  17401. if (this._startingProcessingFilesCallback)
  17402. this._startingProcessingFilesCallback();
  17403. // Handling data transfer via drag'n'drop
  17404. if (event && event.dataTransfer && event.dataTransfer.files) {
  17405. this._filesToLoad = event.dataTransfer.files;
  17406. }
  17407. // Handling files from input files
  17408. if (event && event.target && event.target.files) {
  17409. this._filesToLoad = event.target.files;
  17410. }
  17411. if (this._filesToLoad && this._filesToLoad.length > 0) {
  17412. for (var i = 0; i < this._filesToLoad.length; i++) {
  17413. switch (this._filesToLoad[i].type) {
  17414. case "image/jpeg":
  17415. case "image/png":
  17416. case "image/bmp":
  17417. FilesInput.FilesTextures[this._filesToLoad[i].name] = this._filesToLoad[i];
  17418. break;
  17419. case "image/targa":
  17420. case "image/vnd.ms-dds":
  17421. case "audio/wav":
  17422. case "audio/x-wav":
  17423. case "audio/mp3":
  17424. case "audio/mpeg":
  17425. case "audio/mpeg3":
  17426. case "audio/x-mpeg-3":
  17427. case "audio/ogg":
  17428. FilesInput.FilesToLoad[this._filesToLoad[i].name] = this._filesToLoad[i];
  17429. break;
  17430. default:
  17431. if (this._filesToLoad[i].name.indexOf(".babylon") !== -1 && this._filesToLoad[i].name.indexOf(".manifest") === -1 && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1 && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1) {
  17432. this._sceneFileToLoad = this._filesToLoad[i];
  17433. }
  17434. break;
  17435. }
  17436. }
  17437. this.reload();
  17438. }
  17439. };
  17440. FilesInput.prototype.reload = function () {
  17441. var _this = this;
  17442. var that = this;
  17443. // If a ".babylon" file has been provided
  17444. if (this._sceneFileToLoad) {
  17445. if (this._currentScene) {
  17446. this._engine.stopRenderLoop();
  17447. this._currentScene.dispose();
  17448. }
  17449. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  17450. that._currentScene = newScene;
  17451. // Wait for textures and shaders to be ready
  17452. that._currentScene.executeWhenReady(function () {
  17453. // Attach camera to canvas inputs
  17454. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  17455. that._currentScene.createDefaultCameraOrLight();
  17456. }
  17457. that._currentScene.activeCamera.attachControl(that._canvas);
  17458. if (that._sceneLoadedCallback) {
  17459. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  17460. }
  17461. that._engine.runRenderLoop(function () {
  17462. that.renderFunction();
  17463. });
  17464. });
  17465. }, function (progress) {
  17466. if (_this._progressCallback) {
  17467. _this._progressCallback(progress);
  17468. }
  17469. });
  17470. }
  17471. else {
  17472. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  17473. }
  17474. };
  17475. FilesInput.FilesTextures = new Array();
  17476. FilesInput.FilesToLoad = new Array();
  17477. return FilesInput;
  17478. })();
  17479. BABYLON.FilesInput = FilesInput;
  17480. })(BABYLON || (BABYLON = {}));
  17481. //# sourceMappingURL=babylon.filesInput.js.mapvar BABYLON;
  17482. (function (BABYLON) {
  17483. var OimoJSPlugin = (function () {
  17484. function OimoJSPlugin() {
  17485. this._registeredMeshes = [];
  17486. /**
  17487. * Update the body position according to the mesh position
  17488. * @param mesh
  17489. */
  17490. this.updateBodyPosition = function (mesh) {
  17491. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17492. var registeredMesh = this._registeredMeshes[index];
  17493. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  17494. var body = registeredMesh.body.body;
  17495. mesh.computeWorldMatrix(true);
  17496. var center = mesh.getBoundingInfo().boundingBox.center;
  17497. body.setPosition(center.x, center.y, center.z);
  17498. body.setRotation(mesh.rotation.x, mesh.rotation.y, mesh.rotation.z);
  17499. return;
  17500. }
  17501. // Case where the parent has been updated
  17502. if (registeredMesh.mesh.parent === mesh) {
  17503. mesh.computeWorldMatrix(true);
  17504. registeredMesh.mesh.computeWorldMatrix(true);
  17505. var absolutePosition = registeredMesh.mesh.getAbsolutePosition();
  17506. var absoluteRotation = mesh.rotation;
  17507. body = registeredMesh.body.body;
  17508. body.setPosition(absolutePosition.x, absolutePosition.y, absolutePosition.z);
  17509. body.setRotation(absoluteRotation.x, absoluteRotation.y, absoluteRotation.z);
  17510. return;
  17511. }
  17512. }
  17513. };
  17514. }
  17515. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  17516. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  17517. };
  17518. OimoJSPlugin.prototype.initialize = function (iterations) {
  17519. this._world = new OIMO.World();
  17520. this._world.clear();
  17521. };
  17522. OimoJSPlugin.prototype.setGravity = function (gravity) {
  17523. this._world.gravity = gravity;
  17524. };
  17525. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  17526. var body = null;
  17527. this.unregisterMesh(mesh);
  17528. mesh.computeWorldMatrix(true);
  17529. var initialRotation = null;
  17530. if (mesh.rotationQuaternion) {
  17531. initialRotation = mesh.rotationQuaternion.clone();
  17532. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  17533. mesh.computeWorldMatrix(true);
  17534. }
  17535. var bbox = mesh.getBoundingInfo().boundingBox;
  17536. // The delta between the mesh position and the mesh bounding box center
  17537. var deltaPosition = mesh.position.subtract(bbox.center);
  17538. // Transform delta position with the rotation
  17539. if (initialRotation) {
  17540. var m = new BABYLON.Matrix();
  17541. initialRotation.toRotationMatrix(m);
  17542. deltaPosition = BABYLON.Vector3.TransformCoordinates(deltaPosition, m);
  17543. }
  17544. switch (impostor) {
  17545. case BABYLON.PhysicsEngine.SphereImpostor:
  17546. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  17547. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  17548. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  17549. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  17550. body = new OIMO.Body({
  17551. type: 'sphere',
  17552. size: [size],
  17553. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  17554. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  17555. move: options.mass != 0,
  17556. config: [options.mass, options.friction, options.restitution],
  17557. world: this._world
  17558. });
  17559. break;
  17560. case BABYLON.PhysicsEngine.PlaneImpostor:
  17561. case BABYLON.PhysicsEngine.CylinderImpostor:
  17562. case BABYLON.PhysicsEngine.BoxImpostor:
  17563. var min = bbox.minimumWorld;
  17564. var max = bbox.maximumWorld;
  17565. var box = max.subtract(min);
  17566. var sizeX = this._checkWithEpsilon(box.x);
  17567. var sizeY = this._checkWithEpsilon(box.y);
  17568. var sizeZ = this._checkWithEpsilon(box.z);
  17569. body = new OIMO.Body({
  17570. type: 'box',
  17571. size: [sizeX, sizeY, sizeZ],
  17572. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  17573. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  17574. move: options.mass != 0,
  17575. config: [options.mass, options.friction, options.restitution],
  17576. world: this._world
  17577. });
  17578. break;
  17579. }
  17580. //If quaternion was set as the rotation of the object
  17581. if (initialRotation) {
  17582. //We have to access the rigid body's properties to set the quaternion.
  17583. //The setQuaternion function of Oimo only sets the newOrientation that is only set after an impulse is given or a collision.
  17584. body.body.orientation = new OIMO.Quat(initialRotation.w, initialRotation.x, initialRotation.y, initialRotation.z);
  17585. //update the internal rotation matrix
  17586. body.body.syncShapes();
  17587. }
  17588. this._registeredMeshes.push({
  17589. mesh: mesh,
  17590. body: body,
  17591. delta: deltaPosition
  17592. });
  17593. return body;
  17594. };
  17595. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  17596. var types = [], sizes = [], positions = [], rotations = [];
  17597. var initialMesh = parts[0].mesh;
  17598. for (var index = 0; index < parts.length; index++) {
  17599. var part = parts[index];
  17600. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  17601. types.push(bodyParameters.type);
  17602. sizes.push.apply(sizes, bodyParameters.size);
  17603. positions.push.apply(positions, bodyParameters.pos);
  17604. rotations.push.apply(rotations, bodyParameters.rot);
  17605. }
  17606. var body = new OIMO.Body({
  17607. type: types,
  17608. size: sizes,
  17609. pos: positions,
  17610. rot: rotations,
  17611. move: options.mass != 0,
  17612. config: [options.mass, options.friction, options.restitution],
  17613. world: this._world
  17614. });
  17615. this._registeredMeshes.push({
  17616. mesh: initialMesh,
  17617. body: body
  17618. });
  17619. return body;
  17620. };
  17621. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  17622. var bodyParameters = null;
  17623. var mesh = part.mesh;
  17624. // We need the bounding box/sphere info to compute the physics body
  17625. mesh.computeWorldMatrix();
  17626. switch (part.impostor) {
  17627. case BABYLON.PhysicsEngine.SphereImpostor:
  17628. var bbox = mesh.getBoundingInfo().boundingBox;
  17629. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  17630. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  17631. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  17632. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  17633. bodyParameters = {
  17634. type: 'sphere',
  17635. /* bug with oimo : sphere needs 3 sizes in this case */
  17636. size: [size, -1, -1],
  17637. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  17638. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  17639. };
  17640. break;
  17641. case BABYLON.PhysicsEngine.PlaneImpostor:
  17642. case BABYLON.PhysicsEngine.BoxImpostor:
  17643. bbox = mesh.getBoundingInfo().boundingBox;
  17644. var min = bbox.minimumWorld;
  17645. var max = bbox.maximumWorld;
  17646. var box = max.subtract(min);
  17647. var sizeX = this._checkWithEpsilon(box.x);
  17648. var sizeY = this._checkWithEpsilon(box.y);
  17649. var sizeZ = this._checkWithEpsilon(box.z);
  17650. var relativePosition = mesh.position;
  17651. bodyParameters = {
  17652. type: 'box',
  17653. size: [sizeX, sizeY, sizeZ],
  17654. pos: [relativePosition.x, relativePosition.y, relativePosition.z],
  17655. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  17656. };
  17657. break;
  17658. }
  17659. return bodyParameters;
  17660. };
  17661. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  17662. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17663. var registeredMesh = this._registeredMeshes[index];
  17664. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  17665. if (registeredMesh.body) {
  17666. this._world.removeRigidBody(registeredMesh.body.body);
  17667. this._unbindBody(registeredMesh.body);
  17668. }
  17669. this._registeredMeshes.splice(index, 1);
  17670. return;
  17671. }
  17672. }
  17673. };
  17674. OimoJSPlugin.prototype._unbindBody = function (body) {
  17675. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17676. var registeredMesh = this._registeredMeshes[index];
  17677. if (registeredMesh.body === body) {
  17678. registeredMesh.body = null;
  17679. }
  17680. }
  17681. };
  17682. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  17683. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17684. var registeredMesh = this._registeredMeshes[index];
  17685. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  17686. // Get object mass to have a behaviour similar to cannon.js
  17687. var mass = registeredMesh.body.body.massInfo.mass;
  17688. // The force is scaled with the mass of object
  17689. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  17690. return;
  17691. }
  17692. }
  17693. };
  17694. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  17695. var body1 = null, body2 = null;
  17696. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17697. var registeredMesh = this._registeredMeshes[index];
  17698. if (registeredMesh.mesh === mesh1) {
  17699. body1 = registeredMesh.body.body;
  17700. }
  17701. else if (registeredMesh.mesh === mesh2) {
  17702. body2 = registeredMesh.body.body;
  17703. }
  17704. }
  17705. if (!body1 || !body2) {
  17706. return false;
  17707. }
  17708. if (!options) {
  17709. options = {};
  17710. }
  17711. new OIMO.Link({
  17712. type: options.type,
  17713. body1: body1,
  17714. body2: body2,
  17715. min: options.min,
  17716. max: options.max,
  17717. axe1: options.axe1,
  17718. axe2: options.axe2,
  17719. pos1: [pivot1.x, pivot1.y, pivot1.z],
  17720. pos2: [pivot2.x, pivot2.y, pivot2.z],
  17721. collision: options.collision,
  17722. spring: options.spring,
  17723. world: this._world
  17724. });
  17725. return true;
  17726. };
  17727. OimoJSPlugin.prototype.dispose = function () {
  17728. this._world.clear();
  17729. while (this._registeredMeshes.length) {
  17730. this.unregisterMesh(this._registeredMeshes[0].mesh);
  17731. }
  17732. };
  17733. OimoJSPlugin.prototype.isSupported = function () {
  17734. return OIMO !== undefined;
  17735. };
  17736. OimoJSPlugin.prototype._getLastShape = function (body) {
  17737. var lastShape = body.shapes;
  17738. while (lastShape.next) {
  17739. lastShape = lastShape.next;
  17740. }
  17741. return lastShape;
  17742. };
  17743. OimoJSPlugin.prototype.runOneStep = function (time) {
  17744. this._world.step();
  17745. // Update the position of all registered meshes
  17746. var i = this._registeredMeshes.length;
  17747. var m;
  17748. while (i--) {
  17749. var body = this._registeredMeshes[i].body.body;
  17750. var mesh = this._registeredMeshes[i].mesh;
  17751. var delta = this._registeredMeshes[i].delta;
  17752. if (!body.sleeping) {
  17753. if (body.shapes.next) {
  17754. var parentShape = this._getLastShape(body);
  17755. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  17756. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  17757. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  17758. var mtx = BABYLON.Matrix.FromArray(body.getMatrix());
  17759. if (!mesh.rotationQuaternion) {
  17760. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  17761. }
  17762. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  17763. mesh.computeWorldMatrix();
  17764. }
  17765. else {
  17766. m = body.getMatrix();
  17767. mtx = BABYLON.Matrix.FromArray(m);
  17768. // Body position
  17769. var bodyX = mtx.m[12], bodyY = mtx.m[13], bodyZ = mtx.m[14];
  17770. if (!delta) {
  17771. mesh.position.x = bodyX;
  17772. mesh.position.y = bodyY;
  17773. mesh.position.z = bodyZ;
  17774. }
  17775. else {
  17776. mesh.position.x = bodyX + delta.x;
  17777. mesh.position.y = bodyY + delta.y;
  17778. mesh.position.z = bodyZ + delta.z;
  17779. }
  17780. if (!mesh.rotationQuaternion) {
  17781. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  17782. }
  17783. BABYLON.Quaternion.FromRotationMatrixToRef(mtx, mesh.rotationQuaternion);
  17784. mesh.computeWorldMatrix();
  17785. }
  17786. }
  17787. }
  17788. };
  17789. return OimoJSPlugin;
  17790. })();
  17791. BABYLON.OimoJSPlugin = OimoJSPlugin;
  17792. })(BABYLON || (BABYLON = {}));
  17793. //# sourceMappingURL=babylon.oimoJSPlugin.js.mapvar BABYLON;
  17794. (function (BABYLON) {
  17795. var PhysicsEngine = (function () {
  17796. function PhysicsEngine(plugin) {
  17797. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  17798. }
  17799. PhysicsEngine.prototype._initialize = function (gravity) {
  17800. this._currentPlugin.initialize();
  17801. this._setGravity(gravity);
  17802. };
  17803. PhysicsEngine.prototype._runOneStep = function (delta) {
  17804. if (delta > 0.1) {
  17805. delta = 0.1;
  17806. }
  17807. else if (delta <= 0) {
  17808. delta = 1.0 / 60.0;
  17809. }
  17810. this._currentPlugin.runOneStep(delta);
  17811. };
  17812. PhysicsEngine.prototype._setGravity = function (gravity) {
  17813. this.gravity = gravity || new BABYLON.Vector3(0, -9.82, 0);
  17814. this._currentPlugin.setGravity(this.gravity);
  17815. };
  17816. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  17817. return this._currentPlugin.registerMesh(mesh, impostor, options);
  17818. };
  17819. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  17820. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  17821. };
  17822. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  17823. this._currentPlugin.unregisterMesh(mesh);
  17824. };
  17825. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  17826. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  17827. };
  17828. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  17829. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  17830. };
  17831. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  17832. this._currentPlugin.updateBodyPosition(mesh);
  17833. };
  17834. PhysicsEngine.prototype.dispose = function () {
  17835. this._currentPlugin.dispose();
  17836. };
  17837. PhysicsEngine.prototype.isSupported = function () {
  17838. return this._currentPlugin.isSupported();
  17839. };
  17840. // Statics
  17841. PhysicsEngine.NoImpostor = 0;
  17842. PhysicsEngine.SphereImpostor = 1;
  17843. PhysicsEngine.BoxImpostor = 2;
  17844. PhysicsEngine.PlaneImpostor = 3;
  17845. PhysicsEngine.MeshImpostor = 4;
  17846. PhysicsEngine.CapsuleImpostor = 5;
  17847. PhysicsEngine.ConeImpostor = 6;
  17848. PhysicsEngine.CylinderImpostor = 7;
  17849. PhysicsEngine.ConvexHullImpostor = 8;
  17850. PhysicsEngine.Epsilon = 0.001;
  17851. return PhysicsEngine;
  17852. })();
  17853. BABYLON.PhysicsEngine = PhysicsEngine;
  17854. })(BABYLON || (BABYLON = {}));
  17855. //# sourceMappingURL=babylon.physicsEngine.js.mapvar BABYLON;
  17856. (function (BABYLON) {
  17857. var serializeLight = function (light) {
  17858. var serializationObject = {};
  17859. serializationObject.name = light.name;
  17860. serializationObject.id = light.id;
  17861. serializationObject.tags = BABYLON.Tags.GetTags(light);
  17862. if (light instanceof BABYLON.PointLight) {
  17863. serializationObject.type = 0;
  17864. serializationObject.position = light.position.asArray();
  17865. }
  17866. else if (light instanceof BABYLON.DirectionalLight) {
  17867. serializationObject.type = 1;
  17868. var directionalLight = light;
  17869. serializationObject.position = directionalLight.position.asArray();
  17870. serializationObject.direction = directionalLight.direction.asArray();
  17871. }
  17872. else if (light instanceof BABYLON.SpotLight) {
  17873. serializationObject.type = 2;
  17874. var spotLight = light;
  17875. serializationObject.position = spotLight.position.asArray();
  17876. serializationObject.direction = spotLight.position.asArray();
  17877. serializationObject.angle = spotLight.angle;
  17878. serializationObject.exponent = spotLight.exponent;
  17879. }
  17880. else if (light instanceof BABYLON.HemisphericLight) {
  17881. serializationObject.type = 3;
  17882. var hemisphericLight = light;
  17883. serializationObject.direction = hemisphericLight.direction.asArray();
  17884. serializationObject.groundColor = hemisphericLight.groundColor.asArray();
  17885. }
  17886. if (light.intensity) {
  17887. serializationObject.intensity = light.intensity;
  17888. }
  17889. serializationObject.range = light.range;
  17890. serializationObject.diffuse = light.diffuse.asArray();
  17891. serializationObject.specular = light.specular.asArray();
  17892. return serializationObject;
  17893. };
  17894. var serializeFresnelParameter = function (fresnelParameter) {
  17895. var serializationObject = {};
  17896. serializationObject.isEnabled = fresnelParameter.isEnabled;
  17897. serializationObject.leftColor = fresnelParameter.leftColor;
  17898. serializationObject.rightColor = fresnelParameter.rightColor;
  17899. serializationObject.bias = fresnelParameter.bias;
  17900. serializationObject.power = fresnelParameter.power;
  17901. return serializationObject;
  17902. };
  17903. var serializeCamera = function (camera) {
  17904. var serializationObject = {};
  17905. serializationObject.name = camera.name;
  17906. serializationObject.tags = BABYLON.Tags.GetTags(camera);
  17907. serializationObject.id = camera.id;
  17908. serializationObject.position = camera.position.asArray();
  17909. // Parent
  17910. if (camera.parent) {
  17911. serializationObject.parentId = camera.parent.id;
  17912. }
  17913. // Target
  17914. serializationObject.rotation = camera.rotation.asArray();
  17915. // Locked target
  17916. if (camera.lockedTarget && camera.lockedTarget.id) {
  17917. serializationObject.lockedTargetId = camera.lockedTarget.id;
  17918. }
  17919. serializationObject.fov = camera.fov;
  17920. serializationObject.minZ = camera.minZ;
  17921. serializationObject.maxZ = camera.maxZ;
  17922. serializationObject.speed = camera.speed;
  17923. serializationObject.inertia = camera.inertia;
  17924. serializationObject.checkCollisions = camera.checkCollisions;
  17925. serializationObject.applyGravity = camera.applyGravity;
  17926. if (camera.ellipsoid) {
  17927. serializationObject.ellipsoid = camera.ellipsoid.asArray();
  17928. }
  17929. // Animations
  17930. appendAnimations(camera, serializationObject);
  17931. // Layer mask
  17932. serializationObject.layerMask = camera.layerMask;
  17933. return serializationObject;
  17934. };
  17935. var appendAnimations = function (source, destination) {
  17936. if (source.animations) {
  17937. destination.animations = [];
  17938. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  17939. var animation = source.animations[animationIndex];
  17940. destination.animations.push(serializeAnimation(animation));
  17941. }
  17942. }
  17943. };
  17944. var serializeAnimation = function (animation) {
  17945. var serializationObject = {};
  17946. serializationObject.name = animation.name;
  17947. serializationObject.property = animation.targetProperty;
  17948. serializationObject.framePerSecond = animation.framePerSecond;
  17949. serializationObject.dataType = animation.dataType;
  17950. serializationObject.loopBehavior = animation.loopMode;
  17951. var dataType = animation.dataType;
  17952. serializationObject.keys = [];
  17953. var keys = animation.getKeys();
  17954. for (var index = 0; index < keys.length; index++) {
  17955. var animationKey = keys[index];
  17956. var key = {};
  17957. key.frame = animationKey.frame;
  17958. switch (dataType) {
  17959. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  17960. key.values = [animationKey.value];
  17961. break;
  17962. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  17963. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  17964. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  17965. key.values = animationKey.value.asArray();
  17966. break;
  17967. }
  17968. serializationObject.keys.push(key);
  17969. }
  17970. return serializationObject;
  17971. };
  17972. var serializeMultiMaterial = function (material) {
  17973. var serializationObject = {};
  17974. serializationObject.name = material.name;
  17975. serializationObject.id = material.id;
  17976. serializationObject.tags = BABYLON.Tags.GetTags(material);
  17977. serializationObject.materials = [];
  17978. for (var matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
  17979. var subMat = material.subMaterials[matIndex];
  17980. if (subMat) {
  17981. serializationObject.materials.push(subMat.id);
  17982. }
  17983. else {
  17984. serializationObject.materials.push(null);
  17985. }
  17986. }
  17987. return serializationObject;
  17988. };
  17989. var serializeMaterial = function (material) {
  17990. var serializationObject = {};
  17991. serializationObject.name = material.name;
  17992. serializationObject.ambient = material.ambientColor.asArray();
  17993. serializationObject.diffuse = material.diffuseColor.asArray();
  17994. serializationObject.specular = material.specularColor.asArray();
  17995. serializationObject.specularPower = material.specularPower;
  17996. serializationObject.emissive = material.emissiveColor.asArray();
  17997. serializationObject.alpha = material.alpha;
  17998. serializationObject.id = material.id;
  17999. serializationObject.tags = BABYLON.Tags.GetTags(material);
  18000. serializationObject.backFaceCulling = material.backFaceCulling;
  18001. if (material.diffuseTexture) {
  18002. serializationObject.diffuseTexture = serializeTexture(material.diffuseTexture);
  18003. }
  18004. if (material.diffuseFresnelParameters) {
  18005. serializationObject.diffuseFresnelParameters = serializeFresnelParameter(material.diffuseFresnelParameters);
  18006. }
  18007. if (material.ambientTexture) {
  18008. serializationObject.ambientTexture = serializeTexture(material.ambientTexture);
  18009. }
  18010. if (material.opacityTexture) {
  18011. serializationObject.opacityTexture = serializeTexture(material.opacityTexture);
  18012. }
  18013. if (material.opacityFresnelParameters) {
  18014. serializationObject.opacityFresnelParameters = serializeFresnelParameter(material.opacityFresnelParameters);
  18015. }
  18016. if (material.reflectionTexture) {
  18017. serializationObject.reflectionTexture = serializeTexture(material.reflectionTexture);
  18018. }
  18019. if (material.reflectionFresnelParameters) {
  18020. serializationObject.reflectionFresnelParameters = serializeFresnelParameter(material.reflectionFresnelParameters);
  18021. }
  18022. if (material.emissiveTexture) {
  18023. serializationObject.emissiveTexture = serializeTexture(material.emissiveTexture);
  18024. }
  18025. if (material.emissiveFresnelParameters) {
  18026. serializationObject.emissiveFresnelParameters = serializeFresnelParameter(material.emissiveFresnelParameters);
  18027. }
  18028. if (material.specularTexture) {
  18029. serializationObject.specularTexture = serializeTexture(material.specularTexture);
  18030. }
  18031. if (material.bumpTexture) {
  18032. serializationObject.bumpTexture = serializeTexture(material.bumpTexture);
  18033. }
  18034. return serializationObject;
  18035. };
  18036. var serializeTexture = function (texture) {
  18037. var serializationObject = {};
  18038. if (!texture.name) {
  18039. return null;
  18040. }
  18041. if (texture instanceof BABYLON.CubeTexture) {
  18042. serializationObject.name = texture.name;
  18043. serializationObject.hasAlpha = texture.hasAlpha;
  18044. serializationObject.level = texture.level;
  18045. serializationObject.coordinatesMode = texture.coordinatesMode;
  18046. return serializationObject;
  18047. }
  18048. if (texture instanceof BABYLON.MirrorTexture) {
  18049. var mirrorTexture = texture;
  18050. serializationObject.renderTargetSize = mirrorTexture.getRenderSize();
  18051. serializationObject.renderList = [];
  18052. for (var index = 0; index < mirrorTexture.renderList.length; index++) {
  18053. serializationObject.renderList.push(mirrorTexture.renderList[index].id);
  18054. }
  18055. serializationObject.mirrorPlane = mirrorTexture.mirrorPlane.asArray();
  18056. }
  18057. else if (texture instanceof BABYLON.RenderTargetTexture) {
  18058. var renderTargetTexture = texture;
  18059. serializationObject.renderTargetSize = renderTargetTexture.getRenderSize();
  18060. serializationObject.renderList = [];
  18061. for (index = 0; index < renderTargetTexture.renderList.length; index++) {
  18062. serializationObject.renderList.push(renderTargetTexture.renderList[index].id);
  18063. }
  18064. }
  18065. var regularTexture = texture;
  18066. serializationObject.name = texture.name;
  18067. serializationObject.hasAlpha = texture.hasAlpha;
  18068. serializationObject.level = texture.level;
  18069. serializationObject.coordinatesIndex = texture.coordinatesIndex;
  18070. serializationObject.coordinatesMode = texture.coordinatesMode;
  18071. serializationObject.uOffset = regularTexture.uOffset;
  18072. serializationObject.vOffset = regularTexture.vOffset;
  18073. serializationObject.uScale = regularTexture.uScale;
  18074. serializationObject.vScale = regularTexture.vScale;
  18075. serializationObject.uAng = regularTexture.uAng;
  18076. serializationObject.vAng = regularTexture.vAng;
  18077. serializationObject.wAng = regularTexture.wAng;
  18078. serializationObject.wrapU = texture.wrapU;
  18079. serializationObject.wrapV = texture.wrapV;
  18080. // Animations
  18081. appendAnimations(texture, serializationObject);
  18082. return serializationObject;
  18083. };
  18084. var serializeSkeleton = function (skeleton) {
  18085. var serializationObject = {};
  18086. serializationObject.name = skeleton.name;
  18087. serializationObject.id = skeleton.id;
  18088. serializationObject.bones = [];
  18089. for (var index = 0; index < skeleton.bones.length; index++) {
  18090. var bone = skeleton.bones[index];
  18091. var serializedBone = {
  18092. parentBoneIndex: bone.getParent() ? skeleton.bones.indexOf(bone.getParent()) : -1,
  18093. name: bone.name,
  18094. matrix: bone.getLocalMatrix().toArray()
  18095. };
  18096. serializationObject.bones.push(serializedBone);
  18097. if (bone.animations && bone.animations.length > 0) {
  18098. serializedBone.animation = serializeAnimation(bone.animations[0]);
  18099. }
  18100. }
  18101. return serializationObject;
  18102. };
  18103. var serializeParticleSystem = function (particleSystem) {
  18104. var serializationObject = {};
  18105. serializationObject.emitterId = particleSystem.emitter.id;
  18106. serializationObject.capacity = particleSystem.getCapacity();
  18107. if (particleSystem.particleTexture) {
  18108. serializationObject.textureName = particleSystem.particleTexture.name;
  18109. }
  18110. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  18111. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  18112. serializationObject.minSize = particleSystem.minSize;
  18113. serializationObject.maxSize = particleSystem.maxSize;
  18114. serializationObject.minLifeTime = particleSystem.minLifeTime;
  18115. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  18116. serializationObject.emitRate = particleSystem.emitRate;
  18117. serializationObject.minEmitBox = particleSystem.minEmitBox.asArray();
  18118. serializationObject.maxEmitBox = particleSystem.maxEmitBox.asArray();
  18119. serializationObject.gravity = particleSystem.gravity.asArray();
  18120. serializationObject.direction1 = particleSystem.direction1.asArray();
  18121. serializationObject.direction2 = particleSystem.direction2.asArray();
  18122. serializationObject.color1 = particleSystem.color1.asArray();
  18123. serializationObject.color2 = particleSystem.color2.asArray();
  18124. serializationObject.colorDead = particleSystem.colorDead.asArray();
  18125. serializationObject.updateSpeed = particleSystem.updateSpeed;
  18126. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  18127. serializationObject.textureMask = particleSystem.textureMask.asArray();
  18128. serializationObject.blendMode = particleSystem.blendMode;
  18129. return serializationObject;
  18130. };
  18131. var serializeLensFlareSystem = function (lensFlareSystem) {
  18132. var serializationObject = {};
  18133. serializationObject.emitterId = lensFlareSystem.getEmitter().id;
  18134. serializationObject.borderLimit = lensFlareSystem.borderLimit;
  18135. serializationObject.flares = [];
  18136. for (var index = 0; index < lensFlareSystem.lensFlares.length; index++) {
  18137. var flare = lensFlareSystem.lensFlares[index];
  18138. serializationObject.flares.push({
  18139. size: flare.size,
  18140. position: flare.position,
  18141. color: flare.color.asArray(),
  18142. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  18143. });
  18144. }
  18145. return serializationObject;
  18146. };
  18147. var serializeShadowGenerator = function (light) {
  18148. var serializationObject = {};
  18149. var shadowGenerator = light.getShadowGenerator();
  18150. serializationObject.lightId = light.id;
  18151. serializationObject.mapSize = shadowGenerator.getShadowMap().getRenderSize();
  18152. serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
  18153. serializationObject.usePoissonSampling = shadowGenerator.usePoissonSampling;
  18154. serializationObject.renderList = [];
  18155. for (var meshIndex = 0; meshIndex < shadowGenerator.getShadowMap().renderList.length; meshIndex++) {
  18156. var mesh = shadowGenerator.getShadowMap().renderList[meshIndex];
  18157. serializationObject.renderList.push(mesh.id);
  18158. }
  18159. return serializationObject;
  18160. };
  18161. var serializedGeometries = [];
  18162. var serializeGeometry = function (geometry, serializationGeometries) {
  18163. if (serializedGeometries[geometry.id]) {
  18164. return;
  18165. }
  18166. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  18167. serializationGeometries.boxes.push(serializeBox(geometry));
  18168. }
  18169. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  18170. serializationGeometries.spheres.push(serializeSphere(geometry));
  18171. }
  18172. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  18173. serializationGeometries.cylinders.push(serializeCylinder(geometry));
  18174. }
  18175. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  18176. serializationGeometries.toruses.push(serializeTorus(geometry));
  18177. }
  18178. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  18179. serializationGeometries.grounds.push(serializeGround(geometry));
  18180. }
  18181. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  18182. serializationGeometries.planes.push(serializePlane(geometry));
  18183. }
  18184. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  18185. serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
  18186. }
  18187. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  18188. throw new Error("Unknow primitive type");
  18189. }
  18190. else {
  18191. serializationGeometries.vertexData.push(serializeVertexData(geometry));
  18192. }
  18193. serializedGeometries[geometry.id] = true;
  18194. };
  18195. var serializeGeometryBase = function (geometry) {
  18196. var serializationObject = {};
  18197. serializationObject.id = geometry.id;
  18198. if (BABYLON.Tags.HasTags(geometry)) {
  18199. serializationObject.tags = BABYLON.Tags.GetTags(geometry);
  18200. }
  18201. return serializationObject;
  18202. };
  18203. var serializeVertexData = function (vertexData) {
  18204. var serializationObject = serializeGeometryBase(vertexData);
  18205. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  18206. serializationObject.positions = vertexData.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18207. }
  18208. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18209. serializationObject.normals = vertexData.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18210. }
  18211. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  18212. serializationObject.uvs = vertexData.getVerticesData(BABYLON.VertexBuffer.UVKind);
  18213. }
  18214. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  18215. serializationObject.uvs2 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  18216. }
  18217. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  18218. serializationObject.colors = vertexData.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  18219. }
  18220. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  18221. serializationObject.matricesIndices = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  18222. serializationObject.matricesIndices._isExpanded = true;
  18223. }
  18224. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  18225. serializationObject.matricesWeights = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  18226. }
  18227. serializationObject.indices = vertexData.getIndices();
  18228. return serializationObject;
  18229. };
  18230. var serializePrimitive = function (primitive) {
  18231. var serializationObject = serializeGeometryBase(primitive);
  18232. serializationObject.canBeRegenerated = primitive.canBeRegenerated();
  18233. return serializationObject;
  18234. };
  18235. var serializeBox = function (box) {
  18236. var serializationObject = serializePrimitive(box);
  18237. serializationObject.size = box.size;
  18238. return serializationObject;
  18239. };
  18240. var serializeSphere = function (sphere) {
  18241. var serializationObject = serializePrimitive(sphere);
  18242. serializationObject.segments = sphere.segments;
  18243. serializationObject.diameter = sphere.diameter;
  18244. return serializationObject;
  18245. };
  18246. var serializeCylinder = function (cylinder) {
  18247. var serializationObject = serializePrimitive(cylinder);
  18248. serializationObject.height = cylinder.height;
  18249. serializationObject.diameterTop = cylinder.diameterTop;
  18250. serializationObject.diameterBottom = cylinder.diameterBottom;
  18251. serializationObject.tessellation = cylinder.tessellation;
  18252. return serializationObject;
  18253. };
  18254. var serializeTorus = function (torus) {
  18255. var serializationObject = serializePrimitive(torus);
  18256. serializationObject.diameter = torus.diameter;
  18257. serializationObject.thickness = torus.thickness;
  18258. serializationObject.tessellation = torus.tessellation;
  18259. return serializationObject;
  18260. };
  18261. var serializeGround = function (ground) {
  18262. var serializationObject = serializePrimitive(ground);
  18263. serializationObject.width = ground.width;
  18264. serializationObject.height = ground.height;
  18265. serializationObject.subdivisions = ground.subdivisions;
  18266. return serializationObject;
  18267. };
  18268. var serializePlane = function (plane) {
  18269. var serializationObject = serializePrimitive(plane);
  18270. serializationObject.size = plane.size;
  18271. return serializationObject;
  18272. };
  18273. var serializeTorusKnot = function (torusKnot) {
  18274. var serializationObject = serializePrimitive(torusKnot);
  18275. serializationObject.radius = torusKnot.radius;
  18276. serializationObject.tube = torusKnot.tube;
  18277. serializationObject.radialSegments = torusKnot.radialSegments;
  18278. serializationObject.tubularSegments = torusKnot.tubularSegments;
  18279. serializationObject.p = torusKnot.p;
  18280. serializationObject.q = torusKnot.q;
  18281. return serializationObject;
  18282. };
  18283. var serializeMesh = function (mesh, serializationScene) {
  18284. var serializationObject = {};
  18285. serializationObject.name = mesh.name;
  18286. serializationObject.id = mesh.id;
  18287. if (BABYLON.Tags.HasTags(mesh)) {
  18288. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  18289. }
  18290. serializationObject.position = mesh.position.asArray();
  18291. if (mesh.rotationQuaternion) {
  18292. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  18293. }
  18294. else if (mesh.rotation) {
  18295. serializationObject.rotation = mesh.rotation.asArray();
  18296. }
  18297. serializationObject.scaling = mesh.scaling.asArray();
  18298. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  18299. serializationObject.isEnabled = mesh.isEnabled();
  18300. serializationObject.isVisible = mesh.isVisible;
  18301. serializationObject.infiniteDistance = mesh.infiniteDistance;
  18302. serializationObject.pickable = mesh.isPickable;
  18303. serializationObject.receiveShadows = mesh.receiveShadows;
  18304. serializationObject.billboardMode = mesh.billboardMode;
  18305. serializationObject.visibility = mesh.visibility;
  18306. serializationObject.checkCollisions = mesh.checkCollisions;
  18307. // Parent
  18308. if (mesh.parent) {
  18309. serializationObject.parentId = mesh.parent.id;
  18310. }
  18311. // Geometry
  18312. var geometry = mesh._geometry;
  18313. if (geometry) {
  18314. var geometryId = geometry.id;
  18315. serializationObject.geometryId = geometryId;
  18316. if (!mesh.getScene().getGeometryByID(geometryId)) {
  18317. // 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
  18318. serializeGeometry(geometry, serializationScene.geometries);
  18319. }
  18320. // SubMeshes
  18321. serializationObject.subMeshes = [];
  18322. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  18323. var subMesh = mesh.subMeshes[subIndex];
  18324. serializationObject.subMeshes.push({
  18325. materialIndex: subMesh.materialIndex,
  18326. verticesStart: subMesh.verticesStart,
  18327. verticesCount: subMesh.verticesCount,
  18328. indexStart: subMesh.indexStart,
  18329. indexCount: subMesh.indexCount
  18330. });
  18331. }
  18332. }
  18333. // Material
  18334. if (mesh.material) {
  18335. serializationObject.materialId = mesh.material.id;
  18336. }
  18337. else {
  18338. mesh.material = null;
  18339. }
  18340. // Skeleton
  18341. if (mesh.skeleton) {
  18342. serializationObject.skeletonId = mesh.skeleton.id;
  18343. }
  18344. // Physics
  18345. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  18346. serializationObject.physicsMass = mesh.getPhysicsMass();
  18347. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  18348. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  18349. switch (mesh.getPhysicsImpostor()) {
  18350. case BABYLON.PhysicsEngine.BoxImpostor:
  18351. serializationObject.physicsImpostor = 1;
  18352. break;
  18353. case BABYLON.PhysicsEngine.SphereImpostor:
  18354. serializationObject.physicsImpostor = 2;
  18355. break;
  18356. }
  18357. }
  18358. // Instances
  18359. serializationObject.instances = [];
  18360. for (var index = 0; index < mesh.instances.length; index++) {
  18361. var instance = mesh.instances[index];
  18362. var serializationInstance = {
  18363. name: instance.name,
  18364. position: instance.position,
  18365. rotation: instance.rotation,
  18366. rotationQuaternion: instance.rotationQuaternion,
  18367. scaling: instance.scaling
  18368. };
  18369. serializationObject.instances.push(serializationInstance);
  18370. // Animations
  18371. appendAnimations(instance, serializationInstance);
  18372. }
  18373. // Animations
  18374. appendAnimations(mesh, serializationObject);
  18375. // Layer mask
  18376. serializationObject.layerMask = mesh.layerMask;
  18377. return serializationObject;
  18378. };
  18379. var SceneSerializer = (function () {
  18380. function SceneSerializer() {
  18381. }
  18382. SceneSerializer.Serialize = function (scene) {
  18383. var serializationObject = {};
  18384. // Scene
  18385. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  18386. serializationObject.autoClear = scene.autoClear;
  18387. serializationObject.clearColor = scene.clearColor.asArray();
  18388. serializationObject.ambientColor = scene.ambientColor.asArray();
  18389. serializationObject.gravity = scene.gravity.asArray();
  18390. // Fog
  18391. if (scene.fogMode && scene.fogMode !== 0) {
  18392. serializationObject.fogMode = scene.fogMode;
  18393. serializationObject.fogColor = scene.fogColor.asArray();
  18394. serializationObject.fogStart = scene.fogStart;
  18395. serializationObject.fogEnd = scene.fogEnd;
  18396. serializationObject.fogDensity = scene.fogDensity;
  18397. }
  18398. // Lights
  18399. serializationObject.lights = [];
  18400. for (var index = 0; index < scene.lights.length; index++) {
  18401. var light = scene.lights[index];
  18402. serializationObject.lights.push(serializeLight(light));
  18403. }
  18404. // Cameras
  18405. serializationObject.cameras = [];
  18406. for (index = 0; index < scene.cameras.length; index++) {
  18407. var camera = scene.cameras[index];
  18408. if (camera instanceof BABYLON.FreeCamera) {
  18409. serializationObject.cameras.push(serializeCamera(camera));
  18410. }
  18411. }
  18412. if (scene.activeCamera) {
  18413. serializationObject.activeCameraID = scene.activeCamera.id;
  18414. }
  18415. // Materials
  18416. serializationObject.materials = [];
  18417. serializationObject.multiMaterials = [];
  18418. for (index = 0; index < scene.materials.length; index++) {
  18419. var material = scene.materials[index];
  18420. if (material instanceof BABYLON.StandardMaterial) {
  18421. serializationObject.materials.push(serializeMaterial(material));
  18422. }
  18423. else if (material instanceof BABYLON.MultiMaterial) {
  18424. serializationObject.multiMaterials.push(serializeMultiMaterial(material));
  18425. }
  18426. }
  18427. // Skeletons
  18428. serializationObject.skeletons = [];
  18429. for (index = 0; index < scene.skeletons.length; index++) {
  18430. serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
  18431. }
  18432. // Geometries
  18433. serializationObject.geometries = {};
  18434. serializationObject.geometries.boxes = [];
  18435. serializationObject.geometries.spheres = [];
  18436. serializationObject.geometries.cylinders = [];
  18437. serializationObject.geometries.toruses = [];
  18438. serializationObject.geometries.grounds = [];
  18439. serializationObject.geometries.planes = [];
  18440. serializationObject.geometries.torusKnots = [];
  18441. serializationObject.geometries.vertexData = [];
  18442. serializedGeometries = [];
  18443. var geometries = scene.getGeometries();
  18444. for (var index = 0; index < geometries.length; index++) {
  18445. var geometry = geometries[index];
  18446. if (geometry.isReady()) {
  18447. serializeGeometry(geometry, serializationObject.geometries);
  18448. }
  18449. }
  18450. // Meshes
  18451. serializationObject.meshes = [];
  18452. for (index = 0; index < scene.meshes.length; index++) {
  18453. var abstractMesh = scene.meshes[index];
  18454. if (abstractMesh instanceof BABYLON.Mesh) {
  18455. var mesh = abstractMesh;
  18456. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  18457. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  18458. }
  18459. }
  18460. }
  18461. // Particles Systems
  18462. serializationObject.particleSystems = [];
  18463. for (index = 0; index < scene.particleSystems.length; index++) {
  18464. serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
  18465. }
  18466. // Lens flares
  18467. serializationObject.lensFlareSystems = [];
  18468. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  18469. serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
  18470. }
  18471. // Shadows
  18472. serializationObject.shadowGenerators = [];
  18473. for (index = 0; index < scene.lights.length; index++) {
  18474. light = scene.lights[index];
  18475. if (light.getShadowGenerator()) {
  18476. serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
  18477. }
  18478. }
  18479. return serializationObject;
  18480. };
  18481. return SceneSerializer;
  18482. })();
  18483. BABYLON.SceneSerializer = SceneSerializer;
  18484. })(BABYLON || (BABYLON = {}));
  18485. //# sourceMappingURL=babylon.sceneSerializer.js.mapvar BABYLON;
  18486. (function (BABYLON) {
  18487. var SceneLoader = (function () {
  18488. function SceneLoader() {
  18489. }
  18490. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  18491. get: function () {
  18492. return SceneLoader._ForceFullSceneLoadingForIncremental;
  18493. },
  18494. set: function (value) {
  18495. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  18496. },
  18497. enumerable: true,
  18498. configurable: true
  18499. });
  18500. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  18501. get: function () {
  18502. return SceneLoader._ShowLoadingScreen;
  18503. },
  18504. set: function (value) {
  18505. SceneLoader._ShowLoadingScreen = value;
  18506. },
  18507. enumerable: true,
  18508. configurable: true
  18509. });
  18510. SceneLoader._getPluginForFilename = function (sceneFilename) {
  18511. var dotPosition = sceneFilename.lastIndexOf(".");
  18512. var queryStringPosition = sceneFilename.indexOf("?");
  18513. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  18514. for (var index = 0; index < this._registeredPlugins.length; index++) {
  18515. var plugin = this._registeredPlugins[index];
  18516. if (plugin.extensions.indexOf(extension) !== -1) {
  18517. return plugin;
  18518. }
  18519. }
  18520. return this._registeredPlugins[this._registeredPlugins.length - 1];
  18521. };
  18522. // Public functions
  18523. SceneLoader.RegisterPlugin = function (plugin) {
  18524. plugin.extensions = plugin.extensions.toLowerCase();
  18525. SceneLoader._registeredPlugins.push(plugin);
  18526. };
  18527. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  18528. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  18529. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  18530. return;
  18531. }
  18532. var manifestChecked = function (success) {
  18533. scene.database = database;
  18534. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  18535. var importMeshFromData = function (data) {
  18536. var meshes = [];
  18537. var particleSystems = [];
  18538. var skeletons = [];
  18539. try {
  18540. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  18541. if (onerror) {
  18542. onerror(scene, 'unable to load the scene');
  18543. }
  18544. return;
  18545. }
  18546. }
  18547. catch (e) {
  18548. if (onerror) {
  18549. onerror(scene, e);
  18550. }
  18551. return;
  18552. }
  18553. if (onsuccess) {
  18554. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  18555. onsuccess(meshes, particleSystems, skeletons);
  18556. }
  18557. };
  18558. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  18559. // Direct load
  18560. importMeshFromData(sceneFilename.substr(5));
  18561. return;
  18562. }
  18563. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  18564. importMeshFromData(data);
  18565. }, progressCallBack, database);
  18566. };
  18567. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  18568. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  18569. };
  18570. /**
  18571. * Load a scene
  18572. * @param rootUrl a string that defines the root url for scene and resources
  18573. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  18574. * @param engine is the instance of BABYLON.Engine to use to create the scene
  18575. */
  18576. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  18577. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  18578. };
  18579. /**
  18580. * Append a scene
  18581. * @param rootUrl a string that defines the root url for scene and resources
  18582. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  18583. * @param scene is the instance of BABYLON.Scene to append to
  18584. */
  18585. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  18586. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  18587. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  18588. return;
  18589. }
  18590. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  18591. var database;
  18592. if (SceneLoader.ShowLoadingScreen) {
  18593. scene.getEngine().displayLoadingUI();
  18594. }
  18595. var loadSceneFromData = function (data) {
  18596. scene.database = database;
  18597. if (!plugin.load(scene, data, rootUrl)) {
  18598. if (onerror) {
  18599. onerror(scene);
  18600. }
  18601. scene.getEngine().hideLoadingUI();
  18602. return;
  18603. }
  18604. if (onsuccess) {
  18605. onsuccess(scene);
  18606. }
  18607. if (SceneLoader.ShowLoadingScreen) {
  18608. scene.executeWhenReady(function () {
  18609. scene.getEngine().hideLoadingUI();
  18610. });
  18611. }
  18612. };
  18613. var manifestChecked = function (success) {
  18614. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  18615. };
  18616. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  18617. // Direct load
  18618. loadSceneFromData(sceneFilename.substr(5));
  18619. return;
  18620. }
  18621. if (rootUrl.indexOf("file:") === -1) {
  18622. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  18623. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  18624. }
  18625. else {
  18626. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  18627. }
  18628. };
  18629. // Flags
  18630. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  18631. SceneLoader._ShowLoadingScreen = true;
  18632. // Members
  18633. SceneLoader._registeredPlugins = new Array();
  18634. return SceneLoader;
  18635. })();
  18636. BABYLON.SceneLoader = SceneLoader;
  18637. ;
  18638. })(BABYLON || (BABYLON = {}));
  18639. //# sourceMappingURL=babylon.sceneLoader.js.mapvar BABYLON;
  18640. (function (BABYLON) {
  18641. var Internals;
  18642. (function (Internals) {
  18643. var checkColors4 = function (colors, count) {
  18644. // Check if color3 was used
  18645. if (colors.length === count * 3) {
  18646. var colors4 = [];
  18647. for (var index = 0; index < colors.length; index += 3) {
  18648. var newIndex = (index / 3) * 4;
  18649. colors4[newIndex] = colors[index];
  18650. colors4[newIndex + 1] = colors[index + 1];
  18651. colors4[newIndex + 2] = colors[index + 2];
  18652. colors4[newIndex + 3] = 1.0;
  18653. }
  18654. return colors4;
  18655. }
  18656. return colors;
  18657. };
  18658. var loadCubeTexture = function (rootUrl, parsedTexture, scene) {
  18659. var texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene);
  18660. texture.name = parsedTexture.name;
  18661. texture.hasAlpha = parsedTexture.hasAlpha;
  18662. texture.level = parsedTexture.level;
  18663. texture.coordinatesMode = parsedTexture.coordinatesMode;
  18664. return texture;
  18665. };
  18666. var loadTexture = function (rootUrl, parsedTexture, scene) {
  18667. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  18668. return null;
  18669. }
  18670. if (parsedTexture.isCube) {
  18671. return loadCubeTexture(rootUrl, parsedTexture, scene);
  18672. }
  18673. var texture;
  18674. if (parsedTexture.mirrorPlane) {
  18675. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  18676. texture._waitingRenderList = parsedTexture.renderList;
  18677. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  18678. }
  18679. else if (parsedTexture.isRenderTarget) {
  18680. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  18681. texture._waitingRenderList = parsedTexture.renderList;
  18682. }
  18683. else {
  18684. texture = new BABYLON.Texture(rootUrl + parsedTexture.name, scene);
  18685. }
  18686. texture.name = parsedTexture.name;
  18687. texture.hasAlpha = parsedTexture.hasAlpha;
  18688. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  18689. texture.level = parsedTexture.level;
  18690. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  18691. texture.coordinatesMode = parsedTexture.coordinatesMode;
  18692. texture.uOffset = parsedTexture.uOffset;
  18693. texture.vOffset = parsedTexture.vOffset;
  18694. texture.uScale = parsedTexture.uScale;
  18695. texture.vScale = parsedTexture.vScale;
  18696. texture.uAng = parsedTexture.uAng;
  18697. texture.vAng = parsedTexture.vAng;
  18698. texture.wAng = parsedTexture.wAng;
  18699. texture.wrapU = parsedTexture.wrapU;
  18700. texture.wrapV = parsedTexture.wrapV;
  18701. // Animations
  18702. if (parsedTexture.animations) {
  18703. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  18704. var parsedAnimation = parsedTexture.animations[animationIndex];
  18705. texture.animations.push(parseAnimation(parsedAnimation));
  18706. }
  18707. }
  18708. return texture;
  18709. };
  18710. var parseSkeleton = function (parsedSkeleton, scene) {
  18711. var skeleton = new BABYLON.Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  18712. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  18713. var parsedBone = parsedSkeleton.bones[index];
  18714. var parentBone = null;
  18715. if (parsedBone.parentBoneIndex > -1) {
  18716. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  18717. }
  18718. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  18719. if (parsedBone.animation) {
  18720. bone.animations.push(parseAnimation(parsedBone.animation));
  18721. }
  18722. }
  18723. return skeleton;
  18724. };
  18725. var parseFresnelParameters = function (parsedFresnelParameters) {
  18726. var fresnelParameters = new BABYLON.FresnelParameters();
  18727. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  18728. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  18729. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  18730. fresnelParameters.bias = parsedFresnelParameters.bias;
  18731. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  18732. return fresnelParameters;
  18733. };
  18734. var parseMaterial = function (parsedMaterial, scene, rootUrl) {
  18735. var material;
  18736. material = new BABYLON.StandardMaterial(parsedMaterial.name, scene);
  18737. material.ambientColor = BABYLON.Color3.FromArray(parsedMaterial.ambient);
  18738. material.diffuseColor = BABYLON.Color3.FromArray(parsedMaterial.diffuse);
  18739. material.specularColor = BABYLON.Color3.FromArray(parsedMaterial.specular);
  18740. material.specularPower = parsedMaterial.specularPower;
  18741. material.emissiveColor = BABYLON.Color3.FromArray(parsedMaterial.emissive);
  18742. material.alpha = parsedMaterial.alpha;
  18743. material.id = parsedMaterial.id;
  18744. BABYLON.Tags.AddTagsTo(material, parsedMaterial.tags);
  18745. material.backFaceCulling = parsedMaterial.backFaceCulling;
  18746. material.wireframe = parsedMaterial.wireframe;
  18747. if (parsedMaterial.diffuseTexture) {
  18748. material.diffuseTexture = loadTexture(rootUrl, parsedMaterial.diffuseTexture, scene);
  18749. }
  18750. if (parsedMaterial.diffuseFresnelParameters) {
  18751. material.diffuseFresnelParameters = parseFresnelParameters(parsedMaterial.diffuseFresnelParameters);
  18752. }
  18753. if (parsedMaterial.ambientTexture) {
  18754. material.ambientTexture = loadTexture(rootUrl, parsedMaterial.ambientTexture, scene);
  18755. }
  18756. if (parsedMaterial.opacityTexture) {
  18757. material.opacityTexture = loadTexture(rootUrl, parsedMaterial.opacityTexture, scene);
  18758. }
  18759. if (parsedMaterial.opacityFresnelParameters) {
  18760. material.opacityFresnelParameters = parseFresnelParameters(parsedMaterial.opacityFresnelParameters);
  18761. }
  18762. if (parsedMaterial.reflectionTexture) {
  18763. material.reflectionTexture = loadTexture(rootUrl, parsedMaterial.reflectionTexture, scene);
  18764. }
  18765. if (parsedMaterial.reflectionFresnelParameters) {
  18766. material.reflectionFresnelParameters = parseFresnelParameters(parsedMaterial.reflectionFresnelParameters);
  18767. }
  18768. if (parsedMaterial.emissiveTexture) {
  18769. material.emissiveTexture = loadTexture(rootUrl, parsedMaterial.emissiveTexture, scene);
  18770. }
  18771. if (parsedMaterial.emissiveFresnelParameters) {
  18772. material.emissiveFresnelParameters = parseFresnelParameters(parsedMaterial.emissiveFresnelParameters);
  18773. }
  18774. if (parsedMaterial.specularTexture) {
  18775. material.specularTexture = loadTexture(rootUrl, parsedMaterial.specularTexture, scene);
  18776. }
  18777. if (parsedMaterial.bumpTexture) {
  18778. material.bumpTexture = loadTexture(rootUrl, parsedMaterial.bumpTexture, scene);
  18779. }
  18780. return material;
  18781. };
  18782. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  18783. for (var index = 0; index < parsedData.materials.length; index++) {
  18784. var parsedMaterial = parsedData.materials[index];
  18785. if (parsedMaterial.id === id) {
  18786. return parseMaterial(parsedMaterial, scene, rootUrl);
  18787. }
  18788. }
  18789. return null;
  18790. };
  18791. var parseMultiMaterial = function (parsedMultiMaterial, scene) {
  18792. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  18793. multiMaterial.id = parsedMultiMaterial.id;
  18794. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  18795. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  18796. var subMatId = parsedMultiMaterial.materials[matIndex];
  18797. if (subMatId) {
  18798. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  18799. }
  18800. else {
  18801. multiMaterial.subMaterials.push(null);
  18802. }
  18803. }
  18804. return multiMaterial;
  18805. };
  18806. var parseLensFlareSystem = function (parsedLensFlareSystem, scene, rootUrl) {
  18807. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  18808. var lensFlareSystem = new BABYLON.LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  18809. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  18810. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  18811. var parsedFlare = parsedLensFlareSystem.flares[index];
  18812. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  18813. }
  18814. return lensFlareSystem;
  18815. };
  18816. var parseParticleSystem = function (parsedParticleSystem, scene, rootUrl) {
  18817. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  18818. var particleSystem = new BABYLON.ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  18819. if (parsedParticleSystem.textureName) {
  18820. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  18821. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  18822. }
  18823. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  18824. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  18825. particleSystem.minSize = parsedParticleSystem.minSize;
  18826. particleSystem.maxSize = parsedParticleSystem.maxSize;
  18827. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  18828. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  18829. particleSystem.emitter = emitter;
  18830. particleSystem.emitRate = parsedParticleSystem.emitRate;
  18831. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  18832. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  18833. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  18834. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  18835. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  18836. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  18837. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  18838. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  18839. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  18840. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  18841. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  18842. particleSystem.blendMode = parsedParticleSystem.blendMode;
  18843. particleSystem.start();
  18844. return particleSystem;
  18845. };
  18846. var parseShadowGenerator = function (parsedShadowGenerator, scene) {
  18847. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  18848. var shadowGenerator = new BABYLON.ShadowGenerator(parsedShadowGenerator.mapSize, light);
  18849. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  18850. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  18851. shadowGenerator.getShadowMap().renderList.push(mesh);
  18852. }
  18853. if (parsedShadowGenerator.usePoissonSampling) {
  18854. shadowGenerator.usePoissonSampling = true;
  18855. }
  18856. else {
  18857. shadowGenerator.useVarianceShadowMap = parsedShadowGenerator.useVarianceShadowMap;
  18858. }
  18859. return shadowGenerator;
  18860. };
  18861. var parseAnimation = function (parsedAnimation) {
  18862. var animation = new BABYLON.Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  18863. var dataType = parsedAnimation.dataType;
  18864. var keys = [];
  18865. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  18866. var key = parsedAnimation.keys[index];
  18867. var data;
  18868. switch (dataType) {
  18869. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  18870. data = key.values[0];
  18871. break;
  18872. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  18873. data = BABYLON.Quaternion.FromArray(key.values);
  18874. break;
  18875. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  18876. data = BABYLON.Matrix.FromArray(key.values);
  18877. break;
  18878. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  18879. default:
  18880. data = BABYLON.Vector3.FromArray(key.values);
  18881. break;
  18882. }
  18883. keys.push({
  18884. frame: key.frame,
  18885. value: data
  18886. });
  18887. }
  18888. animation.setKeys(keys);
  18889. return animation;
  18890. };
  18891. var parseLight = function (parsedLight, scene) {
  18892. var light;
  18893. switch (parsedLight.type) {
  18894. case 0:
  18895. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  18896. break;
  18897. case 1:
  18898. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  18899. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  18900. break;
  18901. case 2:
  18902. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  18903. break;
  18904. case 3:
  18905. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  18906. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  18907. break;
  18908. }
  18909. light.id = parsedLight.id;
  18910. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  18911. if (parsedLight.intensity !== undefined) {
  18912. light.intensity = parsedLight.intensity;
  18913. }
  18914. if (parsedLight.range) {
  18915. light.range = parsedLight.range;
  18916. }
  18917. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  18918. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  18919. if (parsedLight.excludedMeshesIds) {
  18920. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  18921. }
  18922. // Parent
  18923. if (parsedLight.parentId) {
  18924. light._waitingParentId = parsedLight.parentId;
  18925. }
  18926. if (parsedLight.includedOnlyMeshesIds) {
  18927. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  18928. }
  18929. // Animations
  18930. if (parsedLight.animations) {
  18931. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  18932. var parsedAnimation = parsedLight.animations[animationIndex];
  18933. light.animations.push(parseAnimation(parsedAnimation));
  18934. }
  18935. }
  18936. if (parsedLight.autoAnimate) {
  18937. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  18938. }
  18939. };
  18940. var parseCamera = function (parsedCamera, scene) {
  18941. var camera;
  18942. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  18943. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  18944. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  18945. var alpha = parsedCamera.alpha;
  18946. var beta = parsedCamera.beta;
  18947. var radius = parsedCamera.radius;
  18948. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  18949. var eye_space = parsedCamera.eye_space;
  18950. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, eye_space, scene);
  18951. }
  18952. else {
  18953. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  18954. }
  18955. }
  18956. else if (parsedCamera.type === "AnaglyphFreeCamera") {
  18957. eye_space = parsedCamera.eye_space;
  18958. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, eye_space, scene);
  18959. }
  18960. else if (parsedCamera.type === "DeviceOrientationCamera") {
  18961. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  18962. }
  18963. else if (parsedCamera.type === "FollowCamera") {
  18964. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  18965. camera.heightOffset = parsedCamera.heightOffset;
  18966. camera.radius = parsedCamera.radius;
  18967. camera.rotationOffset = parsedCamera.rotationOffset;
  18968. if (lockedTargetMesh)
  18969. camera.target = lockedTargetMesh;
  18970. }
  18971. else if (parsedCamera.type === "GamepadCamera") {
  18972. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  18973. }
  18974. else if (parsedCamera.type === "OculusCamera") {
  18975. camera = new BABYLON.OculusCamera(parsedCamera.name, position, scene);
  18976. }
  18977. else if (parsedCamera.type === "OculusGamepadCamera") {
  18978. camera = new BABYLON.OculusGamepadCamera(parsedCamera.name, position, scene);
  18979. }
  18980. else if (parsedCamera.type === "TouchCamera") {
  18981. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  18982. }
  18983. else if (parsedCamera.type === "VirtualJoysticksCamera") {
  18984. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  18985. }
  18986. else if (parsedCamera.type === "WebVRCamera") {
  18987. camera = new BABYLON.WebVRCamera(parsedCamera.name, position, scene);
  18988. }
  18989. else if (parsedCamera.type === "VRDeviceOrientationCamera") {
  18990. camera = new BABYLON.VRDeviceOrientationCamera(parsedCamera.name, position, scene);
  18991. }
  18992. else {
  18993. // Free Camera is the default value
  18994. camera = new BABYLON.FreeCamera(parsedCamera.name, position, scene);
  18995. }
  18996. // Test for lockedTargetMesh & FreeCamera outside of if-else-if nest, since things like GamepadCamera extend FreeCamera
  18997. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  18998. camera.lockedTarget = lockedTargetMesh;
  18999. }
  19000. camera.id = parsedCamera.id;
  19001. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  19002. // Parent
  19003. if (parsedCamera.parentId) {
  19004. camera._waitingParentId = parsedCamera.parentId;
  19005. }
  19006. // Target
  19007. if (parsedCamera.target) {
  19008. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  19009. }
  19010. else {
  19011. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  19012. }
  19013. camera.fov = parsedCamera.fov;
  19014. camera.minZ = parsedCamera.minZ;
  19015. camera.maxZ = parsedCamera.maxZ;
  19016. camera.speed = parsedCamera.speed;
  19017. camera.inertia = parsedCamera.inertia;
  19018. camera.checkCollisions = parsedCamera.checkCollisions;
  19019. camera.applyGravity = parsedCamera.applyGravity;
  19020. if (parsedCamera.ellipsoid) {
  19021. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  19022. }
  19023. // Animations
  19024. if (parsedCamera.animations) {
  19025. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  19026. var parsedAnimation = parsedCamera.animations[animationIndex];
  19027. camera.animations.push(parseAnimation(parsedAnimation));
  19028. }
  19029. }
  19030. if (parsedCamera.autoAnimate) {
  19031. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  19032. }
  19033. // Layer Mask
  19034. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  19035. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  19036. }
  19037. else {
  19038. camera.layerMask = 0xFFFFFFFF;
  19039. }
  19040. return camera;
  19041. };
  19042. var parseGeometry = function (parsedGeometry, scene) {
  19043. var id = parsedGeometry.id;
  19044. return scene.getGeometryByID(id);
  19045. };
  19046. var parseBox = function (parsedBox, scene) {
  19047. if (parseGeometry(parsedBox, scene)) {
  19048. return null; // null since geometry could be something else than a box...
  19049. }
  19050. var box = new BABYLON.Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  19051. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  19052. scene.pushGeometry(box, true);
  19053. return box;
  19054. };
  19055. var parseSphere = function (parsedSphere, scene) {
  19056. if (parseGeometry(parsedSphere, scene)) {
  19057. return null; // null since geometry could be something else than a sphere...
  19058. }
  19059. var sphere = new BABYLON.Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  19060. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  19061. scene.pushGeometry(sphere, true);
  19062. return sphere;
  19063. };
  19064. var parseCylinder = function (parsedCylinder, scene) {
  19065. if (parseGeometry(parsedCylinder, scene)) {
  19066. return null; // null since geometry could be something else than a cylinder...
  19067. }
  19068. var cylinder = new BABYLON.Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  19069. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  19070. scene.pushGeometry(cylinder, true);
  19071. return cylinder;
  19072. };
  19073. var parseTorus = function (parsedTorus, scene) {
  19074. if (parseGeometry(parsedTorus, scene)) {
  19075. return null; // null since geometry could be something else than a torus...
  19076. }
  19077. var torus = new BABYLON.Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  19078. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  19079. scene.pushGeometry(torus, true);
  19080. return torus;
  19081. };
  19082. var parseGround = function (parsedGround, scene) {
  19083. if (parseGeometry(parsedGround, scene)) {
  19084. return null; // null since geometry could be something else than a ground...
  19085. }
  19086. var ground = new BABYLON.Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  19087. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  19088. scene.pushGeometry(ground, true);
  19089. return ground;
  19090. };
  19091. var parsePlane = function (parsedPlane, scene) {
  19092. if (parseGeometry(parsedPlane, scene)) {
  19093. return null; // null since geometry could be something else than a plane...
  19094. }
  19095. var plane = new BABYLON.Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  19096. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  19097. scene.pushGeometry(plane, true);
  19098. return plane;
  19099. };
  19100. var parseTorusKnot = function (parsedTorusKnot, scene) {
  19101. if (parseGeometry(parsedTorusKnot, scene)) {
  19102. return null; // null since geometry could be something else than a torusKnot...
  19103. }
  19104. 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);
  19105. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  19106. scene.pushGeometry(torusKnot, true);
  19107. return torusKnot;
  19108. };
  19109. var parseVertexData = function (parsedVertexData, scene, rootUrl) {
  19110. if (parseGeometry(parsedVertexData, scene)) {
  19111. return null; // null since geometry could be a primitive
  19112. }
  19113. var geometry = new BABYLON.Geometry(parsedVertexData.id, scene);
  19114. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  19115. if (parsedVertexData.delayLoadingFile) {
  19116. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19117. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  19118. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  19119. geometry._delayInfo = [];
  19120. if (parsedVertexData.hasUVs) {
  19121. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  19122. }
  19123. if (parsedVertexData.hasUVs2) {
  19124. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  19125. }
  19126. if (parsedVertexData.hasColors) {
  19127. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  19128. }
  19129. if (parsedVertexData.hasMatricesIndices) {
  19130. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  19131. }
  19132. if (parsedVertexData.hasMatricesWeights) {
  19133. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  19134. }
  19135. geometry._delayLoadingFunction = importVertexData;
  19136. }
  19137. else {
  19138. importVertexData(parsedVertexData, geometry);
  19139. }
  19140. scene.pushGeometry(geometry, true);
  19141. return geometry;
  19142. };
  19143. var parseMesh = function (parsedMesh, scene, rootUrl) {
  19144. var mesh = new BABYLON.Mesh(parsedMesh.name, scene);
  19145. mesh.id = parsedMesh.id;
  19146. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  19147. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  19148. if (parsedMesh.rotationQuaternion) {
  19149. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  19150. }
  19151. else if (parsedMesh.rotation) {
  19152. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  19153. }
  19154. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  19155. if (parsedMesh.localMatrix) {
  19156. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  19157. }
  19158. else if (parsedMesh.pivotMatrix) {
  19159. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  19160. }
  19161. mesh.setEnabled(parsedMesh.isEnabled);
  19162. mesh.isVisible = parsedMesh.isVisible;
  19163. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  19164. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  19165. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  19166. if (parsedMesh.applyFog !== undefined) {
  19167. mesh.applyFog = parsedMesh.applyFog;
  19168. }
  19169. if (parsedMesh.pickable !== undefined) {
  19170. mesh.isPickable = parsedMesh.pickable;
  19171. }
  19172. if (parsedMesh.alphaIndex !== undefined) {
  19173. mesh.alphaIndex = parsedMesh.alphaIndex;
  19174. }
  19175. mesh.receiveShadows = parsedMesh.receiveShadows;
  19176. mesh.billboardMode = parsedMesh.billboardMode;
  19177. if (parsedMesh.visibility !== undefined) {
  19178. mesh.visibility = parsedMesh.visibility;
  19179. }
  19180. mesh.checkCollisions = parsedMesh.checkCollisions;
  19181. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  19182. // Parent
  19183. if (parsedMesh.parentId) {
  19184. mesh._waitingParentId = parsedMesh.parentId;
  19185. }
  19186. // Actions
  19187. if (parsedMesh.actions !== undefined) {
  19188. mesh._waitingActions = parsedMesh.actions;
  19189. }
  19190. // Geometry
  19191. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  19192. if (parsedMesh.delayLoadingFile) {
  19193. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19194. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  19195. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  19196. if (parsedMesh._binaryInfo) {
  19197. mesh._binaryInfo = parsedMesh._binaryInfo;
  19198. }
  19199. mesh._delayInfo = [];
  19200. if (parsedMesh.hasUVs) {
  19201. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  19202. }
  19203. if (parsedMesh.hasUVs2) {
  19204. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  19205. }
  19206. if (parsedMesh.hasColors) {
  19207. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  19208. }
  19209. if (parsedMesh.hasMatricesIndices) {
  19210. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  19211. }
  19212. if (parsedMesh.hasMatricesWeights) {
  19213. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  19214. }
  19215. mesh._delayLoadingFunction = importGeometry;
  19216. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  19217. mesh._checkDelayState();
  19218. }
  19219. }
  19220. else {
  19221. importGeometry(parsedMesh, mesh);
  19222. }
  19223. // Material
  19224. if (parsedMesh.materialId) {
  19225. mesh.setMaterialByID(parsedMesh.materialId);
  19226. }
  19227. else {
  19228. mesh.material = null;
  19229. }
  19230. // Skeleton
  19231. if (parsedMesh.skeletonId > -1) {
  19232. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  19233. }
  19234. // Physics
  19235. if (parsedMesh.physicsImpostor) {
  19236. if (!scene.isPhysicsEnabled()) {
  19237. scene.enablePhysics();
  19238. }
  19239. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  19240. }
  19241. // Animations
  19242. if (parsedMesh.animations) {
  19243. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  19244. var parsedAnimation = parsedMesh.animations[animationIndex];
  19245. mesh.animations.push(parseAnimation(parsedAnimation));
  19246. }
  19247. }
  19248. if (parsedMesh.autoAnimate) {
  19249. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  19250. }
  19251. // Layer Mask
  19252. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  19253. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  19254. }
  19255. else {
  19256. mesh.layerMask = 0xFFFFFFFF;
  19257. }
  19258. // Instances
  19259. if (parsedMesh.instances) {
  19260. for (var index = 0; index < parsedMesh.instances.length; index++) {
  19261. var parsedInstance = parsedMesh.instances[index];
  19262. var instance = mesh.createInstance(parsedInstance.name);
  19263. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  19264. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  19265. if (parsedInstance.rotationQuaternion) {
  19266. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  19267. }
  19268. else if (parsedInstance.rotation) {
  19269. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  19270. }
  19271. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  19272. instance.checkCollisions = mesh.checkCollisions;
  19273. if (parsedMesh.animations) {
  19274. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  19275. parsedAnimation = parsedMesh.animations[animationIndex];
  19276. instance.animations.push(parseAnimation(parsedAnimation));
  19277. }
  19278. }
  19279. }
  19280. }
  19281. return mesh;
  19282. };
  19283. var parseActions = function (parsedActions, object, scene) {
  19284. var actionManager = new BABYLON.ActionManager(scene);
  19285. if (object === null)
  19286. scene.actionManager = actionManager;
  19287. else
  19288. object.actionManager = actionManager;
  19289. // instanciate a new object
  19290. var instanciate = function (name, params) {
  19291. var newInstance = Object.create(BABYLON[name].prototype);
  19292. newInstance.constructor.apply(newInstance, params);
  19293. return newInstance;
  19294. };
  19295. var parseParameter = function (name, value, target, propertyPath) {
  19296. if (propertyPath === null) {
  19297. // String, boolean or float
  19298. var floatValue = parseFloat(value);
  19299. if (value === "true" || value === "false")
  19300. return value === "true";
  19301. else
  19302. return isNaN(floatValue) ? value : floatValue;
  19303. }
  19304. var effectiveTarget = propertyPath.split(".");
  19305. var values = value.split(",");
  19306. for (var i = 0; i < effectiveTarget.length; i++) {
  19307. target = target[effectiveTarget[i]];
  19308. }
  19309. // Return appropriate value with its type
  19310. if (target instanceof Boolean)
  19311. return values[0] === "true";
  19312. if (target instanceof String)
  19313. return values[0];
  19314. // Parameters with multiple values such as Vector3 etc.
  19315. var split = new Array();
  19316. for (var i = 0; i < values.length; i++)
  19317. split.push(parseFloat(values[i]));
  19318. if (target instanceof BABYLON.Vector3)
  19319. return BABYLON.Vector3.FromArray(split);
  19320. if (target instanceof BABYLON.Vector4)
  19321. return BABYLON.Vector4.FromArray(split);
  19322. if (target instanceof BABYLON.Color3)
  19323. return BABYLON.Color3.FromArray(split);
  19324. if (target instanceof BABYLON.Color4)
  19325. return BABYLON.Color4.FromArray(split);
  19326. return parseFloat(values[0]);
  19327. };
  19328. // traverse graph per trigger
  19329. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  19330. if (combineArray === void 0) { combineArray = null; }
  19331. if (parsedAction.detached)
  19332. return;
  19333. var parameters = new Array();
  19334. var target = null;
  19335. var propertyPath = null;
  19336. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  19337. // Parameters
  19338. if (parsedAction.type === 2)
  19339. parameters.push(actionManager);
  19340. else
  19341. parameters.push(trigger);
  19342. if (combine) {
  19343. var actions = new Array();
  19344. for (var j = 0; j < parsedAction.combine.length; j++) {
  19345. traverse(parsedAction.combine[j], BABYLON.ActionManager.NothingTrigger, condition, action, actions);
  19346. }
  19347. parameters.push(actions);
  19348. }
  19349. else {
  19350. for (var i = 0; i < parsedAction.properties.length; i++) {
  19351. var value = parsedAction.properties[i].value;
  19352. var name = parsedAction.properties[i].name;
  19353. if (name === "target")
  19354. value = target = scene.getNodeByName(value);
  19355. else if (name === "parent")
  19356. value = scene.getNodeByName(value);
  19357. else if (name === "sound")
  19358. value = scene.getSoundByName(value);
  19359. else if (name !== "propertyPath") {
  19360. if (parsedAction.type === 2 && name === "operator")
  19361. value = BABYLON.ValueCondition[value];
  19362. else
  19363. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  19364. }
  19365. else {
  19366. propertyPath = value;
  19367. }
  19368. parameters.push(value);
  19369. }
  19370. }
  19371. parameters.push(condition);
  19372. // If interpolate value action
  19373. if (parsedAction.name === "InterpolateValueAction") {
  19374. var param = parameters[parameters.length - 2];
  19375. parameters[parameters.length - 1] = param;
  19376. parameters[parameters.length - 2] = condition;
  19377. }
  19378. // Action or condition(s) and not CombineAction
  19379. var newAction = instanciate(parsedAction.name, parameters);
  19380. if (combineArray === null) {
  19381. if (newAction instanceof BABYLON.Condition) {
  19382. condition = newAction;
  19383. newAction = action;
  19384. }
  19385. else {
  19386. condition = null;
  19387. if (action)
  19388. action.then(newAction);
  19389. else
  19390. actionManager.registerAction(newAction);
  19391. }
  19392. }
  19393. else {
  19394. if (combineArray !== null)
  19395. combineArray.push(newAction);
  19396. }
  19397. for (var i = 0; i < parsedAction.children.length; i++)
  19398. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  19399. };
  19400. for (var i = 0; i < parsedActions.children.length; i++) {
  19401. var triggerParams;
  19402. var trigger = parsedActions.children[i];
  19403. if (trigger.properties.length > 0) {
  19404. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: scene.getMeshByName(trigger.properties[0].value) };
  19405. }
  19406. else
  19407. triggerParams = BABYLON.ActionManager[trigger.name];
  19408. for (var j = 0; j < trigger.children.length; j++)
  19409. traverse(trigger.children[j], triggerParams, null, null);
  19410. }
  19411. };
  19412. var parseSound = function (parsedSound, scene, rootUrl) {
  19413. var soundName = parsedSound.name;
  19414. var soundUrl = rootUrl + soundName;
  19415. var options = {
  19416. autoplay: parsedSound.autoplay,
  19417. loop: parsedSound.loop,
  19418. volume: parsedSound.volume,
  19419. spatialSound: parsedSound.spatialSound,
  19420. maxDistance: parsedSound.maxDistance,
  19421. rolloffFactor: parsedSound.rolloffFactor,
  19422. refDistance: parsedSound.refDistance,
  19423. distanceModel: parsedSound.distanceModel,
  19424. panningModel: parsedSound.panningModel,
  19425. playbackRate: parsedSound.playbackRate
  19426. };
  19427. var newSound = new BABYLON.Sound(soundName, soundUrl, scene, function () {
  19428. scene._removePendingData(newSound);
  19429. }, options);
  19430. scene._addPendingData(newSound);
  19431. if (parsedSound.position) {
  19432. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  19433. newSound.setPosition(soundPosition);
  19434. }
  19435. if (parsedSound.isDirectional) {
  19436. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  19437. if (parsedSound.localDirectionToMesh) {
  19438. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  19439. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  19440. }
  19441. }
  19442. if (parsedSound.connectedMeshId) {
  19443. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  19444. if (connectedMesh) {
  19445. newSound.attachToMesh(connectedMesh);
  19446. }
  19447. }
  19448. };
  19449. var isDescendantOf = function (mesh, names, hierarchyIds) {
  19450. names = (names instanceof Array) ? names : [names];
  19451. for (var i in names) {
  19452. if (mesh.name === names[i]) {
  19453. hierarchyIds.push(mesh.id);
  19454. return true;
  19455. }
  19456. }
  19457. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  19458. hierarchyIds.push(mesh.id);
  19459. return true;
  19460. }
  19461. return false;
  19462. };
  19463. var importVertexData = function (parsedVertexData, geometry) {
  19464. var vertexData = new BABYLON.VertexData();
  19465. // positions
  19466. var positions = parsedVertexData.positions;
  19467. if (positions) {
  19468. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  19469. }
  19470. // normals
  19471. var normals = parsedVertexData.normals;
  19472. if (normals) {
  19473. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  19474. }
  19475. // uvs
  19476. var uvs = parsedVertexData.uvs;
  19477. if (uvs) {
  19478. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  19479. }
  19480. // uv2s
  19481. var uv2s = parsedVertexData.uv2s;
  19482. if (uv2s) {
  19483. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  19484. }
  19485. // colors
  19486. var colors = parsedVertexData.colors;
  19487. if (colors) {
  19488. vertexData.set(checkColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  19489. }
  19490. // matricesIndices
  19491. var matricesIndices = parsedVertexData.matricesIndices;
  19492. if (matricesIndices) {
  19493. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  19494. }
  19495. // matricesWeights
  19496. var matricesWeights = parsedVertexData.matricesWeights;
  19497. if (matricesWeights) {
  19498. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  19499. }
  19500. // indices
  19501. var indices = parsedVertexData.indices;
  19502. if (indices) {
  19503. vertexData.indices = indices;
  19504. }
  19505. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  19506. };
  19507. var importGeometry = function (parsedGeometry, mesh) {
  19508. var scene = mesh.getScene();
  19509. // Geometry
  19510. var geometryId = parsedGeometry.geometryId;
  19511. if (geometryId) {
  19512. var geometry = scene.getGeometryByID(geometryId);
  19513. if (geometry) {
  19514. geometry.applyToMesh(mesh);
  19515. }
  19516. }
  19517. else if (parsedGeometry instanceof ArrayBuffer) {
  19518. var binaryInfo = mesh._binaryInfo;
  19519. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  19520. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  19521. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  19522. }
  19523. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  19524. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  19525. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  19526. }
  19527. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  19528. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  19529. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  19530. }
  19531. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  19532. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  19533. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  19534. }
  19535. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  19536. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  19537. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false);
  19538. }
  19539. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  19540. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  19541. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  19542. }
  19543. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  19544. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  19545. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  19546. }
  19547. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  19548. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  19549. mesh.setIndices(indicesData);
  19550. }
  19551. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  19552. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  19553. mesh.subMeshes = [];
  19554. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  19555. var materialIndex = subMeshesData[(i * 5) + 0];
  19556. var verticesStart = subMeshesData[(i * 5) + 1];
  19557. var verticesCount = subMeshesData[(i * 5) + 2];
  19558. var indexStart = subMeshesData[(i * 5) + 3];
  19559. var indexCount = subMeshesData[(i * 5) + 4];
  19560. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  19561. }
  19562. }
  19563. }
  19564. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  19565. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  19566. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  19567. if (parsedGeometry.uvs) {
  19568. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  19569. }
  19570. if (parsedGeometry.uvs2) {
  19571. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  19572. }
  19573. if (parsedGeometry.colors) {
  19574. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, checkColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  19575. }
  19576. if (parsedGeometry.matricesIndices) {
  19577. if (!parsedGeometry.matricesIndices._isExpanded) {
  19578. var floatIndices = [];
  19579. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  19580. var matricesIndex = parsedGeometry.matricesIndices[i];
  19581. floatIndices.push(matricesIndex & 0x000000FF);
  19582. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  19583. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  19584. floatIndices.push(matricesIndex >> 24);
  19585. }
  19586. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  19587. }
  19588. else {
  19589. delete parsedGeometry.matricesIndices._isExpanded;
  19590. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  19591. }
  19592. }
  19593. if (parsedGeometry.matricesWeights) {
  19594. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  19595. }
  19596. mesh.setIndices(parsedGeometry.indices);
  19597. // SubMeshes
  19598. if (parsedGeometry.subMeshes) {
  19599. mesh.subMeshes = [];
  19600. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  19601. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  19602. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  19603. }
  19604. }
  19605. }
  19606. // Flat shading
  19607. if (mesh._shouldGenerateFlatShading) {
  19608. mesh.convertToFlatShadedMesh();
  19609. delete mesh._shouldGenerateFlatShading;
  19610. }
  19611. // Update
  19612. mesh.computeWorldMatrix(true);
  19613. // Octree
  19614. if (scene._selectionOctree) {
  19615. scene._selectionOctree.addMesh(mesh);
  19616. }
  19617. };
  19618. BABYLON.SceneLoader.RegisterPlugin({
  19619. extensions: ".babylon",
  19620. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  19621. var parsedData = JSON.parse(data);
  19622. var loadedSkeletonsIds = [];
  19623. var loadedMaterialsIds = [];
  19624. var hierarchyIds = [];
  19625. for (var index = 0; index < parsedData.meshes.length; index++) {
  19626. var parsedMesh = parsedData.meshes[index];
  19627. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  19628. if (meshesNames instanceof Array) {
  19629. // Remove found mesh name from list.
  19630. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  19631. }
  19632. // Material ?
  19633. if (parsedMesh.materialId) {
  19634. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  19635. if (!materialFound) {
  19636. for (var multimatIndex = 0; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
  19637. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  19638. if (parsedMultiMaterial.id == parsedMesh.materialId) {
  19639. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  19640. var subMatId = parsedMultiMaterial.materials[matIndex];
  19641. loadedMaterialsIds.push(subMatId);
  19642. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  19643. }
  19644. loadedMaterialsIds.push(parsedMultiMaterial.id);
  19645. parseMultiMaterial(parsedMultiMaterial, scene);
  19646. materialFound = true;
  19647. break;
  19648. }
  19649. }
  19650. }
  19651. if (!materialFound) {
  19652. loadedMaterialsIds.push(parsedMesh.materialId);
  19653. parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  19654. }
  19655. }
  19656. // Skeleton ?
  19657. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  19658. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  19659. if (!skeletonAlreadyLoaded) {
  19660. for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
  19661. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  19662. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  19663. skeletons.push(parseSkeleton(parsedSkeleton, scene));
  19664. loadedSkeletonsIds.push(parsedSkeleton.id);
  19665. }
  19666. }
  19667. }
  19668. }
  19669. var mesh = parseMesh(parsedMesh, scene, rootUrl);
  19670. meshes.push(mesh);
  19671. }
  19672. }
  19673. for (index = 0; index < scene.meshes.length; index++) {
  19674. var currentMesh = scene.meshes[index];
  19675. if (currentMesh._waitingParentId) {
  19676. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  19677. currentMesh._waitingParentId = undefined;
  19678. }
  19679. }
  19680. // Particles
  19681. if (parsedData.particleSystems) {
  19682. for (index = 0; index < parsedData.particleSystems.length; index++) {
  19683. var parsedParticleSystem = parsedData.particleSystems[index];
  19684. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  19685. particleSystems.push(parseParticleSystem(parsedParticleSystem, scene, rootUrl));
  19686. }
  19687. }
  19688. }
  19689. return true;
  19690. },
  19691. load: function (scene, data, rootUrl) {
  19692. var parsedData = JSON.parse(data);
  19693. // Scene
  19694. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  19695. scene.autoClear = parsedData.autoClear;
  19696. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  19697. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  19698. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  19699. // Fog
  19700. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  19701. scene.fogMode = parsedData.fogMode;
  19702. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  19703. scene.fogStart = parsedData.fogStart;
  19704. scene.fogEnd = parsedData.fogEnd;
  19705. scene.fogDensity = parsedData.fogDensity;
  19706. }
  19707. for (var index = 0; index < parsedData.lights.length; index++) {
  19708. var parsedLight = parsedData.lights[index];
  19709. parseLight(parsedLight, scene);
  19710. }
  19711. // Materials
  19712. if (parsedData.materials) {
  19713. for (index = 0; index < parsedData.materials.length; index++) {
  19714. var parsedMaterial = parsedData.materials[index];
  19715. parseMaterial(parsedMaterial, scene, rootUrl);
  19716. }
  19717. }
  19718. if (parsedData.multiMaterials) {
  19719. for (index = 0; index < parsedData.multiMaterials.length; index++) {
  19720. var parsedMultiMaterial = parsedData.multiMaterials[index];
  19721. parseMultiMaterial(parsedMultiMaterial, scene);
  19722. }
  19723. }
  19724. // Skeletons
  19725. if (parsedData.skeletons) {
  19726. for (index = 0; index < parsedData.skeletons.length; index++) {
  19727. var parsedSkeleton = parsedData.skeletons[index];
  19728. parseSkeleton(parsedSkeleton, scene);
  19729. }
  19730. }
  19731. // Geometries
  19732. var geometries = parsedData.geometries;
  19733. if (geometries) {
  19734. // Boxes
  19735. var boxes = geometries.boxes;
  19736. if (boxes) {
  19737. for (index = 0; index < boxes.length; index++) {
  19738. var parsedBox = boxes[index];
  19739. parseBox(parsedBox, scene);
  19740. }
  19741. }
  19742. // Spheres
  19743. var spheres = geometries.spheres;
  19744. if (spheres) {
  19745. for (index = 0; index < spheres.length; index++) {
  19746. var parsedSphere = spheres[index];
  19747. parseSphere(parsedSphere, scene);
  19748. }
  19749. }
  19750. // Cylinders
  19751. var cylinders = geometries.cylinders;
  19752. if (cylinders) {
  19753. for (index = 0; index < cylinders.length; index++) {
  19754. var parsedCylinder = cylinders[index];
  19755. parseCylinder(parsedCylinder, scene);
  19756. }
  19757. }
  19758. // Toruses
  19759. var toruses = geometries.toruses;
  19760. if (toruses) {
  19761. for (index = 0; index < toruses.length; index++) {
  19762. var parsedTorus = toruses[index];
  19763. parseTorus(parsedTorus, scene);
  19764. }
  19765. }
  19766. // Grounds
  19767. var grounds = geometries.grounds;
  19768. if (grounds) {
  19769. for (index = 0; index < grounds.length; index++) {
  19770. var parsedGround = grounds[index];
  19771. parseGround(parsedGround, scene);
  19772. }
  19773. }
  19774. // Planes
  19775. var planes = geometries.planes;
  19776. if (planes) {
  19777. for (index = 0; index < planes.length; index++) {
  19778. var parsedPlane = planes[index];
  19779. parsePlane(parsedPlane, scene);
  19780. }
  19781. }
  19782. // TorusKnots
  19783. var torusKnots = geometries.torusKnots;
  19784. if (torusKnots) {
  19785. for (index = 0; index < torusKnots.length; index++) {
  19786. var parsedTorusKnot = torusKnots[index];
  19787. parseTorusKnot(parsedTorusKnot, scene);
  19788. }
  19789. }
  19790. // VertexData
  19791. var vertexData = geometries.vertexData;
  19792. if (vertexData) {
  19793. for (index = 0; index < vertexData.length; index++) {
  19794. var parsedVertexData = vertexData[index];
  19795. parseVertexData(parsedVertexData, scene, rootUrl);
  19796. }
  19797. }
  19798. }
  19799. for (index = 0; index < parsedData.meshes.length; index++) {
  19800. var parsedMesh = parsedData.meshes[index];
  19801. parseMesh(parsedMesh, scene, rootUrl);
  19802. }
  19803. for (index = 0; index < parsedData.cameras.length; index++) {
  19804. var parsedCamera = parsedData.cameras[index];
  19805. parseCamera(parsedCamera, scene);
  19806. }
  19807. if (parsedData.activeCameraID) {
  19808. scene.setActiveCameraByID(parsedData.activeCameraID);
  19809. }
  19810. for (index = 0; index < scene.cameras.length; index++) {
  19811. var camera = scene.cameras[index];
  19812. if (camera._waitingParentId) {
  19813. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  19814. camera._waitingParentId = undefined;
  19815. }
  19816. }
  19817. for (index = 0; index < scene.lights.length; index++) {
  19818. var light = scene.lights[index];
  19819. if (light._waitingParentId) {
  19820. light.parent = scene.getLastEntryByID(light._waitingParentId);
  19821. light._waitingParentId = undefined;
  19822. }
  19823. }
  19824. // Sounds
  19825. if (parsedData.sounds) {
  19826. for (index = 0; index < parsedData.sounds.length; index++) {
  19827. var parsedSound = parsedData.sounds[index];
  19828. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  19829. parseSound(parsedSound, scene, rootUrl);
  19830. }
  19831. else {
  19832. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  19833. }
  19834. }
  19835. }
  19836. for (index = 0; index < scene.meshes.length; index++) {
  19837. var mesh = scene.meshes[index];
  19838. if (mesh._waitingParentId) {
  19839. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  19840. mesh._waitingParentId = undefined;
  19841. }
  19842. if (mesh._waitingActions) {
  19843. parseActions(mesh._waitingActions, mesh, scene);
  19844. mesh._waitingActions = undefined;
  19845. }
  19846. }
  19847. // Particles Systems
  19848. if (parsedData.particleSystems) {
  19849. for (index = 0; index < parsedData.particleSystems.length; index++) {
  19850. var parsedParticleSystem = parsedData.particleSystems[index];
  19851. parseParticleSystem(parsedParticleSystem, scene, rootUrl);
  19852. }
  19853. }
  19854. // Lens flares
  19855. if (parsedData.lensFlareSystems) {
  19856. for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
  19857. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  19858. parseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
  19859. }
  19860. }
  19861. // Shadows
  19862. if (parsedData.shadowGenerators) {
  19863. for (index = 0; index < parsedData.shadowGenerators.length; index++) {
  19864. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  19865. parseShadowGenerator(parsedShadowGenerator, scene);
  19866. }
  19867. }
  19868. // Actions (scene)
  19869. if (parsedData.actions) {
  19870. parseActions(parsedData.actions, null, scene);
  19871. }
  19872. // Finish
  19873. return true;
  19874. }
  19875. });
  19876. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  19877. })(BABYLON || (BABYLON = {}));
  19878. //# sourceMappingURL=babylon.babylonFileLoader.js.mapvar BABYLON;
  19879. (function (BABYLON) {
  19880. // Unique ID when we import meshes from Babylon to CSG
  19881. var currentCSGMeshId = 0;
  19882. // # class Vertex
  19883. // Represents a vertex of a polygon. Use your own vertex class instead of this
  19884. // one to provide additional features like texture coordinates and vertex
  19885. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  19886. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  19887. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  19888. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  19889. // is not used anywhere else.
  19890. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  19891. var Vertex = (function () {
  19892. function Vertex(pos, normal, uv) {
  19893. this.pos = pos;
  19894. this.normal = normal;
  19895. this.uv = uv;
  19896. }
  19897. Vertex.prototype.clone = function () {
  19898. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  19899. };
  19900. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  19901. // orientation of a polygon is flipped.
  19902. Vertex.prototype.flip = function () {
  19903. this.normal = this.normal.scale(-1);
  19904. };
  19905. // Create a new vertex between this vertex and `other` by linearly
  19906. // interpolating all properties using a parameter of `t`. Subclasses should
  19907. // override this to interpolate additional properties.
  19908. Vertex.prototype.interpolate = function (other, t) {
  19909. 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));
  19910. };
  19911. return Vertex;
  19912. })();
  19913. // # class Plane
  19914. // Represents a plane in 3D space.
  19915. var Plane = (function () {
  19916. function Plane(normal, w) {
  19917. this.normal = normal;
  19918. this.w = w;
  19919. }
  19920. Plane.FromPoints = function (a, b, c) {
  19921. var v0 = c.subtract(a);
  19922. var v1 = b.subtract(a);
  19923. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  19924. return null;
  19925. }
  19926. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  19927. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  19928. };
  19929. Plane.prototype.clone = function () {
  19930. return new Plane(this.normal.clone(), this.w);
  19931. };
  19932. Plane.prototype.flip = function () {
  19933. this.normal.scaleInPlace(-1);
  19934. this.w = -this.w;
  19935. };
  19936. // Split `polygon` by this plane if needed, then put the polygon or polygon
  19937. // fragments in the appropriate lists. Coplanar polygons go into either
  19938. // `coplanarFront` or `coplanarBack` depending on their orientation with
  19939. // respect to this plane. Polygons in front or in back of this plane go into
  19940. // either `front` or `back`.
  19941. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  19942. var COPLANAR = 0;
  19943. var FRONT = 1;
  19944. var BACK = 2;
  19945. var SPANNING = 3;
  19946. // Classify each point as well as the entire polygon into one of the above
  19947. // four classes.
  19948. var polygonType = 0;
  19949. var types = [];
  19950. for (var i = 0; i < polygon.vertices.length; i++) {
  19951. var t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  19952. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  19953. polygonType |= type;
  19954. types.push(type);
  19955. }
  19956. switch (polygonType) {
  19957. case COPLANAR:
  19958. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  19959. break;
  19960. case FRONT:
  19961. front.push(polygon);
  19962. break;
  19963. case BACK:
  19964. back.push(polygon);
  19965. break;
  19966. case SPANNING:
  19967. var f = [], b = [];
  19968. for (i = 0; i < polygon.vertices.length; i++) {
  19969. var j = (i + 1) % polygon.vertices.length;
  19970. var ti = types[i], tj = types[j];
  19971. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  19972. if (ti != BACK)
  19973. f.push(vi);
  19974. if (ti != FRONT)
  19975. b.push(ti != BACK ? vi.clone() : vi);
  19976. if ((ti | tj) == SPANNING) {
  19977. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  19978. var v = vi.interpolate(vj, t);
  19979. f.push(v);
  19980. b.push(v.clone());
  19981. }
  19982. }
  19983. if (f.length >= 3) {
  19984. var poly = new Polygon(f, polygon.shared);
  19985. if (poly.plane)
  19986. front.push(poly);
  19987. }
  19988. if (b.length >= 3) {
  19989. poly = new Polygon(b, polygon.shared);
  19990. if (poly.plane)
  19991. back.push(poly);
  19992. }
  19993. break;
  19994. }
  19995. };
  19996. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  19997. // point is on the plane.
  19998. Plane.EPSILON = 1e-5;
  19999. return Plane;
  20000. })();
  20001. // # class Polygon
  20002. // Represents a convex polygon. The vertices used to initialize a polygon must
  20003. // be coplanar and form a convex loop.
  20004. //
  20005. // Each convex polygon has a `shared` property, which is shared between all
  20006. // polygons that are clones of each other or were split from the same polygon.
  20007. // This can be used to define per-polygon properties (such as surface color).
  20008. var Polygon = (function () {
  20009. function Polygon(vertices, shared) {
  20010. this.vertices = vertices;
  20011. this.shared = shared;
  20012. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  20013. }
  20014. Polygon.prototype.clone = function () {
  20015. var vertices = this.vertices.map(function (v) { return v.clone(); });
  20016. return new Polygon(vertices, this.shared);
  20017. };
  20018. Polygon.prototype.flip = function () {
  20019. this.vertices.reverse().map(function (v) {
  20020. v.flip();
  20021. });
  20022. this.plane.flip();
  20023. };
  20024. return Polygon;
  20025. })();
  20026. // # class Node
  20027. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  20028. // by picking a polygon to split along. That polygon (and all other coplanar
  20029. // polygons) are added directly to that node and the other polygons are added to
  20030. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  20031. // no distinction between internal and leaf nodes.
  20032. var Node = (function () {
  20033. function Node(polygons) {
  20034. this.plane = null;
  20035. this.front = null;
  20036. this.back = null;
  20037. this.polygons = [];
  20038. if (polygons) {
  20039. this.build(polygons);
  20040. }
  20041. }
  20042. Node.prototype.clone = function () {
  20043. var node = new Node();
  20044. node.plane = this.plane && this.plane.clone();
  20045. node.front = this.front && this.front.clone();
  20046. node.back = this.back && this.back.clone();
  20047. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  20048. return node;
  20049. };
  20050. // Convert solid space to empty space and empty space to solid space.
  20051. Node.prototype.invert = function () {
  20052. for (var i = 0; i < this.polygons.length; i++) {
  20053. this.polygons[i].flip();
  20054. }
  20055. if (this.plane) {
  20056. this.plane.flip();
  20057. }
  20058. if (this.front) {
  20059. this.front.invert();
  20060. }
  20061. if (this.back) {
  20062. this.back.invert();
  20063. }
  20064. var temp = this.front;
  20065. this.front = this.back;
  20066. this.back = temp;
  20067. };
  20068. // Recursively remove all polygons in `polygons` that are inside this BSP
  20069. // tree.
  20070. Node.prototype.clipPolygons = function (polygons) {
  20071. if (!this.plane)
  20072. return polygons.slice();
  20073. var front = [], back = [];
  20074. for (var i = 0; i < polygons.length; i++) {
  20075. this.plane.splitPolygon(polygons[i], front, back, front, back);
  20076. }
  20077. if (this.front) {
  20078. front = this.front.clipPolygons(front);
  20079. }
  20080. if (this.back) {
  20081. back = this.back.clipPolygons(back);
  20082. }
  20083. else {
  20084. back = [];
  20085. }
  20086. return front.concat(back);
  20087. };
  20088. // Remove all polygons in this BSP tree that are inside the other BSP tree
  20089. // `bsp`.
  20090. Node.prototype.clipTo = function (bsp) {
  20091. this.polygons = bsp.clipPolygons(this.polygons);
  20092. if (this.front)
  20093. this.front.clipTo(bsp);
  20094. if (this.back)
  20095. this.back.clipTo(bsp);
  20096. };
  20097. // Return a list of all polygons in this BSP tree.
  20098. Node.prototype.allPolygons = function () {
  20099. var polygons = this.polygons.slice();
  20100. if (this.front)
  20101. polygons = polygons.concat(this.front.allPolygons());
  20102. if (this.back)
  20103. polygons = polygons.concat(this.back.allPolygons());
  20104. return polygons;
  20105. };
  20106. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  20107. // new polygons are filtered down to the bottom of the tree and become new
  20108. // nodes there. Each set of polygons is partitioned using the first polygon
  20109. // (no heuristic is used to pick a good split).
  20110. Node.prototype.build = function (polygons) {
  20111. if (!polygons.length)
  20112. return;
  20113. if (!this.plane)
  20114. this.plane = polygons[0].plane.clone();
  20115. var front = [], back = [];
  20116. for (var i = 0; i < polygons.length; i++) {
  20117. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  20118. }
  20119. if (front.length) {
  20120. if (!this.front)
  20121. this.front = new Node();
  20122. this.front.build(front);
  20123. }
  20124. if (back.length) {
  20125. if (!this.back)
  20126. this.back = new Node();
  20127. this.back.build(back);
  20128. }
  20129. };
  20130. return Node;
  20131. })();
  20132. var CSG = (function () {
  20133. function CSG() {
  20134. this.polygons = new Array();
  20135. }
  20136. // Convert BABYLON.Mesh to BABYLON.CSG
  20137. CSG.FromMesh = function (mesh) {
  20138. var vertex, normal, uv, position, polygon, polygons = [], vertices;
  20139. if (mesh instanceof BABYLON.Mesh) {
  20140. mesh.computeWorldMatrix(true);
  20141. var matrix = mesh.getWorldMatrix();
  20142. var meshPosition = mesh.position.clone();
  20143. var meshRotation = mesh.rotation.clone();
  20144. var meshScaling = mesh.scaling.clone();
  20145. }
  20146. else {
  20147. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  20148. }
  20149. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  20150. var subMeshes = mesh.subMeshes;
  20151. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  20152. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  20153. vertices = [];
  20154. for (var j = 0; j < 3; j++) {
  20155. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  20156. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  20157. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  20158. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  20159. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  20160. vertex = new Vertex(position, normal, uv);
  20161. vertices.push(vertex);
  20162. }
  20163. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  20164. // To handle the case of degenerated triangle
  20165. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  20166. if (polygon.plane)
  20167. polygons.push(polygon);
  20168. }
  20169. }
  20170. var csg = CSG.FromPolygons(polygons);
  20171. csg.matrix = matrix;
  20172. csg.position = meshPosition;
  20173. csg.rotation = meshRotation;
  20174. csg.scaling = meshScaling;
  20175. currentCSGMeshId++;
  20176. return csg;
  20177. };
  20178. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  20179. CSG.FromPolygons = function (polygons) {
  20180. var csg = new BABYLON.CSG();
  20181. csg.polygons = polygons;
  20182. return csg;
  20183. };
  20184. CSG.prototype.clone = function () {
  20185. var csg = new BABYLON.CSG();
  20186. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  20187. csg.copyTransformAttributes(this);
  20188. return csg;
  20189. };
  20190. CSG.prototype.toPolygons = function () {
  20191. return this.polygons;
  20192. };
  20193. CSG.prototype.union = function (csg) {
  20194. var a = new Node(this.clone().polygons);
  20195. var b = new Node(csg.clone().polygons);
  20196. a.clipTo(b);
  20197. b.clipTo(a);
  20198. b.invert();
  20199. b.clipTo(a);
  20200. b.invert();
  20201. a.build(b.allPolygons());
  20202. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  20203. };
  20204. CSG.prototype.unionInPlace = function (csg) {
  20205. var a = new Node(this.polygons);
  20206. var b = new Node(csg.polygons);
  20207. a.clipTo(b);
  20208. b.clipTo(a);
  20209. b.invert();
  20210. b.clipTo(a);
  20211. b.invert();
  20212. a.build(b.allPolygons());
  20213. this.polygons = a.allPolygons();
  20214. };
  20215. CSG.prototype.subtract = function (csg) {
  20216. var a = new Node(this.clone().polygons);
  20217. var b = new Node(csg.clone().polygons);
  20218. a.invert();
  20219. a.clipTo(b);
  20220. b.clipTo(a);
  20221. b.invert();
  20222. b.clipTo(a);
  20223. b.invert();
  20224. a.build(b.allPolygons());
  20225. a.invert();
  20226. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  20227. };
  20228. CSG.prototype.subtractInPlace = function (csg) {
  20229. var a = new Node(this.polygons);
  20230. var b = new Node(csg.polygons);
  20231. a.invert();
  20232. a.clipTo(b);
  20233. b.clipTo(a);
  20234. b.invert();
  20235. b.clipTo(a);
  20236. b.invert();
  20237. a.build(b.allPolygons());
  20238. a.invert();
  20239. this.polygons = a.allPolygons();
  20240. };
  20241. CSG.prototype.intersect = function (csg) {
  20242. var a = new Node(this.clone().polygons);
  20243. var b = new Node(csg.clone().polygons);
  20244. a.invert();
  20245. b.clipTo(a);
  20246. b.invert();
  20247. a.clipTo(b);
  20248. b.clipTo(a);
  20249. a.build(b.allPolygons());
  20250. a.invert();
  20251. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  20252. };
  20253. CSG.prototype.intersectInPlace = function (csg) {
  20254. var a = new Node(this.polygons);
  20255. var b = new Node(csg.polygons);
  20256. a.invert();
  20257. b.clipTo(a);
  20258. b.invert();
  20259. a.clipTo(b);
  20260. b.clipTo(a);
  20261. a.build(b.allPolygons());
  20262. a.invert();
  20263. this.polygons = a.allPolygons();
  20264. };
  20265. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  20266. // not modified.
  20267. CSG.prototype.inverse = function () {
  20268. var csg = this.clone();
  20269. csg.inverseInPlace();
  20270. return csg;
  20271. };
  20272. CSG.prototype.inverseInPlace = function () {
  20273. this.polygons.map(function (p) {
  20274. p.flip();
  20275. });
  20276. };
  20277. // This is used to keep meshes transformations so they can be restored
  20278. // when we build back a Babylon Mesh
  20279. // NB : All CSG operations are performed in world coordinates
  20280. CSG.prototype.copyTransformAttributes = function (csg) {
  20281. this.matrix = csg.matrix;
  20282. this.position = csg.position;
  20283. this.rotation = csg.rotation;
  20284. this.scaling = csg.scaling;
  20285. return this;
  20286. };
  20287. // Build Raw mesh from CSG
  20288. // Coordinates here are in world space
  20289. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  20290. var matrix = this.matrix.clone();
  20291. matrix.invert();
  20292. 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;
  20293. if (keepSubMeshes) {
  20294. // Sort Polygons, since subMeshes are indices range
  20295. polygons.sort(function (a, b) {
  20296. if (a.shared.meshId === b.shared.meshId) {
  20297. return a.shared.subMeshId - b.shared.subMeshId;
  20298. }
  20299. else {
  20300. return a.shared.meshId - b.shared.meshId;
  20301. }
  20302. });
  20303. }
  20304. for (var i = 0, il = polygons.length; i < il; i++) {
  20305. polygon = polygons[i];
  20306. // Building SubMeshes
  20307. if (!subMesh_dict[polygon.shared.meshId]) {
  20308. subMesh_dict[polygon.shared.meshId] = {};
  20309. }
  20310. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  20311. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  20312. indexStart: +Infinity,
  20313. indexEnd: -Infinity,
  20314. materialIndex: polygon.shared.materialIndex
  20315. };
  20316. }
  20317. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  20318. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  20319. polygonIndices[0] = 0;
  20320. polygonIndices[1] = j - 1;
  20321. polygonIndices[2] = j;
  20322. for (var k = 0; k < 3; k++) {
  20323. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  20324. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  20325. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  20326. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  20327. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  20328. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  20329. // Check if 2 points can be merged
  20330. 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)) {
  20331. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  20332. uvs.push(uv.x, uv.y);
  20333. normals.push(normal.x, normal.y, normal.z);
  20334. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  20335. }
  20336. indices.push(vertex_idx);
  20337. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  20338. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  20339. currentIndex++;
  20340. }
  20341. }
  20342. }
  20343. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  20344. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  20345. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  20346. mesh.setIndices(indices);
  20347. if (keepSubMeshes) {
  20348. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  20349. var materialIndexOffset = 0, materialMaxIndex;
  20350. mesh.subMeshes.length = 0;
  20351. for (var m in subMesh_dict) {
  20352. materialMaxIndex = -1;
  20353. for (var sm in subMesh_dict[m]) {
  20354. subMesh_obj = subMesh_dict[m][sm];
  20355. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  20356. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  20357. }
  20358. materialIndexOffset += ++materialMaxIndex;
  20359. }
  20360. }
  20361. return mesh;
  20362. };
  20363. // Build Mesh from CSG taking material and transforms into account
  20364. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  20365. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  20366. mesh.material = material;
  20367. mesh.position.copyFrom(this.position);
  20368. mesh.rotation.copyFrom(this.rotation);
  20369. mesh.scaling.copyFrom(this.scaling);
  20370. mesh.computeWorldMatrix(true);
  20371. return mesh;
  20372. };
  20373. return CSG;
  20374. })();
  20375. BABYLON.CSG = CSG;
  20376. })(BABYLON || (BABYLON = {}));
  20377. //# sourceMappingURL=babylon.csg.js.map
  20378. var BABYLON;
  20379. (function (BABYLON) {
  20380. var OculusDistortionCorrectionPostProcess = (function (_super) {
  20381. __extends(OculusDistortionCorrectionPostProcess, _super);
  20382. //ANY
  20383. function OculusDistortionCorrectionPostProcess(name, camera, isRightEye, cameraSettings) {
  20384. var _this = this;
  20385. _super.call(this, name, "oculusDistortionCorrection", [
  20386. 'LensCenter',
  20387. 'Scale',
  20388. 'ScaleIn',
  20389. 'HmdWarpParam'
  20390. ], null, cameraSettings.PostProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  20391. this._isRightEye = isRightEye;
  20392. this._distortionFactors = cameraSettings.DistortionK;
  20393. this._postProcessScaleFactor = cameraSettings.PostProcessScaleFactor;
  20394. this._lensCenterOffset = cameraSettings.LensCenterOffset;
  20395. this.onSizeChanged = function () {
  20396. _this.aspectRatio = _this.width * .5 / _this.height;
  20397. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  20398. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  20399. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  20400. };
  20401. this.onApply = function (effect) {
  20402. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  20403. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  20404. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  20405. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  20406. };
  20407. }
  20408. return OculusDistortionCorrectionPostProcess;
  20409. })(BABYLON.PostProcess);
  20410. BABYLON.OculusDistortionCorrectionPostProcess = OculusDistortionCorrectionPostProcess;
  20411. })(BABYLON || (BABYLON = {}));
  20412. //# sourceMappingURL=babylon.oculusDistortionCorrectionPostProcess.js.map// Mainly based on these 2 articles :
  20413. // 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
  20414. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  20415. var BABYLON;
  20416. (function (BABYLON) {
  20417. (function (JoystickAxis) {
  20418. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  20419. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  20420. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  20421. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  20422. var JoystickAxis = BABYLON.JoystickAxis;
  20423. var VirtualJoystick = (function () {
  20424. function VirtualJoystick(leftJoystick) {
  20425. var _this = this;
  20426. if (leftJoystick) {
  20427. this._leftJoystick = true;
  20428. }
  20429. else {
  20430. this._leftJoystick = false;
  20431. }
  20432. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  20433. VirtualJoystick._globalJoystickIndex++;
  20434. // By default left & right arrow keys are moving the X
  20435. // and up & down keys are moving the Y
  20436. this._axisTargetedByLeftAndRight = 0 /* X */;
  20437. this._axisTargetedByUpAndDown = 1 /* Y */;
  20438. this.reverseLeftRight = false;
  20439. this.reverseUpDown = false;
  20440. // collections of pointers
  20441. this._touches = new BABYLON.VirtualJoystick.Collection();
  20442. this.deltaPosition = BABYLON.Vector3.Zero();
  20443. this._joystickSensibility = 25;
  20444. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  20445. this._rotationSpeed = 25;
  20446. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  20447. this._rotateOnAxisRelativeToMesh = false;
  20448. // injecting a canvas element on top of the canvas 3D game
  20449. if (!VirtualJoystick.vjCanvas) {
  20450. window.addEventListener("resize", function () {
  20451. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  20452. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  20453. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  20454. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  20455. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  20456. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  20457. }, false);
  20458. VirtualJoystick.vjCanvas = document.createElement("canvas");
  20459. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  20460. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  20461. VirtualJoystick.vjCanvas.width = window.innerWidth;
  20462. VirtualJoystick.vjCanvas.height = window.innerHeight;
  20463. VirtualJoystick.vjCanvas.style.width = "100%";
  20464. VirtualJoystick.vjCanvas.style.height = "100%";
  20465. VirtualJoystick.vjCanvas.style.position = "absolute";
  20466. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  20467. VirtualJoystick.vjCanvas.style.top = "0px";
  20468. VirtualJoystick.vjCanvas.style.left = "0px";
  20469. VirtualJoystick.vjCanvas.style.zIndex = "5";
  20470. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  20471. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  20472. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  20473. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  20474. document.body.appendChild(VirtualJoystick.vjCanvas);
  20475. }
  20476. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  20477. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  20478. this.pressed = false;
  20479. // default joystick color
  20480. this._joystickColor = "cyan";
  20481. this._joystickPointerID = -1;
  20482. // current joystick position
  20483. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  20484. // origin joystick position
  20485. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  20486. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  20487. VirtualJoystick.vjCanvas.addEventListener('pointerdown', function (evt) {
  20488. _this._onPointerDown(evt);
  20489. }, false);
  20490. VirtualJoystick.vjCanvas.addEventListener('pointermove', function (evt) {
  20491. _this._onPointerMove(evt);
  20492. }, false);
  20493. VirtualJoystick.vjCanvas.addEventListener('pointerup', function (evt) {
  20494. _this._onPointerUp(evt);
  20495. }, false);
  20496. VirtualJoystick.vjCanvas.addEventListener('pointerout', function (evt) {
  20497. _this._onPointerUp(evt);
  20498. }, false);
  20499. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  20500. evt.preventDefault(); // Disables system menu
  20501. }, false);
  20502. requestAnimationFrame(function () {
  20503. _this._drawVirtualJoystick();
  20504. });
  20505. }
  20506. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  20507. this._joystickSensibility = newJoystickSensibility;
  20508. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  20509. };
  20510. VirtualJoystick.prototype._onPointerDown = function (e) {
  20511. var positionOnScreenCondition;
  20512. e.preventDefault();
  20513. if (this._leftJoystick === true) {
  20514. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  20515. }
  20516. else {
  20517. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  20518. }
  20519. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  20520. // First contact will be dedicated to the virtual joystick
  20521. this._joystickPointerID = e.pointerId;
  20522. this._joystickPointerStartPos.x = e.clientX;
  20523. this._joystickPointerStartPos.y = e.clientY;
  20524. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  20525. this._deltaJoystickVector.x = 0;
  20526. this._deltaJoystickVector.y = 0;
  20527. this.pressed = true;
  20528. this._touches.add(e.pointerId.toString(), e);
  20529. }
  20530. else {
  20531. // You can only trigger the action buttons with a joystick declared
  20532. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  20533. this._action();
  20534. this._touches.add(e.pointerId.toString(), e);
  20535. }
  20536. }
  20537. };
  20538. VirtualJoystick.prototype._onPointerMove = function (e) {
  20539. // If the current pointer is the one associated to the joystick (first touch contact)
  20540. if (this._joystickPointerID == e.pointerId) {
  20541. this._joystickPointerPos.x = e.clientX;
  20542. this._joystickPointerPos.y = e.clientY;
  20543. this._deltaJoystickVector = this._joystickPointerPos.clone();
  20544. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  20545. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  20546. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  20547. switch (this._axisTargetedByLeftAndRight) {
  20548. case 0 /* X */:
  20549. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  20550. break;
  20551. case 1 /* Y */:
  20552. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  20553. break;
  20554. case 2 /* Z */:
  20555. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  20556. break;
  20557. }
  20558. var directionUpDown = this.reverseUpDown ? 1 : -1;
  20559. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  20560. switch (this._axisTargetedByUpAndDown) {
  20561. case 0 /* X */:
  20562. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  20563. break;
  20564. case 1 /* Y */:
  20565. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  20566. break;
  20567. case 2 /* Z */:
  20568. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  20569. break;
  20570. }
  20571. }
  20572. else {
  20573. if (this._touches.item(e.pointerId.toString())) {
  20574. this._touches.item(e.pointerId.toString()).x = e.clientX;
  20575. this._touches.item(e.pointerId.toString()).y = e.clientY;
  20576. }
  20577. }
  20578. };
  20579. VirtualJoystick.prototype._onPointerUp = function (e) {
  20580. this._clearCanvas();
  20581. if (this._joystickPointerID == e.pointerId) {
  20582. this._joystickPointerID = -1;
  20583. this.pressed = false;
  20584. }
  20585. this._deltaJoystickVector.x = 0;
  20586. this._deltaJoystickVector.y = 0;
  20587. this._touches.remove(e.pointerId.toString());
  20588. };
  20589. /**
  20590. * Change the color of the virtual joystick
  20591. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  20592. */
  20593. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  20594. this._joystickColor = newColor;
  20595. };
  20596. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  20597. this._action = action;
  20598. };
  20599. // Define which axis you'd like to control for left & right
  20600. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  20601. switch (axis) {
  20602. case 0 /* X */:
  20603. case 1 /* Y */:
  20604. case 2 /* Z */:
  20605. this._axisTargetedByLeftAndRight = axis;
  20606. break;
  20607. default:
  20608. this._axisTargetedByLeftAndRight = 0 /* X */;
  20609. break;
  20610. }
  20611. };
  20612. // Define which axis you'd like to control for up & down
  20613. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  20614. switch (axis) {
  20615. case 0 /* X */:
  20616. case 1 /* Y */:
  20617. case 2 /* Z */:
  20618. this._axisTargetedByUpAndDown = axis;
  20619. break;
  20620. default:
  20621. this._axisTargetedByUpAndDown = 1 /* Y */;
  20622. break;
  20623. }
  20624. };
  20625. VirtualJoystick.prototype._clearCanvas = function () {
  20626. if (this._leftJoystick) {
  20627. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  20628. }
  20629. else {
  20630. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  20631. }
  20632. };
  20633. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  20634. var _this = this;
  20635. if (this.pressed) {
  20636. this._clearCanvas();
  20637. this._touches.forEach(function (touch) {
  20638. if (touch.pointerId === _this._joystickPointerID) {
  20639. VirtualJoystick.vjCanvasContext.beginPath();
  20640. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  20641. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  20642. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  20643. VirtualJoystick.vjCanvasContext.stroke();
  20644. VirtualJoystick.vjCanvasContext.beginPath();
  20645. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  20646. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  20647. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  20648. VirtualJoystick.vjCanvasContext.stroke();
  20649. VirtualJoystick.vjCanvasContext.beginPath();
  20650. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  20651. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  20652. VirtualJoystick.vjCanvasContext.stroke();
  20653. }
  20654. else {
  20655. VirtualJoystick.vjCanvasContext.beginPath();
  20656. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  20657. VirtualJoystick.vjCanvasContext.beginPath();
  20658. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  20659. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  20660. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  20661. VirtualJoystick.vjCanvasContext.stroke();
  20662. }
  20663. ;
  20664. });
  20665. }
  20666. requestAnimationFrame(function () {
  20667. _this._drawVirtualJoystick();
  20668. });
  20669. };
  20670. VirtualJoystick.prototype.releaseCanvas = function () {
  20671. if (VirtualJoystick.vjCanvas) {
  20672. document.body.removeChild(VirtualJoystick.vjCanvas);
  20673. VirtualJoystick.vjCanvas = null;
  20674. }
  20675. };
  20676. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  20677. VirtualJoystick._globalJoystickIndex = 0;
  20678. return VirtualJoystick;
  20679. })();
  20680. BABYLON.VirtualJoystick = VirtualJoystick;
  20681. })(BABYLON || (BABYLON = {}));
  20682. var BABYLON;
  20683. (function (BABYLON) {
  20684. var VirtualJoystick;
  20685. (function (VirtualJoystick) {
  20686. var Collection = (function () {
  20687. function Collection() {
  20688. this._count = 0;
  20689. this._collection = new Array();
  20690. }
  20691. Collection.prototype.Count = function () {
  20692. return this._count;
  20693. };
  20694. Collection.prototype.add = function (key, item) {
  20695. if (this._collection[key] != undefined) {
  20696. return undefined;
  20697. }
  20698. this._collection[key] = item;
  20699. return ++this._count;
  20700. };
  20701. Collection.prototype.remove = function (key) {
  20702. if (this._collection[key] == undefined) {
  20703. return undefined;
  20704. }
  20705. delete this._collection[key];
  20706. return --this._count;
  20707. };
  20708. Collection.prototype.item = function (key) {
  20709. return this._collection[key];
  20710. };
  20711. Collection.prototype.forEach = function (block) {
  20712. var key;
  20713. for (key in this._collection) {
  20714. if (this._collection.hasOwnProperty(key)) {
  20715. block(this._collection[key]);
  20716. }
  20717. }
  20718. };
  20719. return Collection;
  20720. })();
  20721. VirtualJoystick.Collection = Collection;
  20722. })(VirtualJoystick = BABYLON.VirtualJoystick || (BABYLON.VirtualJoystick = {}));
  20723. })(BABYLON || (BABYLON = {}));
  20724. //# sourceMappingURL=babylon.virtualJoystick.js.map
  20725. var BABYLON;
  20726. (function (BABYLON) {
  20727. var OculusRiftDevKit2013_Metric = {
  20728. HResolution: 1280,
  20729. VResolution: 800,
  20730. HScreenSize: 0.149759993,
  20731. VScreenSize: 0.0935999975,
  20732. VScreenCenter: 0.0467999987,
  20733. EyeToScreenDistance: 0.0410000011,
  20734. LensSeparationDistance: 0.0635000020,
  20735. InterpupillaryDistance: 0.0640000030,
  20736. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  20737. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  20738. PostProcessScaleFactor: 1.714605507808412,
  20739. LensCenterOffset: 0.151976421
  20740. };
  20741. var _OculusInnerCamera = (function (_super) {
  20742. __extends(_OculusInnerCamera, _super);
  20743. function _OculusInnerCamera(name, position, scene, isLeftEye) {
  20744. _super.call(this, name, position, scene);
  20745. this._workMatrix = new BABYLON.Matrix();
  20746. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  20747. // Constants
  20748. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  20749. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  20750. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  20751. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  20752. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  20753. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  20754. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  20755. // Postprocess
  20756. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  20757. }
  20758. _OculusInnerCamera.prototype.getProjectionMatrix = function () {
  20759. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  20760. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  20761. return this._projectionMatrix;
  20762. };
  20763. _OculusInnerCamera.prototype._getViewMatrix = function () {
  20764. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  20765. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  20766. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  20767. // Computing target and final matrix
  20768. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  20769. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  20770. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  20771. return this._viewMatrix;
  20772. };
  20773. return _OculusInnerCamera;
  20774. })(BABYLON.FreeCamera);
  20775. var OculusCamera = (function (_super) {
  20776. __extends(OculusCamera, _super);
  20777. function OculusCamera(name, position, scene) {
  20778. _super.call(this, name, position, scene);
  20779. this._leftCamera = new _OculusInnerCamera(name + "_left", position.clone(), scene, true);
  20780. this._rightCamera = new _OculusInnerCamera(name + "_right", position.clone(), scene, false);
  20781. this.subCameras.push(this._leftCamera);
  20782. this.subCameras.push(this._rightCamera);
  20783. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  20784. }
  20785. OculusCamera.prototype._update = function () {
  20786. this._leftCamera.position.copyFrom(this.position);
  20787. this._rightCamera.position.copyFrom(this.position);
  20788. this._updateCamera(this._leftCamera);
  20789. this._updateCamera(this._rightCamera);
  20790. _super.prototype._update.call(this);
  20791. };
  20792. OculusCamera.prototype._updateCamera = function (camera) {
  20793. camera.minZ = this.minZ;
  20794. camera.maxZ = this.maxZ;
  20795. camera.rotation.x = this.rotation.x;
  20796. camera.rotation.y = this.rotation.y;
  20797. camera.rotation.z = this.rotation.z;
  20798. };
  20799. // Oculus events
  20800. OculusCamera.prototype._onOrientationEvent = function (evt) {
  20801. var yaw = evt.alpha / 180 * Math.PI;
  20802. var pitch = evt.beta / 180 * Math.PI;
  20803. var roll = evt.gamma / 180 * Math.PI;
  20804. if (!this._offsetOrientation) {
  20805. this._offsetOrientation = {
  20806. yaw: yaw,
  20807. pitch: pitch,
  20808. roll: roll
  20809. };
  20810. return;
  20811. }
  20812. else {
  20813. this.rotation.y += yaw - this._offsetOrientation.yaw;
  20814. this.rotation.x += pitch - this._offsetOrientation.pitch;
  20815. this.rotation.z += this._offsetOrientation.roll - roll;
  20816. this._offsetOrientation.yaw = yaw;
  20817. this._offsetOrientation.pitch = pitch;
  20818. this._offsetOrientation.roll = roll;
  20819. }
  20820. };
  20821. OculusCamera.prototype.attachControl = function (element, noPreventDefault) {
  20822. _super.prototype.attachControl.call(this, element, noPreventDefault);
  20823. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  20824. };
  20825. OculusCamera.prototype.detachControl = function (element) {
  20826. _super.prototype.detachControl.call(this, element);
  20827. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  20828. };
  20829. return OculusCamera;
  20830. })(BABYLON.FreeCamera);
  20831. BABYLON.OculusCamera = OculusCamera;
  20832. })(BABYLON || (BABYLON = {}));
  20833. //# sourceMappingURL=babylon.oculusCamera.js.map
  20834. var BABYLON;
  20835. (function (BABYLON) {
  20836. var OculusRiftDevKit2013_Metric = {
  20837. HResolution: 1280,
  20838. VResolution: 800,
  20839. HScreenSize: 0.149759993,
  20840. VScreenSize: 0.0935999975,
  20841. VScreenCenter: 0.0467999987,
  20842. EyeToScreenDistance: 0.0410000011,
  20843. LensSeparationDistance: 0.0635000020,
  20844. InterpupillaryDistance: 0.0640000030,
  20845. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  20846. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  20847. PostProcessScaleFactor: 1.714605507808412,
  20848. LensCenterOffset: 0.151976421
  20849. };
  20850. var _OculusInnerGamepadCamera = (function (_super) {
  20851. __extends(_OculusInnerGamepadCamera, _super);
  20852. function _OculusInnerGamepadCamera(name, position, scene, isLeftEye) {
  20853. _super.call(this, name, position, scene);
  20854. this._workMatrix = new BABYLON.Matrix();
  20855. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  20856. // Constants
  20857. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  20858. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  20859. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  20860. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  20861. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  20862. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  20863. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  20864. // Postprocess
  20865. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  20866. }
  20867. _OculusInnerGamepadCamera.prototype.getProjectionMatrix = function () {
  20868. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  20869. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  20870. return this._projectionMatrix;
  20871. };
  20872. _OculusInnerGamepadCamera.prototype._getViewMatrix = function () {
  20873. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  20874. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  20875. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  20876. // Computing target and final matrix
  20877. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  20878. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  20879. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  20880. return this._viewMatrix;
  20881. };
  20882. return _OculusInnerGamepadCamera;
  20883. })(BABYLON.FreeCamera);
  20884. var OculusGamepadCamera = (function (_super) {
  20885. __extends(OculusGamepadCamera, _super);
  20886. function OculusGamepadCamera(name, position, scene) {
  20887. var _this = this;
  20888. _super.call(this, name, position, scene);
  20889. this.angularSensibility = 200;
  20890. this.moveSensibility = 75;
  20891. this._leftCamera = new _OculusInnerGamepadCamera(name + "_left", position.clone(), scene, true);
  20892. this._rightCamera = new _OculusInnerGamepadCamera(name + "_right", position.clone(), scene, false);
  20893. this.subCameras.push(this._leftCamera);
  20894. this.subCameras.push(this._rightCamera);
  20895. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  20896. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  20897. _this._onNewGameConnected(gamepad);
  20898. });
  20899. }
  20900. OculusGamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  20901. // Only the first gamepad can control the camera
  20902. if (gamepad.index === 0) {
  20903. this._gamepad = gamepad;
  20904. }
  20905. };
  20906. OculusGamepadCamera.prototype._update = function () {
  20907. this._leftCamera.position.copyFrom(this.position);
  20908. this._rightCamera.position.copyFrom(this.position);
  20909. this._updateCamera(this._leftCamera);
  20910. this._updateCamera(this._rightCamera);
  20911. _super.prototype._update.call(this);
  20912. };
  20913. OculusGamepadCamera.prototype._checkInputs = function () {
  20914. if (!this._gamepad) {
  20915. return;
  20916. }
  20917. var LSValues = this._gamepad.leftStick;
  20918. var normalizedLX = LSValues.x / this.moveSensibility;
  20919. var normalizedLY = LSValues.y / this.moveSensibility;
  20920. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  20921. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  20922. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  20923. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x, 0, -LSValues.y), cameraTransform);
  20924. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  20925. };
  20926. OculusGamepadCamera.prototype._updateCamera = function (camera) {
  20927. camera.minZ = this.minZ;
  20928. camera.maxZ = this.maxZ;
  20929. camera.rotation.x = this.rotation.x;
  20930. camera.rotation.y = this.rotation.y;
  20931. camera.rotation.z = this.rotation.z;
  20932. };
  20933. // Oculus events
  20934. OculusGamepadCamera.prototype._onOrientationEvent = function (evt) {
  20935. var yaw = evt.alpha / 180 * Math.PI;
  20936. var pitch = evt.beta / 180 * Math.PI;
  20937. var roll = evt.gamma / 180 * Math.PI;
  20938. if (!this._offsetOrientation) {
  20939. this._offsetOrientation = {
  20940. yaw: yaw,
  20941. pitch: pitch,
  20942. roll: roll
  20943. };
  20944. return;
  20945. }
  20946. else {
  20947. this.rotation.y += yaw - this._offsetOrientation.yaw;
  20948. this.rotation.x += pitch - this._offsetOrientation.pitch;
  20949. this.rotation.z += this._offsetOrientation.roll - roll;
  20950. this._offsetOrientation.yaw = yaw;
  20951. this._offsetOrientation.pitch = pitch;
  20952. this._offsetOrientation.roll = roll;
  20953. }
  20954. };
  20955. OculusGamepadCamera.prototype.attachControl = function (element, noPreventDefault) {
  20956. _super.prototype.attachControl.call(this, element, noPreventDefault);
  20957. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  20958. };
  20959. OculusGamepadCamera.prototype.detachControl = function (element) {
  20960. _super.prototype.detachControl.call(this, element);
  20961. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  20962. };
  20963. OculusGamepadCamera.prototype.dispose = function () {
  20964. this._gamepads.dispose();
  20965. _super.prototype.dispose.call(this);
  20966. };
  20967. return OculusGamepadCamera;
  20968. })(BABYLON.FreeCamera);
  20969. BABYLON.OculusGamepadCamera = OculusGamepadCamera;
  20970. })(BABYLON || (BABYLON = {}));
  20971. //# sourceMappingURL=babylon.oculusGamepadCamera.js.map
  20972. var BABYLON;
  20973. (function (BABYLON) {
  20974. // We're mainly based on the logic defined into the FreeCamera code
  20975. var VirtualJoysticksCamera = (function (_super) {
  20976. __extends(VirtualJoysticksCamera, _super);
  20977. function VirtualJoysticksCamera(name, position, scene) {
  20978. _super.call(this, name, position, scene);
  20979. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  20980. this._leftjoystick.setAxisForUpDown(2 /* Z */);
  20981. this._leftjoystick.setAxisForLeftRight(0 /* X */);
  20982. this._leftjoystick.setJoystickSensibility(0.15);
  20983. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  20984. this._rightjoystick.setAxisForUpDown(0 /* X */);
  20985. this._rightjoystick.setAxisForLeftRight(1 /* Y */);
  20986. this._rightjoystick.reverseUpDown = true;
  20987. this._rightjoystick.setJoystickSensibility(0.05);
  20988. this._rightjoystick.setJoystickColor("yellow");
  20989. }
  20990. VirtualJoysticksCamera.prototype._checkInputs = function () {
  20991. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  20992. var deltaTransform = BABYLON.Vector3.TransformCoordinates(this._leftjoystick.deltaPosition, cameraTransform);
  20993. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  20994. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  20995. if (!this._leftjoystick.pressed) {
  20996. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  20997. }
  20998. if (!this._rightjoystick.pressed) {
  20999. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  21000. }
  21001. };
  21002. VirtualJoysticksCamera.prototype.dispose = function () {
  21003. this._leftjoystick.releaseCanvas();
  21004. _super.prototype.dispose.call(this);
  21005. };
  21006. return VirtualJoysticksCamera;
  21007. })(BABYLON.FreeCamera);
  21008. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  21009. })(BABYLON || (BABYLON = {}));
  21010. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  21011. var BABYLON;
  21012. (function (BABYLON) {
  21013. var ShaderMaterial = (function (_super) {
  21014. __extends(ShaderMaterial, _super);
  21015. function ShaderMaterial(name, scene, shaderPath, options) {
  21016. _super.call(this, name, scene);
  21017. this._textures = new Array();
  21018. this._floats = new Array();
  21019. this._floatsArrays = {};
  21020. this._colors3 = new Array();
  21021. this._colors4 = new Array();
  21022. this._vectors2 = new Array();
  21023. this._vectors3 = new Array();
  21024. this._matrices = new Array();
  21025. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  21026. this._shaderPath = shaderPath;
  21027. options.needAlphaBlending = options.needAlphaBlending || false;
  21028. options.needAlphaTesting = options.needAlphaTesting || false;
  21029. options.attributes = options.attributes || ["position", "normal", "uv"];
  21030. options.uniforms = options.uniforms || ["worldViewProjection"];
  21031. options.samplers = options.samplers || [];
  21032. this._options = options;
  21033. }
  21034. ShaderMaterial.prototype.needAlphaBlending = function () {
  21035. return this._options.needAlphaBlending;
  21036. };
  21037. ShaderMaterial.prototype.needAlphaTesting = function () {
  21038. return this._options.needAlphaTesting;
  21039. };
  21040. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  21041. if (this._options.uniforms.indexOf(uniformName) === -1) {
  21042. this._options.uniforms.push(uniformName);
  21043. }
  21044. };
  21045. ShaderMaterial.prototype.setTexture = function (name, texture) {
  21046. if (this._options.samplers.indexOf(name) === -1) {
  21047. this._options.samplers.push(name);
  21048. }
  21049. this._textures[name] = texture;
  21050. return this;
  21051. };
  21052. ShaderMaterial.prototype.setFloat = function (name, value) {
  21053. this._checkUniform(name);
  21054. this._floats[name] = value;
  21055. return this;
  21056. };
  21057. ShaderMaterial.prototype.setFloats = function (name, value) {
  21058. this._checkUniform(name);
  21059. this._floatsArrays[name] = value;
  21060. return this;
  21061. };
  21062. ShaderMaterial.prototype.setColor3 = function (name, value) {
  21063. this._checkUniform(name);
  21064. this._colors3[name] = value;
  21065. return this;
  21066. };
  21067. ShaderMaterial.prototype.setColor4 = function (name, value) {
  21068. this._checkUniform(name);
  21069. this._colors4[name] = value;
  21070. return this;
  21071. };
  21072. ShaderMaterial.prototype.setVector2 = function (name, value) {
  21073. this._checkUniform(name);
  21074. this._vectors2[name] = value;
  21075. return this;
  21076. };
  21077. ShaderMaterial.prototype.setVector3 = function (name, value) {
  21078. this._checkUniform(name);
  21079. this._vectors3[name] = value;
  21080. return this;
  21081. };
  21082. ShaderMaterial.prototype.setMatrix = function (name, value) {
  21083. this._checkUniform(name);
  21084. this._matrices[name] = value;
  21085. return this;
  21086. };
  21087. ShaderMaterial.prototype.isReady = function () {
  21088. var scene = this.getScene();
  21089. var engine = scene.getEngine();
  21090. if (!this.checkReadyOnEveryCall) {
  21091. if (this._renderId === scene.getRenderId()) {
  21092. return true;
  21093. }
  21094. }
  21095. var previousEffect = this._effect;
  21096. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, "", null, this.onCompiled, this.onError);
  21097. if (!this._effect.isReady()) {
  21098. return false;
  21099. }
  21100. if (previousEffect !== this._effect) {
  21101. scene.resetCachedMaterial();
  21102. }
  21103. this._renderId = scene.getRenderId();
  21104. return true;
  21105. };
  21106. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  21107. var scene = this.getScene();
  21108. if (this._options.uniforms.indexOf("world") !== -1) {
  21109. this._effect.setMatrix("world", world);
  21110. }
  21111. if (this._options.uniforms.indexOf("worldView") !== -1) {
  21112. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  21113. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  21114. }
  21115. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  21116. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  21117. }
  21118. };
  21119. ShaderMaterial.prototype.bind = function (world) {
  21120. // Std values
  21121. this.bindOnlyWorldMatrix(world);
  21122. if (this.getScene().getCachedMaterial() !== this) {
  21123. if (this._options.uniforms.indexOf("view") !== -1) {
  21124. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  21125. }
  21126. if (this._options.uniforms.indexOf("projection") !== -1) {
  21127. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  21128. }
  21129. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  21130. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  21131. }
  21132. for (var name in this._textures) {
  21133. this._effect.setTexture(name, this._textures[name]);
  21134. }
  21135. for (name in this._floats) {
  21136. this._effect.setFloat(name, this._floats[name]);
  21137. }
  21138. for (name in this._floatsArrays) {
  21139. this._effect.setArray(name, this._floatsArrays[name]);
  21140. }
  21141. for (name in this._colors3) {
  21142. this._effect.setColor3(name, this._colors3[name]);
  21143. }
  21144. for (name in this._colors4) {
  21145. var color = this._colors4[name];
  21146. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  21147. }
  21148. for (name in this._vectors2) {
  21149. this._effect.setVector2(name, this._vectors2[name]);
  21150. }
  21151. for (name in this._vectors3) {
  21152. this._effect.setVector3(name, this._vectors3[name]);
  21153. }
  21154. for (name in this._matrices) {
  21155. this._effect.setMatrix(name, this._matrices[name]);
  21156. }
  21157. }
  21158. _super.prototype.bind.call(this, world, null);
  21159. };
  21160. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  21161. for (var name in this._textures) {
  21162. this._textures[name].dispose();
  21163. }
  21164. this._textures = [];
  21165. _super.prototype.dispose.call(this, forceDisposeEffect);
  21166. };
  21167. return ShaderMaterial;
  21168. })(BABYLON.Material);
  21169. BABYLON.ShaderMaterial = ShaderMaterial;
  21170. })(BABYLON || (BABYLON = {}));
  21171. //# sourceMappingURL=babylon.shaderMaterial.js.mapvar BABYLON;
  21172. (function (BABYLON) {
  21173. var VertexData = (function () {
  21174. function VertexData() {
  21175. }
  21176. VertexData.prototype.set = function (data, kind) {
  21177. switch (kind) {
  21178. case BABYLON.VertexBuffer.PositionKind:
  21179. this.positions = data;
  21180. break;
  21181. case BABYLON.VertexBuffer.NormalKind:
  21182. this.normals = data;
  21183. break;
  21184. case BABYLON.VertexBuffer.UVKind:
  21185. this.uvs = data;
  21186. break;
  21187. case BABYLON.VertexBuffer.UV2Kind:
  21188. this.uv2s = data;
  21189. break;
  21190. case BABYLON.VertexBuffer.ColorKind:
  21191. this.colors = data;
  21192. break;
  21193. case BABYLON.VertexBuffer.MatricesIndicesKind:
  21194. this.matricesIndices = data;
  21195. break;
  21196. case BABYLON.VertexBuffer.MatricesWeightsKind:
  21197. this.matricesWeights = data;
  21198. break;
  21199. }
  21200. };
  21201. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  21202. this._applyTo(mesh, updatable);
  21203. };
  21204. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  21205. this._applyTo(geometry, updatable);
  21206. };
  21207. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  21208. this._update(mesh);
  21209. };
  21210. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  21211. this._update(geometry);
  21212. };
  21213. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  21214. if (this.positions) {
  21215. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  21216. }
  21217. if (this.normals) {
  21218. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  21219. }
  21220. if (this.uvs) {
  21221. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  21222. }
  21223. if (this.uv2s) {
  21224. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updatable);
  21225. }
  21226. if (this.colors) {
  21227. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  21228. }
  21229. if (this.matricesIndices) {
  21230. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  21231. }
  21232. if (this.matricesWeights) {
  21233. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  21234. }
  21235. if (this.indices) {
  21236. meshOrGeometry.setIndices(this.indices);
  21237. }
  21238. };
  21239. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  21240. if (this.positions) {
  21241. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  21242. }
  21243. if (this.normals) {
  21244. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  21245. }
  21246. if (this.uvs) {
  21247. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  21248. }
  21249. if (this.uv2s) {
  21250. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updateExtends, makeItUnique);
  21251. }
  21252. if (this.colors) {
  21253. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  21254. }
  21255. if (this.matricesIndices) {
  21256. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  21257. }
  21258. if (this.matricesWeights) {
  21259. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  21260. }
  21261. if (this.indices) {
  21262. meshOrGeometry.setIndices(this.indices);
  21263. }
  21264. };
  21265. VertexData.prototype.transform = function (matrix) {
  21266. var transformed = BABYLON.Vector3.Zero();
  21267. if (this.positions) {
  21268. var position = BABYLON.Vector3.Zero();
  21269. for (var index = 0; index < this.positions.length; index += 3) {
  21270. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  21271. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  21272. this.positions[index] = transformed.x;
  21273. this.positions[index + 1] = transformed.y;
  21274. this.positions[index + 2] = transformed.z;
  21275. }
  21276. }
  21277. if (this.normals) {
  21278. var normal = BABYLON.Vector3.Zero();
  21279. for (index = 0; index < this.normals.length; index += 3) {
  21280. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  21281. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  21282. this.normals[index] = transformed.x;
  21283. this.normals[index + 1] = transformed.y;
  21284. this.normals[index + 2] = transformed.z;
  21285. }
  21286. }
  21287. };
  21288. VertexData.prototype.merge = function (other) {
  21289. if (other.indices) {
  21290. if (!this.indices) {
  21291. this.indices = [];
  21292. }
  21293. var offset = this.positions ? this.positions.length / 3 : 0;
  21294. for (var index = 0; index < other.indices.length; index++) {
  21295. this.indices.push(other.indices[index] + offset);
  21296. }
  21297. }
  21298. if (other.positions) {
  21299. if (!this.positions) {
  21300. this.positions = [];
  21301. }
  21302. for (index = 0; index < other.positions.length; index++) {
  21303. this.positions.push(other.positions[index]);
  21304. }
  21305. }
  21306. if (other.normals) {
  21307. if (!this.normals) {
  21308. this.normals = [];
  21309. }
  21310. for (index = 0; index < other.normals.length; index++) {
  21311. this.normals.push(other.normals[index]);
  21312. }
  21313. }
  21314. if (other.uvs) {
  21315. if (!this.uvs) {
  21316. this.uvs = [];
  21317. }
  21318. for (index = 0; index < other.uvs.length; index++) {
  21319. this.uvs.push(other.uvs[index]);
  21320. }
  21321. }
  21322. if (other.uv2s) {
  21323. if (!this.uv2s) {
  21324. this.uv2s = [];
  21325. }
  21326. for (index = 0; index < other.uv2s.length; index++) {
  21327. this.uv2s.push(other.uv2s[index]);
  21328. }
  21329. }
  21330. if (other.matricesIndices) {
  21331. if (!this.matricesIndices) {
  21332. this.matricesIndices = [];
  21333. }
  21334. for (index = 0; index < other.matricesIndices.length; index++) {
  21335. this.matricesIndices.push(other.matricesIndices[index]);
  21336. }
  21337. }
  21338. if (other.matricesWeights) {
  21339. if (!this.matricesWeights) {
  21340. this.matricesWeights = [];
  21341. }
  21342. for (index = 0; index < other.matricesWeights.length; index++) {
  21343. this.matricesWeights.push(other.matricesWeights[index]);
  21344. }
  21345. }
  21346. if (other.colors) {
  21347. if (!this.colors) {
  21348. this.colors = [];
  21349. }
  21350. for (index = 0; index < other.colors.length; index++) {
  21351. this.colors.push(other.colors[index]);
  21352. }
  21353. }
  21354. };
  21355. // Statics
  21356. VertexData.ExtractFromMesh = function (mesh) {
  21357. return VertexData._ExtractFrom(mesh);
  21358. };
  21359. VertexData.ExtractFromGeometry = function (geometry) {
  21360. return VertexData._ExtractFrom(geometry);
  21361. };
  21362. VertexData._ExtractFrom = function (meshOrGeometry) {
  21363. var result = new VertexData();
  21364. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  21365. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21366. }
  21367. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21368. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21369. }
  21370. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  21371. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind);
  21372. }
  21373. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  21374. result.uv2s = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  21375. }
  21376. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  21377. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  21378. }
  21379. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  21380. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  21381. }
  21382. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  21383. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  21384. }
  21385. result.indices = meshOrGeometry.getIndices();
  21386. return result;
  21387. };
  21388. VertexData.CreateRibbon = function (pathArray, closeArray, closePath, offset, sideOrientation) {
  21389. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  21390. closeArray = closeArray || false;
  21391. closePath = closePath || false;
  21392. var defaultOffset = Math.floor(pathArray[0].length / 2);
  21393. offset = offset || defaultOffset;
  21394. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  21395. var positions = [];
  21396. var indices = [];
  21397. var normals = [];
  21398. var uvs = [];
  21399. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  21400. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  21401. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  21402. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  21403. var minlg; // minimal length among all paths from pathArray
  21404. var lg = []; // array of path lengths : nb of vertex per path
  21405. var idx = []; // array of path indexes : index of each path (first vertex) in positions array
  21406. var p; // path iterator
  21407. var i; // point iterator
  21408. var j; // point iterator
  21409. // if single path in pathArray
  21410. if (pathArray.length < 2) {
  21411. var ar1 = [];
  21412. var ar2 = [];
  21413. for (i = 0; i < pathArray[0].length - offset; i++) {
  21414. ar1.push(pathArray[0][i]);
  21415. ar2.push(pathArray[0][i + offset]);
  21416. }
  21417. pathArray = [ar1, ar2];
  21418. }
  21419. // positions and horizontal distances (u)
  21420. var idc = 0;
  21421. minlg = pathArray[0].length;
  21422. for (p = 0; p < pathArray.length; p++) {
  21423. uTotalDistance[p] = 0;
  21424. us[p] = [0];
  21425. var path = pathArray[p];
  21426. var l = path.length;
  21427. minlg = (minlg < l) ? minlg : l;
  21428. lg[p] = l;
  21429. idx[p] = idc;
  21430. j = 0;
  21431. while (j < l) {
  21432. positions.push(path[j].x, path[j].y, path[j].z);
  21433. if (j > 0) {
  21434. var vectlg = path[j].subtract(path[j - 1]).length();
  21435. var dist = vectlg + uTotalDistance[p];
  21436. us[p].push(dist);
  21437. uTotalDistance[p] = dist;
  21438. }
  21439. j++;
  21440. }
  21441. if (closePath) {
  21442. vectlg = path[0].subtract(path[j - 1]).length();
  21443. dist = vectlg + uTotalDistance[p];
  21444. uTotalDistance[p] = dist;
  21445. }
  21446. idc += l;
  21447. }
  21448. for (i = 0; i < minlg; i++) {
  21449. vTotalDistance[i] = 0;
  21450. vs[i] = [0];
  21451. var path1;
  21452. var path2;
  21453. for (p = 0; p < pathArray.length - 1; p++) {
  21454. path1 = pathArray[p];
  21455. path2 = pathArray[p + 1];
  21456. vectlg = path2[i].subtract(path1[i]).length();
  21457. dist = vectlg + vTotalDistance[i];
  21458. vs[i].push(dist);
  21459. vTotalDistance[i] = dist;
  21460. }
  21461. if (closeArray) {
  21462. path1 = pathArray[p];
  21463. path2 = pathArray[0];
  21464. vectlg = path2[i].subtract(path1[i]).length();
  21465. dist = vectlg + vTotalDistance[i];
  21466. vTotalDistance[i] = dist;
  21467. }
  21468. }
  21469. // uvs
  21470. var u;
  21471. var v;
  21472. for (p = 0; p < pathArray.length; p++) {
  21473. for (i = 0; i < minlg; i++) {
  21474. u = us[p][i] / uTotalDistance[p];
  21475. v = vs[i][p] / vTotalDistance[i];
  21476. uvs.push(u, v);
  21477. }
  21478. }
  21479. // indices
  21480. p = 0; // path index
  21481. var pi = 0; // positions array index
  21482. var l1 = lg[p] - 1; // path1 length
  21483. var l2 = lg[p + 1] - 1; // path2 length
  21484. var min = (l1 < l2) ? l1 : l2; // current path stop index
  21485. var shft = idx[1] - idx[0]; // shift
  21486. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate
  21487. var t1; // two consecutive triangles, so 4 points : point1
  21488. var t2; // point2
  21489. var t3; // point3
  21490. var t4; // point4
  21491. while (pi <= min && p < path1nb) {
  21492. // draw two triangles between path1 (p1) and path2 (p2) : (p1.pi, p2.pi, p1.pi+1) and (p2.pi+1, p1.pi+1, p2.pi) clockwise
  21493. t1 = pi;
  21494. t2 = pi + shft;
  21495. t3 = pi + 1;
  21496. t4 = pi + shft + 1;
  21497. indices.push(pi, pi + shft, pi + 1);
  21498. indices.push(pi + shft + 1, pi + 1, pi + shft);
  21499. pi += 1;
  21500. if (pi === min) {
  21501. if (closePath) {
  21502. indices.push(pi, pi + shft, idx[p]);
  21503. indices.push(idx[p] + shft, idx[p], pi + shft);
  21504. t3 = idx[p];
  21505. t4 = idx[p] + shft;
  21506. }
  21507. p++;
  21508. if (p === lg.length - 1) {
  21509. shft = idx[0] - idx[p];
  21510. l1 = lg[p] - 1;
  21511. l2 = lg[0] - 1;
  21512. }
  21513. else {
  21514. shft = idx[p + 1] - idx[p];
  21515. l1 = lg[p] - 1;
  21516. l2 = lg[p + 1] - 1;
  21517. }
  21518. pi = idx[p];
  21519. min = (l1 < l2) ? l1 + pi : l2 + pi;
  21520. }
  21521. }
  21522. // normals
  21523. VertexData.ComputeNormals(positions, indices, normals);
  21524. // sides
  21525. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  21526. // Result
  21527. var vertexData = new VertexData();
  21528. vertexData.indices = indices;
  21529. vertexData.positions = positions;
  21530. vertexData.normals = normals;
  21531. vertexData.uvs = uvs;
  21532. return vertexData;
  21533. };
  21534. VertexData.CreateBox = function (size, sideOrientation) {
  21535. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  21536. var normalsSource = [
  21537. new BABYLON.Vector3(0, 0, 1),
  21538. new BABYLON.Vector3(0, 0, -1),
  21539. new BABYLON.Vector3(1, 0, 0),
  21540. new BABYLON.Vector3(-1, 0, 0),
  21541. new BABYLON.Vector3(0, 1, 0),
  21542. new BABYLON.Vector3(0, -1, 0)
  21543. ];
  21544. var indices = [];
  21545. var positions = [];
  21546. var normals = [];
  21547. var uvs = [];
  21548. size = size || 1;
  21549. for (var index = 0; index < normalsSource.length; index++) {
  21550. var normal = normalsSource[index];
  21551. // Get two vectors perpendicular to the face normal and to each other.
  21552. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  21553. var side2 = BABYLON.Vector3.Cross(normal, side1);
  21554. // Six indices (two triangles) per face.
  21555. var verticesLength = positions.length / 3;
  21556. indices.push(verticesLength);
  21557. indices.push(verticesLength + 1);
  21558. indices.push(verticesLength + 2);
  21559. indices.push(verticesLength);
  21560. indices.push(verticesLength + 2);
  21561. indices.push(verticesLength + 3);
  21562. // Four vertices per face.
  21563. var vertex = normal.subtract(side1).subtract(side2).scale(size / 2);
  21564. positions.push(vertex.x, vertex.y, vertex.z);
  21565. normals.push(normal.x, normal.y, normal.z);
  21566. uvs.push(1.0, 1.0);
  21567. vertex = normal.subtract(side1).add(side2).scale(size / 2);
  21568. positions.push(vertex.x, vertex.y, vertex.z);
  21569. normals.push(normal.x, normal.y, normal.z);
  21570. uvs.push(0.0, 1.0);
  21571. vertex = normal.add(side1).add(side2).scale(size / 2);
  21572. positions.push(vertex.x, vertex.y, vertex.z);
  21573. normals.push(normal.x, normal.y, normal.z);
  21574. uvs.push(0.0, 0.0);
  21575. vertex = normal.add(side1).subtract(side2).scale(size / 2);
  21576. positions.push(vertex.x, vertex.y, vertex.z);
  21577. normals.push(normal.x, normal.y, normal.z);
  21578. uvs.push(1.0, 0.0);
  21579. }
  21580. // sides
  21581. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  21582. // Result
  21583. var vertexData = new VertexData();
  21584. vertexData.indices = indices;
  21585. vertexData.positions = positions;
  21586. vertexData.normals = normals;
  21587. vertexData.uvs = uvs;
  21588. return vertexData;
  21589. };
  21590. VertexData.CreateSphere = function (segments, diameter, sideOrientation) {
  21591. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  21592. segments = segments || 32;
  21593. diameter = diameter || 1;
  21594. var radius = diameter / 2;
  21595. var totalZRotationSteps = 2 + segments;
  21596. var totalYRotationSteps = 2 * totalZRotationSteps;
  21597. var indices = [];
  21598. var positions = [];
  21599. var normals = [];
  21600. var uvs = [];
  21601. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  21602. var normalizedZ = zRotationStep / totalZRotationSteps;
  21603. var angleZ = (normalizedZ * Math.PI);
  21604. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  21605. var normalizedY = yRotationStep / totalYRotationSteps;
  21606. var angleY = normalizedY * Math.PI * 2;
  21607. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  21608. var rotationY = BABYLON.Matrix.RotationY(angleY);
  21609. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  21610. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  21611. var vertex = complete.scale(radius);
  21612. var normal = BABYLON.Vector3.Normalize(vertex);
  21613. positions.push(vertex.x, vertex.y, vertex.z);
  21614. normals.push(normal.x, normal.y, normal.z);
  21615. uvs.push(normalizedZ, normalizedY);
  21616. }
  21617. if (zRotationStep > 0) {
  21618. var verticesCount = positions.length / 3;
  21619. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  21620. indices.push((firstIndex));
  21621. indices.push((firstIndex + 1));
  21622. indices.push(firstIndex + totalYRotationSteps + 1);
  21623. indices.push((firstIndex + totalYRotationSteps + 1));
  21624. indices.push((firstIndex + 1));
  21625. indices.push((firstIndex + totalYRotationSteps + 2));
  21626. }
  21627. }
  21628. }
  21629. // Sides
  21630. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  21631. // Result
  21632. var vertexData = new VertexData();
  21633. vertexData.indices = indices;
  21634. vertexData.positions = positions;
  21635. vertexData.normals = normals;
  21636. vertexData.uvs = uvs;
  21637. return vertexData;
  21638. };
  21639. VertexData.CreateCylinder = function (height, diameterTop, diameterBottom, tessellation, subdivisions, sideOrientation) {
  21640. if (subdivisions === void 0) { subdivisions = 1; }
  21641. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  21642. var radiusTop = diameterTop / 2;
  21643. var radiusBottom = diameterBottom / 2;
  21644. var indices = [];
  21645. var positions = [];
  21646. var normals = [];
  21647. var uvs = [];
  21648. height = height || 1;
  21649. diameterTop = diameterTop || 0.5;
  21650. diameterBottom = diameterBottom || 1;
  21651. tessellation = tessellation || 16;
  21652. subdivisions = subdivisions || 1;
  21653. subdivisions = (subdivisions < 1) ? 1 : subdivisions;
  21654. var getCircleVector = function (i) {
  21655. var angle = (i * 2.0 * Math.PI / tessellation);
  21656. var dx = Math.cos(angle);
  21657. var dz = Math.sin(angle);
  21658. return new BABYLON.Vector3(dx, 0, dz);
  21659. };
  21660. var createCylinderCap = function (isTop) {
  21661. var radius = isTop ? radiusTop : radiusBottom;
  21662. if (radius === 0) {
  21663. return;
  21664. }
  21665. var vbase = positions.length / 3;
  21666. var offset = new BABYLON.Vector3(0, height / 2, 0);
  21667. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  21668. if (!isTop) {
  21669. offset.scaleInPlace(-1);
  21670. textureScale.x = -textureScale.x;
  21671. }
  21672. for (var i = 0; i < tessellation; i++) {
  21673. var circleVector = getCircleVector(i);
  21674. var position = circleVector.scale(radius).add(offset);
  21675. var textureCoordinate = new BABYLON.Vector2(circleVector.x * textureScale.x + 0.5, circleVector.z * textureScale.y + 0.5);
  21676. positions.push(position.x, position.y, position.z);
  21677. uvs.push(textureCoordinate.x, textureCoordinate.y);
  21678. }
  21679. for (i = 0; i < tessellation - 2; i++) {
  21680. if (!isTop) {
  21681. indices.push(vbase);
  21682. indices.push(vbase + (i + 2) % tessellation);
  21683. indices.push(vbase + (i + 1) % tessellation);
  21684. }
  21685. else {
  21686. indices.push(vbase);
  21687. indices.push(vbase + (i + 1) % tessellation);
  21688. indices.push(vbase + (i + 2) % tessellation);
  21689. }
  21690. }
  21691. };
  21692. var base = new BABYLON.Vector3(0, -1, 0).scale(height / 2);
  21693. var offset = new BABYLON.Vector3(0, 1, 0).scale(height / subdivisions);
  21694. var stride = tessellation + 1;
  21695. for (var i = 0; i <= tessellation; i++) {
  21696. var circleVector = getCircleVector(i);
  21697. var textureCoordinate = new BABYLON.Vector2(i / tessellation, 0);
  21698. var position, radius = radiusBottom;
  21699. for (var s = 0; s <= subdivisions; s++) {
  21700. // Update variables
  21701. position = circleVector.scale(radius);
  21702. position.addInPlace(base.add(offset.scale(s)));
  21703. textureCoordinate.y += 1 / subdivisions;
  21704. radius += (radiusTop - radiusBottom) / subdivisions;
  21705. // Push in arrays
  21706. positions.push(position.x, position.y, position.z);
  21707. uvs.push(textureCoordinate.x, textureCoordinate.y);
  21708. }
  21709. }
  21710. subdivisions += 1;
  21711. for (s = 0; s < subdivisions - 1; s++) {
  21712. for (i = 0; i <= tessellation; i++) {
  21713. indices.push(i * subdivisions + s);
  21714. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  21715. indices.push(i * subdivisions + (s + 1));
  21716. indices.push(i * subdivisions + (s + 1));
  21717. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  21718. indices.push((i * subdivisions + (s + subdivisions + 1)) % (stride * subdivisions));
  21719. }
  21720. }
  21721. // Create flat triangle fan caps to seal the top and bottom.
  21722. createCylinderCap(true);
  21723. createCylinderCap(false);
  21724. // Normals
  21725. VertexData.ComputeNormals(positions, indices, normals);
  21726. // Sides
  21727. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  21728. // Result
  21729. var vertexData = new VertexData();
  21730. vertexData.indices = indices;
  21731. vertexData.positions = positions;
  21732. vertexData.normals = normals;
  21733. vertexData.uvs = uvs;
  21734. return vertexData;
  21735. };
  21736. VertexData.CreateTorus = function (diameter, thickness, tessellation, sideOrientation) {
  21737. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  21738. var indices = [];
  21739. var positions = [];
  21740. var normals = [];
  21741. var uvs = [];
  21742. diameter = diameter || 1;
  21743. thickness = thickness || 0.5;
  21744. tessellation = tessellation || 16;
  21745. var stride = tessellation + 1;
  21746. for (var i = 0; i <= tessellation; i++) {
  21747. var u = i / tessellation;
  21748. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  21749. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  21750. for (var j = 0; j <= tessellation; j++) {
  21751. var v = 1 - j / tessellation;
  21752. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  21753. var dx = Math.cos(innerAngle);
  21754. var dy = Math.sin(innerAngle);
  21755. // Create a vertex.
  21756. var normal = new BABYLON.Vector3(dx, dy, 0);
  21757. var position = normal.scale(thickness / 2);
  21758. var textureCoordinate = new BABYLON.Vector2(u, v);
  21759. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  21760. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  21761. positions.push(position.x, position.y, position.z);
  21762. normals.push(normal.x, normal.y, normal.z);
  21763. uvs.push(textureCoordinate.x, textureCoordinate.y);
  21764. // And create indices for two triangles.
  21765. var nextI = (i + 1) % stride;
  21766. var nextJ = (j + 1) % stride;
  21767. indices.push(i * stride + j);
  21768. indices.push(i * stride + nextJ);
  21769. indices.push(nextI * stride + j);
  21770. indices.push(i * stride + nextJ);
  21771. indices.push(nextI * stride + nextJ);
  21772. indices.push(nextI * stride + j);
  21773. }
  21774. }
  21775. // Sides
  21776. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  21777. // Result
  21778. var vertexData = new VertexData();
  21779. vertexData.indices = indices;
  21780. vertexData.positions = positions;
  21781. vertexData.normals = normals;
  21782. vertexData.uvs = uvs;
  21783. return vertexData;
  21784. };
  21785. VertexData.CreateLines = function (points) {
  21786. var indices = [];
  21787. var positions = [];
  21788. for (var index = 0; index < points.length; index++) {
  21789. positions.push(points[index].x, points[index].y, points[index].z);
  21790. if (index > 0) {
  21791. indices.push(index - 1);
  21792. indices.push(index);
  21793. }
  21794. }
  21795. // Result
  21796. var vertexData = new VertexData();
  21797. vertexData.indices = indices;
  21798. vertexData.positions = positions;
  21799. return vertexData;
  21800. };
  21801. VertexData.CreateGround = function (width, height, subdivisions) {
  21802. var indices = [];
  21803. var positions = [];
  21804. var normals = [];
  21805. var uvs = [];
  21806. var row, col;
  21807. width = width || 1;
  21808. height = height || 1;
  21809. subdivisions = subdivisions || 1;
  21810. for (row = 0; row <= subdivisions; row++) {
  21811. for (col = 0; col <= subdivisions; col++) {
  21812. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  21813. var normal = new BABYLON.Vector3(0, 1.0, 0);
  21814. positions.push(position.x, position.y, position.z);
  21815. normals.push(normal.x, normal.y, normal.z);
  21816. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  21817. }
  21818. }
  21819. for (row = 0; row < subdivisions; row++) {
  21820. for (col = 0; col < subdivisions; col++) {
  21821. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  21822. indices.push(col + 1 + row * (subdivisions + 1));
  21823. indices.push(col + row * (subdivisions + 1));
  21824. indices.push(col + (row + 1) * (subdivisions + 1));
  21825. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  21826. indices.push(col + row * (subdivisions + 1));
  21827. }
  21828. }
  21829. // Result
  21830. var vertexData = new VertexData();
  21831. vertexData.indices = indices;
  21832. vertexData.positions = positions;
  21833. vertexData.normals = normals;
  21834. vertexData.uvs = uvs;
  21835. return vertexData;
  21836. };
  21837. VertexData.CreateTiledGround = function (xmin, zmin, xmax, zmax, subdivisions, precision) {
  21838. if (subdivisions === void 0) { subdivisions = { w: 1, h: 1 }; }
  21839. if (precision === void 0) { precision = { w: 1, h: 1 }; }
  21840. var indices = [];
  21841. var positions = [];
  21842. var normals = [];
  21843. var uvs = [];
  21844. var row, col, tileRow, tileCol;
  21845. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  21846. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  21847. precision.w = (precision.w < 1) ? 1 : precision.w;
  21848. precision.h = (precision.h < 1) ? 1 : precision.h;
  21849. var tileSize = {
  21850. 'w': (xmax - xmin) / subdivisions.w,
  21851. 'h': (zmax - zmin) / subdivisions.h
  21852. };
  21853. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  21854. // Indices
  21855. var base = positions.length / 3;
  21856. var rowLength = precision.w + 1;
  21857. for (row = 0; row < precision.h; row++) {
  21858. for (col = 0; col < precision.w; col++) {
  21859. var square = [
  21860. base + col + row * rowLength,
  21861. base + (col + 1) + row * rowLength,
  21862. base + (col + 1) + (row + 1) * rowLength,
  21863. base + col + (row + 1) * rowLength
  21864. ];
  21865. indices.push(square[1]);
  21866. indices.push(square[2]);
  21867. indices.push(square[3]);
  21868. indices.push(square[0]);
  21869. indices.push(square[1]);
  21870. indices.push(square[3]);
  21871. }
  21872. }
  21873. // Position, normals and uvs
  21874. var position = BABYLON.Vector3.Zero();
  21875. var normal = new BABYLON.Vector3(0, 1.0, 0);
  21876. for (row = 0; row <= precision.h; row++) {
  21877. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  21878. for (col = 0; col <= precision.w; col++) {
  21879. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  21880. position.y = 0;
  21881. positions.push(position.x, position.y, position.z);
  21882. normals.push(normal.x, normal.y, normal.z);
  21883. uvs.push(col / precision.w, row / precision.h);
  21884. }
  21885. }
  21886. }
  21887. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  21888. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  21889. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  21890. }
  21891. }
  21892. // Result
  21893. var vertexData = new VertexData();
  21894. vertexData.indices = indices;
  21895. vertexData.positions = positions;
  21896. vertexData.normals = normals;
  21897. vertexData.uvs = uvs;
  21898. return vertexData;
  21899. };
  21900. VertexData.CreateGroundFromHeightMap = function (width, height, subdivisions, minHeight, maxHeight, buffer, bufferWidth, bufferHeight) {
  21901. var indices = [];
  21902. var positions = [];
  21903. var normals = [];
  21904. var uvs = [];
  21905. var row, col;
  21906. for (row = 0; row <= subdivisions; row++) {
  21907. for (col = 0; col <= subdivisions; col++) {
  21908. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  21909. // Compute height
  21910. var heightMapX = (((position.x + width / 2) / width) * (bufferWidth - 1)) | 0;
  21911. var heightMapY = ((1.0 - (position.z + height / 2) / height) * (bufferHeight - 1)) | 0;
  21912. var pos = (heightMapX + heightMapY * bufferWidth) * 4;
  21913. var r = buffer[pos] / 255.0;
  21914. var g = buffer[pos + 1] / 255.0;
  21915. var b = buffer[pos + 2] / 255.0;
  21916. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  21917. position.y = minHeight + (maxHeight - minHeight) * gradient;
  21918. // Add vertex
  21919. positions.push(position.x, position.y, position.z);
  21920. normals.push(0, 0, 0);
  21921. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  21922. }
  21923. }
  21924. for (row = 0; row < subdivisions; row++) {
  21925. for (col = 0; col < subdivisions; col++) {
  21926. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  21927. indices.push(col + 1 + row * (subdivisions + 1));
  21928. indices.push(col + row * (subdivisions + 1));
  21929. indices.push(col + (row + 1) * (subdivisions + 1));
  21930. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  21931. indices.push(col + row * (subdivisions + 1));
  21932. }
  21933. }
  21934. // Normals
  21935. VertexData.ComputeNormals(positions, indices, normals);
  21936. // Result
  21937. var vertexData = new VertexData();
  21938. vertexData.indices = indices;
  21939. vertexData.positions = positions;
  21940. vertexData.normals = normals;
  21941. vertexData.uvs = uvs;
  21942. return vertexData;
  21943. };
  21944. VertexData.CreatePlane = function (size, sideOrientation) {
  21945. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  21946. var indices = [];
  21947. var positions = [];
  21948. var normals = [];
  21949. var uvs = [];
  21950. size = size || 1;
  21951. // Vertices
  21952. var halfSize = size / 2.0;
  21953. positions.push(-halfSize, -halfSize, 0);
  21954. normals.push(0, 0, -1.0);
  21955. uvs.push(0.0, 0.0);
  21956. positions.push(halfSize, -halfSize, 0);
  21957. normals.push(0, 0, -1.0);
  21958. uvs.push(1.0, 0.0);
  21959. positions.push(halfSize, halfSize, 0);
  21960. normals.push(0, 0, -1.0);
  21961. uvs.push(1.0, 1.0);
  21962. positions.push(-halfSize, halfSize, 0);
  21963. normals.push(0, 0, -1.0);
  21964. uvs.push(0.0, 1.0);
  21965. // Indices
  21966. indices.push(0);
  21967. indices.push(1);
  21968. indices.push(2);
  21969. indices.push(0);
  21970. indices.push(2);
  21971. indices.push(3);
  21972. // Sides
  21973. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  21974. // Result
  21975. var vertexData = new VertexData();
  21976. vertexData.indices = indices;
  21977. vertexData.positions = positions;
  21978. vertexData.normals = normals;
  21979. vertexData.uvs = uvs;
  21980. return vertexData;
  21981. };
  21982. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  21983. VertexData.CreateTorusKnot = function (radius, tube, radialSegments, tubularSegments, p, q, sideOrientation) {
  21984. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  21985. var indices = [];
  21986. var positions = [];
  21987. var normals = [];
  21988. var uvs = [];
  21989. radius = radius || 2;
  21990. tube = tube || 0.5;
  21991. radialSegments = radialSegments || 32;
  21992. tubularSegments = tubularSegments || 32;
  21993. p = p || 2;
  21994. q = q || 3;
  21995. // Helper
  21996. var getPos = function (angle) {
  21997. var cu = Math.cos(angle);
  21998. var su = Math.sin(angle);
  21999. var quOverP = q / p * angle;
  22000. var cs = Math.cos(quOverP);
  22001. var tx = radius * (2 + cs) * 0.5 * cu;
  22002. var ty = radius * (2 + cs) * su * 0.5;
  22003. var tz = radius * Math.sin(quOverP) * 0.5;
  22004. return new BABYLON.Vector3(tx, ty, tz);
  22005. };
  22006. for (var i = 0; i <= radialSegments; i++) {
  22007. var modI = i % radialSegments;
  22008. var u = modI / radialSegments * 2 * p * Math.PI;
  22009. var p1 = getPos(u);
  22010. var p2 = getPos(u + 0.01);
  22011. var tang = p2.subtract(p1);
  22012. var n = p2.add(p1);
  22013. var bitan = BABYLON.Vector3.Cross(tang, n);
  22014. n = BABYLON.Vector3.Cross(bitan, tang);
  22015. bitan.normalize();
  22016. n.normalize();
  22017. for (var j = 0; j < tubularSegments; j++) {
  22018. var modJ = j % tubularSegments;
  22019. var v = modJ / tubularSegments * 2 * Math.PI;
  22020. var cx = -tube * Math.cos(v);
  22021. var cy = tube * Math.sin(v);
  22022. positions.push(p1.x + cx * n.x + cy * bitan.x);
  22023. positions.push(p1.y + cx * n.y + cy * bitan.y);
  22024. positions.push(p1.z + cx * n.z + cy * bitan.z);
  22025. uvs.push(i / radialSegments);
  22026. uvs.push(j / tubularSegments);
  22027. }
  22028. }
  22029. for (i = 0; i < radialSegments; i++) {
  22030. for (j = 0; j < tubularSegments; j++) {
  22031. var jNext = (j + 1) % tubularSegments;
  22032. var a = i * tubularSegments + j;
  22033. var b = (i + 1) * tubularSegments + j;
  22034. var c = (i + 1) * tubularSegments + jNext;
  22035. var d = i * tubularSegments + jNext;
  22036. indices.push(d);
  22037. indices.push(b);
  22038. indices.push(a);
  22039. indices.push(d);
  22040. indices.push(c);
  22041. indices.push(b);
  22042. }
  22043. }
  22044. // Normals
  22045. VertexData.ComputeNormals(positions, indices, normals);
  22046. // Sides
  22047. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  22048. // Result
  22049. var vertexData = new VertexData();
  22050. vertexData.indices = indices;
  22051. vertexData.positions = positions;
  22052. vertexData.normals = normals;
  22053. vertexData.uvs = uvs;
  22054. return vertexData;
  22055. };
  22056. // Tools
  22057. VertexData.ComputeNormals = function (positions, indices, normals) {
  22058. var positionVectors = [];
  22059. var facesOfVertices = [];
  22060. var index;
  22061. for (index = 0; index < positions.length; index += 3) {
  22062. var vector3 = new BABYLON.Vector3(positions[index], positions[index + 1], positions[index + 2]);
  22063. positionVectors.push(vector3);
  22064. facesOfVertices.push([]);
  22065. }
  22066. // Compute normals
  22067. var facesNormals = [];
  22068. for (index = 0; index < indices.length / 3; index++) {
  22069. var i1 = indices[index * 3];
  22070. var i2 = indices[index * 3 + 1];
  22071. var i3 = indices[index * 3 + 2];
  22072. var p1 = positionVectors[i1];
  22073. var p2 = positionVectors[i2];
  22074. var p3 = positionVectors[i3];
  22075. var p1p2 = p1.subtract(p2);
  22076. var p3p2 = p3.subtract(p2);
  22077. facesNormals[index] = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  22078. facesOfVertices[i1].push(index);
  22079. facesOfVertices[i2].push(index);
  22080. facesOfVertices[i3].push(index);
  22081. }
  22082. for (index = 0; index < positionVectors.length; index++) {
  22083. var faces = facesOfVertices[index];
  22084. var normal = BABYLON.Vector3.Zero();
  22085. for (var faceIndex = 0; faceIndex < faces.length; faceIndex++) {
  22086. normal.addInPlace(facesNormals[faces[faceIndex]]);
  22087. }
  22088. normal = BABYLON.Vector3.Normalize(normal.scale(1.0 / faces.length));
  22089. normals[index * 3] = normal.x;
  22090. normals[index * 3 + 1] = normal.y;
  22091. normals[index * 3 + 2] = normal.z;
  22092. }
  22093. };
  22094. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  22095. var li = indices.length;
  22096. var ln = normals.length;
  22097. var i;
  22098. var n;
  22099. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  22100. switch (sideOrientation) {
  22101. case BABYLON.Mesh.FRONTSIDE:
  22102. break;
  22103. case BABYLON.Mesh.BACKSIDE:
  22104. var tmp;
  22105. for (i = 0; i < li; i += 3) {
  22106. tmp = indices[i];
  22107. indices[i] = indices[i + 2];
  22108. indices[i + 2] = tmp;
  22109. }
  22110. for (n = 0; n < ln; n++) {
  22111. normals[n] = -normals[n];
  22112. }
  22113. break;
  22114. case BABYLON.Mesh.DOUBLESIDE:
  22115. // positions
  22116. var lp = positions.length;
  22117. var l = lp / 3;
  22118. for (var p = 0; p < lp; p++) {
  22119. positions[lp + p] = positions[p];
  22120. }
  22121. for (i = 0; i < li; i += 3) {
  22122. indices[i + li] = indices[i + 2] + l;
  22123. indices[i + 1 + li] = indices[i + 1] + l;
  22124. indices[i + 2 + li] = indices[i] + l;
  22125. }
  22126. for (n = 0; n < ln; n++) {
  22127. normals[ln + n] = -normals[n];
  22128. }
  22129. // uvs
  22130. var lu = uvs.length;
  22131. for (var u = 0; u < lu; u++) {
  22132. uvs[u + lu] = uvs[u];
  22133. }
  22134. break;
  22135. }
  22136. };
  22137. return VertexData;
  22138. })();
  22139. BABYLON.VertexData = VertexData;
  22140. })(BABYLON || (BABYLON = {}));
  22141. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  22142. var BABYLON;
  22143. (function (BABYLON) {
  22144. var buildCamera = function (that, name) {
  22145. that._leftCamera.isIntermediate = true;
  22146. that.subCameras.push(that._leftCamera);
  22147. that.subCameras.push(that._rightCamera);
  22148. that._leftTexture = new BABYLON.PassPostProcess(name + "_leftTexture", 1.0, that._leftCamera);
  22149. that._anaglyphPostProcess = new BABYLON.AnaglyphPostProcess(name + "_anaglyph", 1.0, that._rightCamera);
  22150. that._anaglyphPostProcess.onApply = function (effect) {
  22151. effect.setTextureFromPostProcess("leftSampler", that._leftTexture);
  22152. };
  22153. that._update();
  22154. };
  22155. var AnaglyphArcRotateCamera = (function (_super) {
  22156. __extends(AnaglyphArcRotateCamera, _super);
  22157. // ANY
  22158. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, eyeSpace, scene) {
  22159. _super.call(this, name, alpha, beta, radius, target, scene);
  22160. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  22161. this._leftCamera = new BABYLON.ArcRotateCamera(name + "_left", alpha - this._eyeSpace, beta, radius, target, scene);
  22162. this._rightCamera = new BABYLON.ArcRotateCamera(name + "_right", alpha + this._eyeSpace, beta, radius, target, scene);
  22163. buildCamera(this, name);
  22164. }
  22165. AnaglyphArcRotateCamera.prototype._update = function () {
  22166. this._updateCamera(this._leftCamera);
  22167. this._updateCamera(this._rightCamera);
  22168. this._leftCamera.alpha = this.alpha - this._eyeSpace;
  22169. this._rightCamera.alpha = this.alpha + this._eyeSpace;
  22170. _super.prototype._update.call(this);
  22171. };
  22172. AnaglyphArcRotateCamera.prototype._updateCamera = function (camera) {
  22173. camera.beta = this.beta;
  22174. camera.radius = this.radius;
  22175. camera.minZ = this.minZ;
  22176. camera.maxZ = this.maxZ;
  22177. camera.fov = this.fov;
  22178. camera.target = this.target;
  22179. };
  22180. return AnaglyphArcRotateCamera;
  22181. })(BABYLON.ArcRotateCamera);
  22182. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  22183. var AnaglyphFreeCamera = (function (_super) {
  22184. __extends(AnaglyphFreeCamera, _super);
  22185. function AnaglyphFreeCamera(name, position, eyeSpace, scene) {
  22186. _super.call(this, name, position, scene);
  22187. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  22188. this._transformMatrix = new BABYLON.Matrix();
  22189. this._leftCamera = new BABYLON.FreeCamera(name + "_left", position.clone(), scene);
  22190. this._rightCamera = new BABYLON.FreeCamera(name + "_right", position.clone(), scene);
  22191. buildCamera(this, name);
  22192. }
  22193. AnaglyphFreeCamera.prototype._getSubCameraPosition = function (eyeSpace, result) {
  22194. var target = this.getTarget();
  22195. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(eyeSpace), this._transformMatrix);
  22196. this._transformMatrix = this._transformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  22197. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._transformMatrix, result);
  22198. };
  22199. AnaglyphFreeCamera.prototype._update = function () {
  22200. this._getSubCameraPosition(-this._eyeSpace, this._leftCamera.position);
  22201. this._getSubCameraPosition(this._eyeSpace, this._rightCamera.position);
  22202. this._updateCamera(this._leftCamera);
  22203. this._updateCamera(this._rightCamera);
  22204. _super.prototype._update.call(this);
  22205. };
  22206. AnaglyphFreeCamera.prototype._updateCamera = function (camera) {
  22207. camera.minZ = this.minZ;
  22208. camera.maxZ = this.maxZ;
  22209. camera.fov = this.fov;
  22210. camera.viewport = this.viewport;
  22211. camera.setTarget(this.getTarget());
  22212. };
  22213. return AnaglyphFreeCamera;
  22214. })(BABYLON.FreeCamera);
  22215. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  22216. })(BABYLON || (BABYLON = {}));
  22217. //# sourceMappingURL=babylon.anaglyphCamera.js.map
  22218. var BABYLON;
  22219. (function (BABYLON) {
  22220. var AnaglyphPostProcess = (function (_super) {
  22221. __extends(AnaglyphPostProcess, _super);
  22222. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  22223. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  22224. }
  22225. return AnaglyphPostProcess;
  22226. })(BABYLON.PostProcess);
  22227. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  22228. })(BABYLON || (BABYLON = {}));
  22229. //# sourceMappingURL=babylon.anaglyphPostProcess.js.mapvar BABYLON;
  22230. (function (BABYLON) {
  22231. var Tags = (function () {
  22232. function Tags() {
  22233. }
  22234. Tags.EnableFor = function (obj) {
  22235. obj._tags = obj._tags || {};
  22236. obj.hasTags = function () {
  22237. return Tags.HasTags(obj);
  22238. };
  22239. obj.addTags = function (tagsString) {
  22240. return Tags.AddTagsTo(obj, tagsString);
  22241. };
  22242. obj.removeTags = function (tagsString) {
  22243. return Tags.RemoveTagsFrom(obj, tagsString);
  22244. };
  22245. obj.matchesTagsQuery = function (tagsQuery) {
  22246. return Tags.MatchesQuery(obj, tagsQuery);
  22247. };
  22248. };
  22249. Tags.DisableFor = function (obj) {
  22250. delete obj._tags;
  22251. delete obj.hasTags;
  22252. delete obj.addTags;
  22253. delete obj.removeTags;
  22254. delete obj.matchesTagsQuery;
  22255. };
  22256. Tags.HasTags = function (obj) {
  22257. if (!obj._tags) {
  22258. return false;
  22259. }
  22260. return !BABYLON.Tools.IsEmpty(obj._tags);
  22261. };
  22262. Tags.GetTags = function (obj) {
  22263. if (!obj._tags) {
  22264. return null;
  22265. }
  22266. return obj._tags;
  22267. };
  22268. // the tags 'true' and 'false' are reserved and cannot be used as tags
  22269. // a tag cannot start with '||', '&&', and '!'
  22270. // it cannot contain whitespaces
  22271. Tags.AddTagsTo = function (obj, tagsString) {
  22272. if (!tagsString) {
  22273. return;
  22274. }
  22275. var tags = tagsString.split(" ");
  22276. for (var t in tags) {
  22277. Tags._AddTagTo(obj, tags[t]);
  22278. }
  22279. };
  22280. Tags._AddTagTo = function (obj, tag) {
  22281. tag = tag.trim();
  22282. if (tag === "" || tag === "true" || tag === "false") {
  22283. return;
  22284. }
  22285. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  22286. return;
  22287. }
  22288. Tags.EnableFor(obj);
  22289. obj._tags[tag] = true;
  22290. };
  22291. Tags.RemoveTagsFrom = function (obj, tagsString) {
  22292. if (!Tags.HasTags(obj)) {
  22293. return;
  22294. }
  22295. var tags = tagsString.split(" ");
  22296. for (var t in tags) {
  22297. Tags._RemoveTagFrom(obj, tags[t]);
  22298. }
  22299. };
  22300. Tags._RemoveTagFrom = function (obj, tag) {
  22301. delete obj._tags[tag];
  22302. };
  22303. Tags.MatchesQuery = function (obj, tagsQuery) {
  22304. if (tagsQuery === undefined) {
  22305. return true;
  22306. }
  22307. if (tagsQuery === "") {
  22308. return Tags.HasTags(obj);
  22309. }
  22310. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  22311. };
  22312. return Tags;
  22313. })();
  22314. BABYLON.Tags = Tags;
  22315. })(BABYLON || (BABYLON = {}));
  22316. //# sourceMappingURL=babylon.tags.js.mapvar BABYLON;
  22317. (function (BABYLON) {
  22318. var Internals;
  22319. (function (Internals) {
  22320. var AndOrNotEvaluator = (function () {
  22321. function AndOrNotEvaluator() {
  22322. }
  22323. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  22324. if (!query.match(/\([^\(\)]*\)/g)) {
  22325. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  22326. }
  22327. else {
  22328. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  22329. // remove parenthesis
  22330. r = r.slice(1, r.length - 1);
  22331. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  22332. });
  22333. }
  22334. if (query === "true") {
  22335. return true;
  22336. }
  22337. if (query === "false") {
  22338. return false;
  22339. }
  22340. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  22341. };
  22342. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  22343. evaluateCallback = evaluateCallback || (function (r) {
  22344. return r === "true" ? true : false;
  22345. });
  22346. var result;
  22347. var or = parenthesisContent.split("||");
  22348. for (var i in or) {
  22349. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  22350. var and = ori.split("&&");
  22351. if (and.length > 1) {
  22352. for (var j = 0; j < and.length; ++j) {
  22353. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  22354. if (andj !== "true" && andj !== "false") {
  22355. if (andj[0] === "!") {
  22356. result = !evaluateCallback(andj.substring(1));
  22357. }
  22358. else {
  22359. result = evaluateCallback(andj);
  22360. }
  22361. }
  22362. else {
  22363. result = andj === "true" ? true : false;
  22364. }
  22365. if (!result) {
  22366. ori = "false";
  22367. break;
  22368. }
  22369. }
  22370. }
  22371. if (result || ori === "true") {
  22372. result = true;
  22373. break;
  22374. }
  22375. // result equals false (or undefined)
  22376. if (ori !== "true" && ori !== "false") {
  22377. if (ori[0] === "!") {
  22378. result = !evaluateCallback(ori.substring(1));
  22379. }
  22380. else {
  22381. result = evaluateCallback(ori);
  22382. }
  22383. }
  22384. else {
  22385. result = ori === "true" ? true : false;
  22386. }
  22387. }
  22388. // the whole parenthesis scope is replaced by 'true' or 'false'
  22389. return result ? "true" : "false";
  22390. };
  22391. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  22392. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  22393. // remove whitespaces
  22394. r = r.replace(/[\s]/g, function () { return ""; });
  22395. return r.length % 2 ? "!" : "";
  22396. });
  22397. booleanString = booleanString.trim();
  22398. if (booleanString === "!true") {
  22399. booleanString = "false";
  22400. }
  22401. else if (booleanString === "!false") {
  22402. booleanString = "true";
  22403. }
  22404. return booleanString;
  22405. };
  22406. return AndOrNotEvaluator;
  22407. })();
  22408. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  22409. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  22410. })(BABYLON || (BABYLON = {}));
  22411. //# sourceMappingURL=babylon.andOrNotEvaluator.js.mapvar BABYLON;
  22412. (function (BABYLON) {
  22413. var PostProcessRenderPass = (function () {
  22414. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  22415. this._enabled = true;
  22416. this._refCount = 0;
  22417. this._name = name;
  22418. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  22419. this.setRenderList(renderList);
  22420. this._renderTexture.onBeforeRender = beforeRender;
  22421. this._renderTexture.onAfterRender = afterRender;
  22422. this._scene = scene;
  22423. this._renderList = renderList;
  22424. }
  22425. // private
  22426. PostProcessRenderPass.prototype._incRefCount = function () {
  22427. if (this._refCount === 0) {
  22428. this._scene.customRenderTargets.push(this._renderTexture);
  22429. }
  22430. return ++this._refCount;
  22431. };
  22432. PostProcessRenderPass.prototype._decRefCount = function () {
  22433. this._refCount--;
  22434. if (this._refCount <= 0) {
  22435. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  22436. }
  22437. return this._refCount;
  22438. };
  22439. PostProcessRenderPass.prototype._update = function () {
  22440. this.setRenderList(this._renderList);
  22441. };
  22442. // public
  22443. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  22444. this._renderTexture.renderList = renderList;
  22445. };
  22446. PostProcessRenderPass.prototype.getRenderTexture = function () {
  22447. return this._renderTexture;
  22448. };
  22449. return PostProcessRenderPass;
  22450. })();
  22451. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  22452. })(BABYLON || (BABYLON = {}));
  22453. //# sourceMappingURL=babylon.postProcessRenderPass.js.mapvar BABYLON;
  22454. (function (BABYLON) {
  22455. var PostProcessRenderEffect = (function () {
  22456. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  22457. this._engine = engine;
  22458. this._name = name;
  22459. this._singleInstance = singleInstance || true;
  22460. this._getPostProcess = getPostProcess;
  22461. this._cameras = [];
  22462. this._indicesForCamera = [];
  22463. this._postProcesses = {};
  22464. this._renderPasses = {};
  22465. this._renderEffectAsPasses = {};
  22466. }
  22467. PostProcessRenderEffect.prototype._update = function () {
  22468. for (var renderPassName in this._renderPasses) {
  22469. this._renderPasses[renderPassName]._update();
  22470. }
  22471. };
  22472. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  22473. this._renderPasses[renderPass._name] = renderPass;
  22474. this._linkParameters();
  22475. };
  22476. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  22477. delete this._renderPasses[renderPass._name];
  22478. this._linkParameters();
  22479. };
  22480. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  22481. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  22482. this._linkParameters();
  22483. };
  22484. PostProcessRenderEffect.prototype.getPass = function (passName) {
  22485. for (var renderPassName in this._renderPasses) {
  22486. if (renderPassName === passName) {
  22487. return this._renderPasses[passName];
  22488. }
  22489. }
  22490. };
  22491. PostProcessRenderEffect.prototype.emptyPasses = function () {
  22492. this._renderPasses = {};
  22493. this._linkParameters();
  22494. };
  22495. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  22496. var cameraKey;
  22497. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  22498. for (var i = 0; i < _cam.length; i++) {
  22499. var camera = _cam[i];
  22500. var cameraName = camera.name;
  22501. if (this._singleInstance) {
  22502. cameraKey = 0;
  22503. }
  22504. else {
  22505. cameraKey = cameraName;
  22506. }
  22507. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  22508. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  22509. if (!this._indicesForCamera[cameraName]) {
  22510. this._indicesForCamera[cameraName] = [];
  22511. }
  22512. this._indicesForCamera[cameraName].push(index);
  22513. if (this._cameras.indexOf(camera) === -1) {
  22514. this._cameras[cameraName] = camera;
  22515. }
  22516. for (var passName in this._renderPasses) {
  22517. this._renderPasses[passName]._incRefCount();
  22518. }
  22519. }
  22520. this._linkParameters();
  22521. };
  22522. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  22523. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  22524. for (var i = 0; i < _cam.length; i++) {
  22525. var camera = _cam[i];
  22526. var cameraName = camera.name;
  22527. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  22528. var index = this._cameras.indexOf(cameraName);
  22529. this._indicesForCamera.splice(index, 1);
  22530. this._cameras.splice(index, 1);
  22531. for (var passName in this._renderPasses) {
  22532. this._renderPasses[passName]._decRefCount();
  22533. }
  22534. }
  22535. };
  22536. PostProcessRenderEffect.prototype._enable = function (cameras) {
  22537. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  22538. for (var i = 0; i < _cam.length; i++) {
  22539. var camera = _cam[i];
  22540. var cameraName = camera.name;
  22541. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  22542. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  22543. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  22544. }
  22545. }
  22546. for (var passName in this._renderPasses) {
  22547. this._renderPasses[passName]._incRefCount();
  22548. }
  22549. }
  22550. };
  22551. PostProcessRenderEffect.prototype._disable = function (cameras) {
  22552. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  22553. for (var i = 0; i < _cam.length; i++) {
  22554. var camera = _cam[i];
  22555. var cameraName = camera.Name;
  22556. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  22557. for (var passName in this._renderPasses) {
  22558. this._renderPasses[passName]._decRefCount();
  22559. }
  22560. }
  22561. };
  22562. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  22563. if (this._singleInstance) {
  22564. return this._postProcesses[0];
  22565. }
  22566. else {
  22567. return this._postProcesses[camera.name];
  22568. }
  22569. };
  22570. PostProcessRenderEffect.prototype._linkParameters = function () {
  22571. var _this = this;
  22572. for (var index in this._postProcesses) {
  22573. if (this.applyParameters) {
  22574. this.applyParameters(this._postProcesses[index]);
  22575. }
  22576. this._postProcesses[index].onBeforeRender = function (effect) {
  22577. _this._linkTextures(effect);
  22578. };
  22579. }
  22580. };
  22581. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  22582. for (var renderPassName in this._renderPasses) {
  22583. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  22584. }
  22585. for (var renderEffectName in this._renderEffectAsPasses) {
  22586. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  22587. }
  22588. };
  22589. return PostProcessRenderEffect;
  22590. })();
  22591. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  22592. })(BABYLON || (BABYLON = {}));
  22593. //# sourceMappingURL=babylon.postProcessRenderEffect.js.mapvar BABYLON;
  22594. (function (BABYLON) {
  22595. var PostProcessRenderPipeline = (function () {
  22596. function PostProcessRenderPipeline(engine, name) {
  22597. this._engine = engine;
  22598. this._name = name;
  22599. this._renderEffects = {};
  22600. this._renderEffectsForIsolatedPass = {};
  22601. this._cameras = [];
  22602. }
  22603. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  22604. this._renderEffects[renderEffect._name] = renderEffect;
  22605. };
  22606. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  22607. var renderEffects = this._renderEffects[renderEffectName];
  22608. if (!renderEffects) {
  22609. return;
  22610. }
  22611. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  22612. };
  22613. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  22614. var renderEffects = this._renderEffects[renderEffectName];
  22615. if (!renderEffects) {
  22616. return;
  22617. }
  22618. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  22619. };
  22620. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  22621. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  22622. var indicesToDelete = [];
  22623. for (var i = 0; i < _cam.length; i++) {
  22624. var camera = _cam[i];
  22625. var cameraName = camera.name;
  22626. if (this._cameras.indexOf(camera) === -1) {
  22627. this._cameras[cameraName] = camera;
  22628. }
  22629. else if (unique) {
  22630. indicesToDelete.push(i);
  22631. }
  22632. }
  22633. for (var i = 0; i < indicesToDelete.length; i++) {
  22634. cameras.splice(indicesToDelete[i], 1);
  22635. }
  22636. for (var renderEffectName in this._renderEffects) {
  22637. this._renderEffects[renderEffectName]._attachCameras(_cam);
  22638. }
  22639. };
  22640. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  22641. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  22642. for (var renderEffectName in this._renderEffects) {
  22643. this._renderEffects[renderEffectName]._detachCameras(_cam);
  22644. }
  22645. for (var i = 0; i < _cam.length; i++) {
  22646. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  22647. }
  22648. };
  22649. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  22650. var _this = this;
  22651. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  22652. var pass = null;
  22653. for (var renderEffectName in this._renderEffects) {
  22654. pass = this._renderEffects[renderEffectName].getPass(passName);
  22655. if (pass != null) {
  22656. break;
  22657. }
  22658. }
  22659. if (pass === null) {
  22660. return;
  22661. }
  22662. for (var renderEffectName in this._renderEffects) {
  22663. this._renderEffects[renderEffectName]._disable(_cam);
  22664. }
  22665. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  22666. for (var i = 0; i < _cam.length; i++) {
  22667. var camera = _cam[i];
  22668. var cameraName = camera.name;
  22669. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  22670. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  22671. });
  22672. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  22673. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  22674. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  22675. }
  22676. };
  22677. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  22678. var _this = this;
  22679. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  22680. for (var i = 0; i < _cam.length; i++) {
  22681. var camera = _cam[i];
  22682. var cameraName = camera.name;
  22683. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  22684. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  22685. });
  22686. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  22687. }
  22688. for (var renderEffectName in this._renderEffects) {
  22689. this._renderEffects[renderEffectName]._enable(_cam);
  22690. }
  22691. };
  22692. PostProcessRenderPipeline.prototype._update = function () {
  22693. for (var renderEffectName in this._renderEffects) {
  22694. this._renderEffects[renderEffectName]._update();
  22695. }
  22696. for (var i = 0; i < this._cameras.length; i++) {
  22697. var cameraName = this._cameras[i].name;
  22698. if (this._renderEffectsForIsolatedPass[cameraName]) {
  22699. this._renderEffectsForIsolatedPass[cameraName]._update();
  22700. }
  22701. }
  22702. };
  22703. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  22704. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  22705. return PostProcessRenderPipeline;
  22706. })();
  22707. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  22708. })(BABYLON || (BABYLON = {}));
  22709. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.mapvar BABYLON;
  22710. (function (BABYLON) {
  22711. var PostProcessRenderPipelineManager = (function () {
  22712. function PostProcessRenderPipelineManager() {
  22713. this._renderPipelines = {};
  22714. }
  22715. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  22716. this._renderPipelines[renderPipeline._name] = renderPipeline;
  22717. };
  22718. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  22719. var renderPipeline = this._renderPipelines[renderPipelineName];
  22720. if (!renderPipeline) {
  22721. return;
  22722. }
  22723. renderPipeline._attachCameras(cameras, unique);
  22724. };
  22725. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  22726. var renderPipeline = this._renderPipelines[renderPipelineName];
  22727. if (!renderPipeline) {
  22728. return;
  22729. }
  22730. renderPipeline._detachCameras(cameras);
  22731. };
  22732. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  22733. var renderPipeline = this._renderPipelines[renderPipelineName];
  22734. if (!renderPipeline) {
  22735. return;
  22736. }
  22737. renderPipeline._enableEffect(renderEffectName, cameras);
  22738. };
  22739. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  22740. var renderPipeline = this._renderPipelines[renderPipelineName];
  22741. if (!renderPipeline) {
  22742. return;
  22743. }
  22744. renderPipeline._disableEffect(renderEffectName, cameras);
  22745. };
  22746. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  22747. var renderPipeline = this._renderPipelines[renderPipelineName];
  22748. if (!renderPipeline) {
  22749. return;
  22750. }
  22751. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  22752. };
  22753. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  22754. var renderPipeline = this._renderPipelines[renderPipelineName];
  22755. if (!renderPipeline) {
  22756. return;
  22757. }
  22758. renderPipeline._disableDisplayOnlyPass(cameras);
  22759. };
  22760. PostProcessRenderPipelineManager.prototype.update = function () {
  22761. for (var renderPipelineName in this._renderPipelines) {
  22762. this._renderPipelines[renderPipelineName]._update();
  22763. }
  22764. };
  22765. return PostProcessRenderPipelineManager;
  22766. })();
  22767. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  22768. })(BABYLON || (BABYLON = {}));
  22769. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  22770. var BABYLON;
  22771. (function (BABYLON) {
  22772. var DisplayPassPostProcess = (function (_super) {
  22773. __extends(DisplayPassPostProcess, _super);
  22774. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  22775. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  22776. }
  22777. return DisplayPassPostProcess;
  22778. })(BABYLON.PostProcess);
  22779. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  22780. })(BABYLON || (BABYLON = {}));
  22781. //# sourceMappingURL=babylon.displayPassPostProcess.js.mapvar BABYLON;
  22782. (function (BABYLON) {
  22783. var BoundingBoxRenderer = (function () {
  22784. function BoundingBoxRenderer(scene) {
  22785. this.frontColor = new BABYLON.Color3(1, 1, 1);
  22786. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  22787. this.showBackLines = true;
  22788. this.renderList = new BABYLON.SmartArray(32);
  22789. this._scene = scene;
  22790. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  22791. attributes: ["position"],
  22792. uniforms: ["worldViewProjection", "color"]
  22793. });
  22794. var engine = this._scene.getEngine();
  22795. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  22796. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  22797. 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]);
  22798. }
  22799. BoundingBoxRenderer.prototype.reset = function () {
  22800. this.renderList.reset();
  22801. };
  22802. BoundingBoxRenderer.prototype.render = function () {
  22803. if (this.renderList.length === 0 || !this._colorShader.isReady()) {
  22804. return;
  22805. }
  22806. var engine = this._scene.getEngine();
  22807. engine.setDepthWrite(false);
  22808. this._colorShader._preBind();
  22809. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  22810. var boundingBox = this.renderList.data[boundingBoxIndex];
  22811. var min = boundingBox.minimum;
  22812. var max = boundingBox.maximum;
  22813. var diff = max.subtract(min);
  22814. var median = min.add(diff.scale(0.5));
  22815. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z).multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z)).multiply(boundingBox.getWorldMatrix());
  22816. // VBOs
  22817. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  22818. if (this.showBackLines) {
  22819. // Back
  22820. engine.setDepthFunctionToGreaterOrEqual();
  22821. this._scene.resetCachedMaterial();
  22822. this._colorShader.setColor4("color", this.backColor.toColor4());
  22823. this._colorShader.bind(worldMatrix);
  22824. // Draw order
  22825. engine.draw(false, 0, 24);
  22826. }
  22827. // Front
  22828. engine.setDepthFunctionToLess();
  22829. this._scene.resetCachedMaterial();
  22830. this._colorShader.setColor4("color", this.frontColor.toColor4());
  22831. this._colorShader.bind(worldMatrix);
  22832. // Draw order
  22833. engine.draw(false, 0, 24);
  22834. }
  22835. this._colorShader.unbind();
  22836. engine.setDepthFunctionToLessOrEqual();
  22837. engine.setDepthWrite(true);
  22838. };
  22839. BoundingBoxRenderer.prototype.dispose = function () {
  22840. this._colorShader.dispose();
  22841. this._vb.dispose();
  22842. this._scene.getEngine()._releaseBuffer(this._ib);
  22843. };
  22844. return BoundingBoxRenderer;
  22845. })();
  22846. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  22847. })(BABYLON || (BABYLON = {}));
  22848. //# sourceMappingURL=babylon.boundingBoxRenderer.js.mapvar BABYLON;
  22849. (function (BABYLON) {
  22850. var Internals;
  22851. (function (Internals) {
  22852. /*
  22853. * Based on jsTGALoader - Javascript loader for TGA file
  22854. * By Vincent Thibault
  22855. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  22856. */
  22857. var TGATools = (function () {
  22858. function TGATools() {
  22859. }
  22860. TGATools.GetTGAHeader = function (data) {
  22861. var offset = 0;
  22862. var header = {
  22863. id_length: data[offset++],
  22864. colormap_type: data[offset++],
  22865. image_type: data[offset++],
  22866. colormap_index: data[offset++] | data[offset++] << 8,
  22867. colormap_length: data[offset++] | data[offset++] << 8,
  22868. colormap_size: data[offset++],
  22869. origin: [
  22870. data[offset++] | data[offset++] << 8,
  22871. data[offset++] | data[offset++] << 8
  22872. ],
  22873. width: data[offset++] | data[offset++] << 8,
  22874. height: data[offset++] | data[offset++] << 8,
  22875. pixel_size: data[offset++],
  22876. flags: data[offset++]
  22877. };
  22878. return header;
  22879. };
  22880. TGATools.UploadContent = function (gl, data) {
  22881. // Not enough data to contain header ?
  22882. if (data.length < 19) {
  22883. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  22884. return;
  22885. }
  22886. // Read Header
  22887. var offset = 18;
  22888. var header = TGATools.GetTGAHeader(data);
  22889. // Assume it's a valid Targa file.
  22890. if (header.id_length + offset > data.length) {
  22891. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  22892. return;
  22893. }
  22894. // Skip not needed data
  22895. offset += header.id_length;
  22896. var use_rle = false;
  22897. var use_pal = false;
  22898. var use_rgb = false;
  22899. var use_grey = false;
  22900. switch (header.image_type) {
  22901. case TGATools._TYPE_RLE_INDEXED:
  22902. use_rle = true;
  22903. case TGATools._TYPE_INDEXED:
  22904. use_pal = true;
  22905. break;
  22906. case TGATools._TYPE_RLE_RGB:
  22907. use_rle = true;
  22908. case TGATools._TYPE_RGB:
  22909. use_rgb = true;
  22910. break;
  22911. case TGATools._TYPE_RLE_GREY:
  22912. use_rle = true;
  22913. case TGATools._TYPE_GREY:
  22914. use_grey = true;
  22915. break;
  22916. }
  22917. var pixel_data;
  22918. var numAlphaBits = header.flags & 0xf;
  22919. var pixel_size = header.pixel_size >> 3;
  22920. var pixel_total = header.width * header.height * pixel_size;
  22921. // Read palettes
  22922. var palettes;
  22923. if (use_pal) {
  22924. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  22925. }
  22926. // Read LRE
  22927. if (use_rle) {
  22928. pixel_data = new Uint8Array(pixel_total);
  22929. var c, count, i;
  22930. var localOffset = 0;
  22931. var pixels = new Uint8Array(pixel_size);
  22932. while (offset < pixel_total && localOffset < pixel_total) {
  22933. c = data[offset++];
  22934. count = (c & 0x7f) + 1;
  22935. // RLE pixels
  22936. if (c & 0x80) {
  22937. for (i = 0; i < pixel_size; ++i) {
  22938. pixels[i] = data[offset++];
  22939. }
  22940. for (i = 0; i < count; ++i) {
  22941. pixel_data.set(pixels, localOffset + i * pixel_size);
  22942. }
  22943. localOffset += pixel_size * count;
  22944. }
  22945. else {
  22946. count *= pixel_size;
  22947. for (i = 0; i < count; ++i) {
  22948. pixel_data[localOffset + i] = data[offset++];
  22949. }
  22950. localOffset += count;
  22951. }
  22952. }
  22953. }
  22954. else {
  22955. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  22956. }
  22957. // Load to texture
  22958. var x_start, y_start, x_step, y_step, y_end, x_end;
  22959. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  22960. default:
  22961. case TGATools._ORIGIN_UL:
  22962. x_start = 0;
  22963. x_step = 1;
  22964. x_end = header.width;
  22965. y_start = 0;
  22966. y_step = 1;
  22967. y_end = header.height;
  22968. break;
  22969. case TGATools._ORIGIN_BL:
  22970. x_start = 0;
  22971. x_step = 1;
  22972. x_end = header.width;
  22973. y_start = header.height - 1;
  22974. y_step = -1;
  22975. y_end = -1;
  22976. break;
  22977. case TGATools._ORIGIN_UR:
  22978. x_start = header.width - 1;
  22979. x_step = -1;
  22980. x_end = -1;
  22981. y_start = 0;
  22982. y_step = 1;
  22983. y_end = header.height;
  22984. break;
  22985. case TGATools._ORIGIN_BR:
  22986. x_start = header.width - 1;
  22987. x_step = -1;
  22988. x_end = -1;
  22989. y_start = header.height - 1;
  22990. y_step = -1;
  22991. y_end = -1;
  22992. break;
  22993. }
  22994. // Load the specify method
  22995. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  22996. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  22997. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  22998. };
  22999. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  23000. var image = pixel_data, colormap = palettes;
  23001. var width = header.width, height = header.height;
  23002. var color, i = 0, x, y;
  23003. var imageData = new Uint8Array(width * height * 4);
  23004. for (y = y_start; y !== y_end; y += y_step) {
  23005. for (x = x_start; x !== x_end; x += x_step, i++) {
  23006. color = image[i];
  23007. imageData[(x + width * y) * 4 + 3] = 255;
  23008. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  23009. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  23010. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  23011. }
  23012. }
  23013. return imageData;
  23014. };
  23015. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  23016. var image = pixel_data;
  23017. var width = header.width, height = header.height;
  23018. var color, i = 0, x, y;
  23019. var imageData = new Uint8Array(width * height * 4);
  23020. for (y = y_start; y !== y_end; y += y_step) {
  23021. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  23022. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  23023. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  23024. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  23025. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  23026. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  23027. }
  23028. }
  23029. return imageData;
  23030. };
  23031. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  23032. var image = pixel_data;
  23033. var width = header.width, height = header.height;
  23034. var i = 0, x, y;
  23035. var imageData = new Uint8Array(width * height * 4);
  23036. for (y = y_start; y !== y_end; y += y_step) {
  23037. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  23038. imageData[(x + width * y) * 4 + 3] = 255;
  23039. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  23040. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  23041. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  23042. }
  23043. }
  23044. return imageData;
  23045. };
  23046. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  23047. var image = pixel_data;
  23048. var width = header.width, height = header.height;
  23049. var i = 0, x, y;
  23050. var imageData = new Uint8Array(width * height * 4);
  23051. for (y = y_start; y !== y_end; y += y_step) {
  23052. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  23053. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  23054. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  23055. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  23056. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  23057. }
  23058. }
  23059. return imageData;
  23060. };
  23061. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  23062. var image = pixel_data;
  23063. var width = header.width, height = header.height;
  23064. var color, i = 0, x, y;
  23065. var imageData = new Uint8Array(width * height * 4);
  23066. for (y = y_start; y !== y_end; y += y_step) {
  23067. for (x = x_start; x !== x_end; x += x_step, i++) {
  23068. color = image[i];
  23069. imageData[(x + width * y) * 4 + 0] = color;
  23070. imageData[(x + width * y) * 4 + 1] = color;
  23071. imageData[(x + width * y) * 4 + 2] = color;
  23072. imageData[(x + width * y) * 4 + 3] = 255;
  23073. }
  23074. }
  23075. return imageData;
  23076. };
  23077. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  23078. var image = pixel_data;
  23079. var width = header.width, height = header.height;
  23080. var i = 0, x, y;
  23081. var imageData = new Uint8Array(width * height * 4);
  23082. for (y = y_start; y !== y_end; y += y_step) {
  23083. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  23084. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  23085. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  23086. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  23087. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  23088. }
  23089. }
  23090. return imageData;
  23091. };
  23092. TGATools._TYPE_NO_DATA = 0;
  23093. TGATools._TYPE_INDEXED = 1;
  23094. TGATools._TYPE_RGB = 2;
  23095. TGATools._TYPE_GREY = 3;
  23096. TGATools._TYPE_RLE_INDEXED = 9;
  23097. TGATools._TYPE_RLE_RGB = 10;
  23098. TGATools._TYPE_RLE_GREY = 11;
  23099. TGATools._ORIGIN_MASK = 0x30;
  23100. TGATools._ORIGIN_SHIFT = 0x04;
  23101. TGATools._ORIGIN_BL = 0x00;
  23102. TGATools._ORIGIN_BR = 0x01;
  23103. TGATools._ORIGIN_UL = 0x02;
  23104. TGATools._ORIGIN_UR = 0x03;
  23105. return TGATools;
  23106. })();
  23107. Internals.TGATools = TGATools;
  23108. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  23109. })(BABYLON || (BABYLON = {}));
  23110. //# sourceMappingURL=babylon.tools.tga.js.mapvar BABYLON;
  23111. (function (BABYLON) {
  23112. var Internals;
  23113. (function (Internals) {
  23114. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  23115. // All values and structures referenced from:
  23116. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  23117. var DDS_MAGIC = 0x20534444;
  23118. 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;
  23119. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  23120. 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;
  23121. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  23122. function FourCCToInt32(value) {
  23123. return value.charCodeAt(0) + (value.charCodeAt(1) << 8) + (value.charCodeAt(2) << 16) + (value.charCodeAt(3) << 24);
  23124. }
  23125. function Int32ToFourCC(value) {
  23126. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  23127. }
  23128. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  23129. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  23130. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  23131. var headerLengthInt = 31; // The header length in 32 bit ints
  23132. // Offsets into the header array
  23133. var off_magic = 0;
  23134. var off_size = 1;
  23135. var off_flags = 2;
  23136. var off_height = 3;
  23137. var off_width = 4;
  23138. var off_mipmapCount = 7;
  23139. var off_pfFlags = 20;
  23140. var off_pfFourCC = 21;
  23141. var off_RGBbpp = 22;
  23142. var off_RMask = 23;
  23143. var off_GMask = 24;
  23144. var off_BMask = 25;
  23145. var off_AMask = 26;
  23146. var off_caps1 = 27;
  23147. var off_caps2 = 28;
  23148. ;
  23149. var DDSTools = (function () {
  23150. function DDSTools() {
  23151. }
  23152. DDSTools.GetDDSInfo = function (arrayBuffer) {
  23153. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  23154. var mipmapCount = 1;
  23155. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  23156. mipmapCount = Math.max(1, header[off_mipmapCount]);
  23157. }
  23158. return {
  23159. width: header[off_width],
  23160. height: header[off_height],
  23161. mipmapCount: mipmapCount,
  23162. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  23163. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  23164. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  23165. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  23166. };
  23167. };
  23168. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  23169. var byteArray = new Uint8Array(dataLength);
  23170. var srcData = new Uint8Array(arrayBuffer);
  23171. var index = 0;
  23172. for (var y = height - 1; y >= 0; y--) {
  23173. for (var x = 0; x < width; x++) {
  23174. var srcPos = dataOffset + (x + y * width) * 4;
  23175. byteArray[index + 2] = srcData[srcPos];
  23176. byteArray[index + 1] = srcData[srcPos + 1];
  23177. byteArray[index] = srcData[srcPos + 2];
  23178. byteArray[index + 3] = srcData[srcPos + 3];
  23179. index += 4;
  23180. }
  23181. }
  23182. return byteArray;
  23183. };
  23184. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  23185. var byteArray = new Uint8Array(dataLength);
  23186. var srcData = new Uint8Array(arrayBuffer);
  23187. var index = 0;
  23188. for (var y = height - 1; y >= 0; y--) {
  23189. for (var x = 0; x < width; x++) {
  23190. var srcPos = dataOffset + (x + y * width) * 3;
  23191. byteArray[index + 2] = srcData[srcPos];
  23192. byteArray[index + 1] = srcData[srcPos + 1];
  23193. byteArray[index] = srcData[srcPos + 2];
  23194. index += 3;
  23195. }
  23196. }
  23197. return byteArray;
  23198. };
  23199. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  23200. var byteArray = new Uint8Array(dataLength);
  23201. var srcData = new Uint8Array(arrayBuffer);
  23202. var index = 0;
  23203. for (var y = height - 1; y >= 0; y--) {
  23204. for (var x = 0; x < width; x++) {
  23205. var srcPos = dataOffset + (x + y * width);
  23206. byteArray[index] = srcData[srcPos];
  23207. index++;
  23208. }
  23209. }
  23210. return byteArray;
  23211. };
  23212. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  23213. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  23214. if (header[off_magic] != DDS_MAGIC) {
  23215. BABYLON.Tools.Error("Invalid magic number in DDS header");
  23216. return;
  23217. }
  23218. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  23219. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  23220. return;
  23221. }
  23222. if (info.isFourCC) {
  23223. fourCC = header[off_pfFourCC];
  23224. switch (fourCC) {
  23225. case FOURCC_DXT1:
  23226. blockBytes = 8;
  23227. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  23228. break;
  23229. case FOURCC_DXT3:
  23230. blockBytes = 16;
  23231. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  23232. break;
  23233. case FOURCC_DXT5:
  23234. blockBytes = 16;
  23235. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  23236. break;
  23237. default:
  23238. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  23239. return;
  23240. }
  23241. }
  23242. mipmapCount = 1;
  23243. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  23244. mipmapCount = Math.max(1, header[off_mipmapCount]);
  23245. }
  23246. var bpp = header[off_RGBbpp];
  23247. for (var face = 0; face < faces; face++) {
  23248. var sampler = faces == 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  23249. width = header[off_width];
  23250. height = header[off_height];
  23251. dataOffset = header[off_size] + 4;
  23252. for (i = 0; i < mipmapCount; ++i) {
  23253. if (info.isRGB) {
  23254. if (bpp == 24) {
  23255. dataLength = width * height * 3;
  23256. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  23257. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  23258. }
  23259. else {
  23260. dataLength = width * height * 4;
  23261. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  23262. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  23263. }
  23264. }
  23265. else if (info.isLuminance) {
  23266. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  23267. var unpaddedRowSize = width;
  23268. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  23269. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  23270. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  23271. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  23272. }
  23273. else {
  23274. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  23275. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  23276. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  23277. }
  23278. dataOffset += dataLength;
  23279. width *= 0.5;
  23280. height *= 0.5;
  23281. width = Math.max(1.0, width);
  23282. height = Math.max(1.0, height);
  23283. }
  23284. }
  23285. };
  23286. return DDSTools;
  23287. })();
  23288. Internals.DDSTools = DDSTools;
  23289. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  23290. })(BABYLON || (BABYLON = {}));
  23291. //# sourceMappingURL=babylon.tools.dds.js.mapvar BABYLON;
  23292. (function (BABYLON) {
  23293. var SmartArray = (function () {
  23294. function SmartArray(capacity) {
  23295. this.length = 0;
  23296. this._duplicateId = 0;
  23297. this.data = new Array(capacity);
  23298. this._id = SmartArray._GlobalId++;
  23299. }
  23300. SmartArray.prototype.push = function (value) {
  23301. this.data[this.length++] = value;
  23302. if (this.length > this.data.length) {
  23303. this.data.length *= 2;
  23304. }
  23305. if (!value.__smartArrayFlags) {
  23306. value.__smartArrayFlags = {};
  23307. }
  23308. value.__smartArrayFlags[this._id] = this._duplicateId;
  23309. };
  23310. SmartArray.prototype.pushNoDuplicate = function (value) {
  23311. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  23312. return;
  23313. }
  23314. this.push(value);
  23315. };
  23316. SmartArray.prototype.sort = function (compareFn) {
  23317. this.data.sort(compareFn);
  23318. };
  23319. SmartArray.prototype.reset = function () {
  23320. this.length = 0;
  23321. this._duplicateId++;
  23322. };
  23323. SmartArray.prototype.concat = function (array) {
  23324. if (array.length === 0) {
  23325. return;
  23326. }
  23327. if (this.length + array.length > this.data.length) {
  23328. this.data.length = (this.length + array.length) * 2;
  23329. }
  23330. for (var index = 0; index < array.length; index++) {
  23331. this.data[this.length++] = (array.data || array)[index];
  23332. }
  23333. };
  23334. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  23335. if (array.length === 0) {
  23336. return;
  23337. }
  23338. if (this.length + array.length > this.data.length) {
  23339. this.data.length = (this.length + array.length) * 2;
  23340. }
  23341. for (var index = 0; index < array.length; index++) {
  23342. var item = (array.data || array)[index];
  23343. this.pushNoDuplicate(item);
  23344. }
  23345. };
  23346. SmartArray.prototype.indexOf = function (value) {
  23347. var position = this.data.indexOf(value);
  23348. if (position >= this.length) {
  23349. return -1;
  23350. }
  23351. return position;
  23352. };
  23353. // Statics
  23354. SmartArray._GlobalId = 0;
  23355. return SmartArray;
  23356. })();
  23357. BABYLON.SmartArray = SmartArray;
  23358. })(BABYLON || (BABYLON = {}));
  23359. //# sourceMappingURL=babylon.smartArray.js.mapvar BABYLON;
  23360. (function (BABYLON) {
  23361. var CannonJSPlugin = (function () {
  23362. function CannonJSPlugin() {
  23363. this._registeredMeshes = [];
  23364. this._physicsMaterials = [];
  23365. this.updateBodyPosition = function (mesh) {
  23366. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23367. var registeredMesh = this._registeredMeshes[index];
  23368. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  23369. var body = registeredMesh.body;
  23370. var center = mesh.getBoundingInfo().boundingBox.center;
  23371. body.position.set(center.x, center.z, center.y);
  23372. body.quaternion.x = mesh.rotationQuaternion.x;
  23373. body.quaternion.z = mesh.rotationQuaternion.y;
  23374. body.quaternion.y = mesh.rotationQuaternion.z;
  23375. body.quaternion.w = -mesh.rotationQuaternion.w;
  23376. return;
  23377. }
  23378. }
  23379. };
  23380. }
  23381. CannonJSPlugin.prototype.initialize = function (iterations) {
  23382. if (iterations === void 0) { iterations = 10; }
  23383. this._world = new CANNON.World();
  23384. this._world.broadphase = new CANNON.NaiveBroadphase();
  23385. this._world.solver.iterations = iterations;
  23386. };
  23387. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  23388. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  23389. };
  23390. CannonJSPlugin.prototype.runOneStep = function (delta) {
  23391. this._world.step(delta);
  23392. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23393. var registeredMesh = this._registeredMeshes[index];
  23394. if (registeredMesh.isChild) {
  23395. continue;
  23396. }
  23397. // Body position
  23398. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  23399. var deltaPos = registeredMesh.delta;
  23400. if (deltaPos) {
  23401. registeredMesh.mesh.position.x = bodyX + deltaPos.x;
  23402. registeredMesh.mesh.position.y = bodyZ + deltaPos.y;
  23403. registeredMesh.mesh.position.z = bodyY + deltaPos.z;
  23404. }
  23405. else {
  23406. registeredMesh.mesh.position.x = bodyX;
  23407. registeredMesh.mesh.position.y = bodyZ;
  23408. registeredMesh.mesh.position.z = bodyY;
  23409. }
  23410. if (!registeredMesh.mesh.rotationQuaternion) {
  23411. registeredMesh.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  23412. }
  23413. registeredMesh.mesh.rotationQuaternion.x = registeredMesh.body.quaternion.x;
  23414. registeredMesh.mesh.rotationQuaternion.y = registeredMesh.body.quaternion.z;
  23415. registeredMesh.mesh.rotationQuaternion.z = registeredMesh.body.quaternion.y;
  23416. registeredMesh.mesh.rotationQuaternion.w = -registeredMesh.body.quaternion.w;
  23417. }
  23418. };
  23419. CannonJSPlugin.prototype.setGravity = function (gravity) {
  23420. this._world.gravity.set(gravity.x, gravity.z, gravity.y);
  23421. };
  23422. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  23423. this.unregisterMesh(mesh);
  23424. mesh.computeWorldMatrix(true);
  23425. switch (impostor) {
  23426. case BABYLON.PhysicsEngine.SphereImpostor:
  23427. var bbox = mesh.getBoundingInfo().boundingBox;
  23428. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  23429. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  23430. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  23431. return this._createSphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2, mesh, options);
  23432. case BABYLON.PhysicsEngine.BoxImpostor:
  23433. bbox = mesh.getBoundingInfo().boundingBox;
  23434. var min = bbox.minimumWorld;
  23435. var max = bbox.maximumWorld;
  23436. var box = max.subtract(min).scale(0.5);
  23437. return this._createBox(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z), mesh, options);
  23438. case BABYLON.PhysicsEngine.PlaneImpostor:
  23439. return this._createPlane(mesh, options);
  23440. case BABYLON.PhysicsEngine.MeshImpostor:
  23441. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23442. var rawFaces = mesh.getIndices();
  23443. return this._createConvexPolyhedron(rawVerts, rawFaces, mesh, options);
  23444. }
  23445. return null;
  23446. };
  23447. CannonJSPlugin.prototype._createSphere = function (radius, mesh, options) {
  23448. var shape = new CANNON.Sphere(radius);
  23449. if (!options) {
  23450. return shape;
  23451. }
  23452. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  23453. };
  23454. CannonJSPlugin.prototype._createBox = function (x, y, z, mesh, options) {
  23455. var shape = new CANNON.Box(new CANNON.Vec3(x, z, y));
  23456. if (!options) {
  23457. return shape;
  23458. }
  23459. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  23460. };
  23461. CannonJSPlugin.prototype._createPlane = function (mesh, options) {
  23462. var shape = new CANNON.Plane();
  23463. if (!options) {
  23464. return shape;
  23465. }
  23466. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  23467. };
  23468. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh, options) {
  23469. var verts = [], faces = [];
  23470. mesh.computeWorldMatrix(true);
  23471. for (var i = 0; i < rawVerts.length; i += 3) {
  23472. var transformed = BABYLON.Vector3.Zero();
  23473. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  23474. verts.push(new CANNON.Vec3(transformed.x, transformed.z, transformed.y));
  23475. }
  23476. for (var j = 0; j < rawFaces.length; j += 3) {
  23477. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  23478. }
  23479. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  23480. if (!options) {
  23481. return shape;
  23482. }
  23483. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  23484. };
  23485. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  23486. var index;
  23487. var mat;
  23488. for (index = 0; index < this._physicsMaterials.length; index++) {
  23489. mat = this._physicsMaterials[index];
  23490. if (mat.friction === friction && mat.restitution === restitution) {
  23491. return mat;
  23492. }
  23493. }
  23494. var currentMat = new CANNON.Material();
  23495. currentMat.friction = friction;
  23496. currentMat.restitution = restitution;
  23497. this._physicsMaterials.push(currentMat);
  23498. for (index = 0; index < this._physicsMaterials.length; index++) {
  23499. mat = this._physicsMaterials[index];
  23500. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, mat.friction * currentMat.friction, mat.restitution * currentMat.restitution);
  23501. contactMaterial.contactEquationStiffness = 1e10;
  23502. contactMaterial.contactEquationRegularizationTime = 10;
  23503. this._world.addContactMaterial(contactMaterial);
  23504. }
  23505. return currentMat;
  23506. };
  23507. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, mass, friction, restitution) {
  23508. var initialRotation = null;
  23509. if (mesh.rotationQuaternion) {
  23510. initialRotation = mesh.rotationQuaternion.clone();
  23511. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  23512. }
  23513. // The delta between the mesh position and the mesh bounding box center
  23514. var bbox = mesh.getBoundingInfo().boundingBox;
  23515. var deltaPosition = mesh.position.subtract(bbox.center);
  23516. var material = this._addMaterial(friction, restitution);
  23517. var body = new CANNON.RigidBody(mass, shape, material);
  23518. if (initialRotation) {
  23519. body.quaternion.x = initialRotation.x;
  23520. body.quaternion.z = initialRotation.y;
  23521. body.quaternion.y = initialRotation.z;
  23522. body.quaternion.w = -initialRotation.w;
  23523. }
  23524. body.position.set(bbox.center.x, bbox.center.z, bbox.center.y);
  23525. this._world.add(body);
  23526. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition });
  23527. return body;
  23528. };
  23529. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  23530. var compoundShape = new CANNON.Compound();
  23531. for (var index = 0; index < parts.length; index++) {
  23532. var mesh = parts[index].mesh;
  23533. var shape = this.registerMesh(mesh, parts[index].impostor);
  23534. if (index == 0) {
  23535. compoundShape.addChild(shape, new CANNON.Vec3(0, 0, 0));
  23536. }
  23537. else {
  23538. compoundShape.addChild(shape, new CANNON.Vec3(mesh.position.x, mesh.position.z, mesh.position.y));
  23539. }
  23540. }
  23541. var initialMesh = parts[0].mesh;
  23542. var body = this._createRigidBodyFromShape(compoundShape, initialMesh, options.mass, options.friction, options.restitution);
  23543. body.parts = parts;
  23544. return body;
  23545. };
  23546. CannonJSPlugin.prototype._unbindBody = function (body) {
  23547. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23548. var registeredMesh = this._registeredMeshes[index];
  23549. if (registeredMesh.body === body) {
  23550. registeredMesh.body = null;
  23551. registeredMesh.delta = 0;
  23552. }
  23553. }
  23554. };
  23555. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  23556. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23557. var registeredMesh = this._registeredMeshes[index];
  23558. if (registeredMesh.mesh === mesh) {
  23559. // Remove body
  23560. if (registeredMesh.body) {
  23561. this._world.remove(registeredMesh.body);
  23562. this._unbindBody(registeredMesh.body);
  23563. }
  23564. this._registeredMeshes.splice(index, 1);
  23565. return;
  23566. }
  23567. }
  23568. };
  23569. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  23570. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.z, contactPoint.y);
  23571. var impulse = new CANNON.Vec3(force.x, force.z, force.y);
  23572. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23573. var registeredMesh = this._registeredMeshes[index];
  23574. if (registeredMesh.mesh === mesh) {
  23575. registeredMesh.body.applyImpulse(impulse, worldPoint);
  23576. return;
  23577. }
  23578. }
  23579. };
  23580. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  23581. var body1 = null, body2 = null;
  23582. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23583. var registeredMesh = this._registeredMeshes[index];
  23584. if (registeredMesh.mesh === mesh1) {
  23585. body1 = registeredMesh.body;
  23586. }
  23587. else if (registeredMesh.mesh === mesh2) {
  23588. body2 = registeredMesh.body;
  23589. }
  23590. }
  23591. if (!body1 || !body2) {
  23592. return false;
  23593. }
  23594. 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));
  23595. this._world.addConstraint(constraint);
  23596. return true;
  23597. };
  23598. CannonJSPlugin.prototype.dispose = function () {
  23599. while (this._registeredMeshes.length) {
  23600. this.unregisterMesh(this._registeredMeshes[0].mesh);
  23601. }
  23602. };
  23603. CannonJSPlugin.prototype.isSupported = function () {
  23604. return window.CANNON !== undefined;
  23605. };
  23606. return CannonJSPlugin;
  23607. })();
  23608. BABYLON.CannonJSPlugin = CannonJSPlugin;
  23609. })(BABYLON || (BABYLON = {}));
  23610. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  23611. var BABYLON;
  23612. (function (BABYLON) {
  23613. var Condition = (function () {
  23614. function Condition(actionManager) {
  23615. this._actionManager = actionManager;
  23616. }
  23617. Condition.prototype.isValid = function () {
  23618. return true;
  23619. };
  23620. Condition.prototype._getProperty = function (propertyPath) {
  23621. return this._actionManager._getProperty(propertyPath);
  23622. };
  23623. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  23624. return this._actionManager._getEffectiveTarget(target, propertyPath);
  23625. };
  23626. return Condition;
  23627. })();
  23628. BABYLON.Condition = Condition;
  23629. var ValueCondition = (function (_super) {
  23630. __extends(ValueCondition, _super);
  23631. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  23632. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  23633. _super.call(this, actionManager);
  23634. this.propertyPath = propertyPath;
  23635. this.value = value;
  23636. this.operator = operator;
  23637. this._target = this._getEffectiveTarget(target, this.propertyPath);
  23638. this._property = this._getProperty(this.propertyPath);
  23639. }
  23640. Object.defineProperty(ValueCondition, "IsEqual", {
  23641. get: function () {
  23642. return ValueCondition._IsEqual;
  23643. },
  23644. enumerable: true,
  23645. configurable: true
  23646. });
  23647. Object.defineProperty(ValueCondition, "IsDifferent", {
  23648. get: function () {
  23649. return ValueCondition._IsDifferent;
  23650. },
  23651. enumerable: true,
  23652. configurable: true
  23653. });
  23654. Object.defineProperty(ValueCondition, "IsGreater", {
  23655. get: function () {
  23656. return ValueCondition._IsGreater;
  23657. },
  23658. enumerable: true,
  23659. configurable: true
  23660. });
  23661. Object.defineProperty(ValueCondition, "IsLesser", {
  23662. get: function () {
  23663. return ValueCondition._IsLesser;
  23664. },
  23665. enumerable: true,
  23666. configurable: true
  23667. });
  23668. // Methods
  23669. ValueCondition.prototype.isValid = function () {
  23670. switch (this.operator) {
  23671. case ValueCondition.IsGreater:
  23672. return this._target[this._property] > this.value;
  23673. case ValueCondition.IsLesser:
  23674. return this._target[this._property] < this.value;
  23675. case ValueCondition.IsEqual:
  23676. case ValueCondition.IsDifferent:
  23677. var check;
  23678. if (this.value.equals) {
  23679. check = this.value.equals(this._target[this._property]);
  23680. }
  23681. else {
  23682. check = this.value === this._target[this._property];
  23683. }
  23684. return this.operator === ValueCondition.IsEqual ? check : !check;
  23685. }
  23686. return false;
  23687. };
  23688. // Statics
  23689. ValueCondition._IsEqual = 0;
  23690. ValueCondition._IsDifferent = 1;
  23691. ValueCondition._IsGreater = 2;
  23692. ValueCondition._IsLesser = 3;
  23693. return ValueCondition;
  23694. })(Condition);
  23695. BABYLON.ValueCondition = ValueCondition;
  23696. var PredicateCondition = (function (_super) {
  23697. __extends(PredicateCondition, _super);
  23698. function PredicateCondition(actionManager, predicate) {
  23699. _super.call(this, actionManager);
  23700. this.predicate = predicate;
  23701. }
  23702. PredicateCondition.prototype.isValid = function () {
  23703. return this.predicate();
  23704. };
  23705. return PredicateCondition;
  23706. })(Condition);
  23707. BABYLON.PredicateCondition = PredicateCondition;
  23708. var StateCondition = (function (_super) {
  23709. __extends(StateCondition, _super);
  23710. function StateCondition(actionManager, target, value) {
  23711. _super.call(this, actionManager);
  23712. this.value = value;
  23713. this._target = target;
  23714. }
  23715. // Methods
  23716. StateCondition.prototype.isValid = function () {
  23717. return this._target.state === this.value;
  23718. };
  23719. return StateCondition;
  23720. })(Condition);
  23721. BABYLON.StateCondition = StateCondition;
  23722. })(BABYLON || (BABYLON = {}));
  23723. //# sourceMappingURL=babylon.condition.js.mapvar BABYLON;
  23724. (function (BABYLON) {
  23725. var Action = (function () {
  23726. function Action(triggerOptions, condition) {
  23727. this.triggerOptions = triggerOptions;
  23728. if (triggerOptions.parameter) {
  23729. this.trigger = triggerOptions.trigger;
  23730. this._triggerParameter = triggerOptions.parameter;
  23731. }
  23732. else {
  23733. this.trigger = triggerOptions;
  23734. }
  23735. this._nextActiveAction = this;
  23736. this._condition = condition;
  23737. }
  23738. // Methods
  23739. Action.prototype._prepare = function () {
  23740. };
  23741. Action.prototype.getTriggerParameter = function () {
  23742. return this._triggerParameter;
  23743. };
  23744. Action.prototype._executeCurrent = function (evt) {
  23745. if (this._nextActiveAction._condition) {
  23746. var condition = this._nextActiveAction._condition;
  23747. var currentRenderId = this._actionManager.getScene().getRenderId();
  23748. // We cache the current evaluation for the current frame
  23749. if (condition._evaluationId === currentRenderId) {
  23750. if (!condition._currentResult) {
  23751. return;
  23752. }
  23753. }
  23754. else {
  23755. condition._evaluationId = currentRenderId;
  23756. if (!condition.isValid()) {
  23757. condition._currentResult = false;
  23758. return;
  23759. }
  23760. condition._currentResult = true;
  23761. }
  23762. }
  23763. this._nextActiveAction.execute(evt);
  23764. if (this._nextActiveAction._child) {
  23765. if (!this._nextActiveAction._child._actionManager) {
  23766. this._nextActiveAction._child._actionManager = this._actionManager;
  23767. }
  23768. this._nextActiveAction = this._nextActiveAction._child;
  23769. }
  23770. else {
  23771. this._nextActiveAction = this;
  23772. }
  23773. };
  23774. Action.prototype.execute = function (evt) {
  23775. };
  23776. Action.prototype.then = function (action) {
  23777. this._child = action;
  23778. action._actionManager = this._actionManager;
  23779. action._prepare();
  23780. return action;
  23781. };
  23782. Action.prototype._getProperty = function (propertyPath) {
  23783. return this._actionManager._getProperty(propertyPath);
  23784. };
  23785. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  23786. return this._actionManager._getEffectiveTarget(target, propertyPath);
  23787. };
  23788. return Action;
  23789. })();
  23790. BABYLON.Action = Action;
  23791. })(BABYLON || (BABYLON = {}));
  23792. //# sourceMappingURL=babylon.action.js.mapvar BABYLON;
  23793. (function (BABYLON) {
  23794. /**
  23795. * ActionEvent is the event beint sent when an action is triggered.
  23796. */
  23797. var ActionEvent = (function () {
  23798. /**
  23799. * @constructor
  23800. * @param source The mesh that triggered the action.
  23801. * @param pointerX the X mouse cursor position at the time of the event
  23802. * @param pointerY the Y mouse cursor position at the time of the event
  23803. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  23804. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  23805. */
  23806. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent) {
  23807. this.source = source;
  23808. this.pointerX = pointerX;
  23809. this.pointerY = pointerY;
  23810. this.meshUnderPointer = meshUnderPointer;
  23811. this.sourceEvent = sourceEvent;
  23812. }
  23813. /**
  23814. * Helper function to auto-create an ActionEvent from a source mesh.
  23815. * @param source the source mesh that triggered the event
  23816. * @param evt {Event} The original (browser) event
  23817. */
  23818. ActionEvent.CreateNew = function (source, evt) {
  23819. var scene = source.getScene();
  23820. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  23821. };
  23822. /**
  23823. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  23824. * @param scene the scene where the event occurred
  23825. * @param evt {Event} The original (browser) event
  23826. */
  23827. ActionEvent.CreateNewFromScene = function (scene, evt) {
  23828. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  23829. };
  23830. return ActionEvent;
  23831. })();
  23832. BABYLON.ActionEvent = ActionEvent;
  23833. /**
  23834. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  23835. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  23836. */
  23837. var ActionManager = (function () {
  23838. function ActionManager(scene) {
  23839. // Members
  23840. this.actions = new Array();
  23841. this._scene = scene;
  23842. scene._actionManagers.push(this);
  23843. }
  23844. Object.defineProperty(ActionManager, "NothingTrigger", {
  23845. get: function () {
  23846. return ActionManager._NothingTrigger;
  23847. },
  23848. enumerable: true,
  23849. configurable: true
  23850. });
  23851. Object.defineProperty(ActionManager, "OnPickTrigger", {
  23852. get: function () {
  23853. return ActionManager._OnPickTrigger;
  23854. },
  23855. enumerable: true,
  23856. configurable: true
  23857. });
  23858. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  23859. get: function () {
  23860. return ActionManager._OnLeftPickTrigger;
  23861. },
  23862. enumerable: true,
  23863. configurable: true
  23864. });
  23865. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  23866. get: function () {
  23867. return ActionManager._OnRightPickTrigger;
  23868. },
  23869. enumerable: true,
  23870. configurable: true
  23871. });
  23872. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  23873. get: function () {
  23874. return ActionManager._OnCenterPickTrigger;
  23875. },
  23876. enumerable: true,
  23877. configurable: true
  23878. });
  23879. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  23880. get: function () {
  23881. return ActionManager._OnPointerOverTrigger;
  23882. },
  23883. enumerable: true,
  23884. configurable: true
  23885. });
  23886. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  23887. get: function () {
  23888. return ActionManager._OnPointerOutTrigger;
  23889. },
  23890. enumerable: true,
  23891. configurable: true
  23892. });
  23893. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  23894. get: function () {
  23895. return ActionManager._OnEveryFrameTrigger;
  23896. },
  23897. enumerable: true,
  23898. configurable: true
  23899. });
  23900. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  23901. get: function () {
  23902. return ActionManager._OnIntersectionEnterTrigger;
  23903. },
  23904. enumerable: true,
  23905. configurable: true
  23906. });
  23907. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  23908. get: function () {
  23909. return ActionManager._OnIntersectionExitTrigger;
  23910. },
  23911. enumerable: true,
  23912. configurable: true
  23913. });
  23914. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  23915. get: function () {
  23916. return ActionManager._OnKeyDownTrigger;
  23917. },
  23918. enumerable: true,
  23919. configurable: true
  23920. });
  23921. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  23922. get: function () {
  23923. return ActionManager._OnKeyUpTrigger;
  23924. },
  23925. enumerable: true,
  23926. configurable: true
  23927. });
  23928. // Methods
  23929. ActionManager.prototype.dispose = function () {
  23930. var index = this._scene._actionManagers.indexOf(this);
  23931. if (index > -1) {
  23932. this._scene._actionManagers.splice(index, 1);
  23933. }
  23934. };
  23935. ActionManager.prototype.getScene = function () {
  23936. return this._scene;
  23937. };
  23938. /**
  23939. * Does this action manager handles actions of any of the given triggers
  23940. * @param {number[]} triggers - the triggers to be tested
  23941. * @return {boolean} whether one (or more) of the triggers is handeled
  23942. */
  23943. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  23944. for (var index = 0; index < this.actions.length; index++) {
  23945. var action = this.actions[index];
  23946. if (triggers.indexOf(action.trigger) > -1) {
  23947. return true;
  23948. }
  23949. }
  23950. return false;
  23951. };
  23952. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  23953. /**
  23954. * Does this action manager has pointer triggers
  23955. * @return {boolean} whether or not it has pointer triggers
  23956. */
  23957. get: function () {
  23958. for (var index = 0; index < this.actions.length; index++) {
  23959. var action = this.actions[index];
  23960. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  23961. return true;
  23962. }
  23963. }
  23964. return false;
  23965. },
  23966. enumerable: true,
  23967. configurable: true
  23968. });
  23969. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  23970. /**
  23971. * Does this action manager has pick triggers
  23972. * @return {boolean} whether or not it has pick triggers
  23973. */
  23974. get: function () {
  23975. for (var index = 0; index < this.actions.length; index++) {
  23976. var action = this.actions[index];
  23977. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  23978. return true;
  23979. }
  23980. }
  23981. return false;
  23982. },
  23983. enumerable: true,
  23984. configurable: true
  23985. });
  23986. /**
  23987. * Registers an action to this action manager
  23988. * @param {BABYLON.Action} action - the action to be registered
  23989. * @return {BABYLON.Action} the action amended (prepared) after registration
  23990. */
  23991. ActionManager.prototype.registerAction = function (action) {
  23992. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  23993. if (this.getScene().actionManager !== this) {
  23994. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  23995. return null;
  23996. }
  23997. }
  23998. this.actions.push(action);
  23999. action._actionManager = this;
  24000. action._prepare();
  24001. return action;
  24002. };
  24003. /**
  24004. * Process a specific trigger
  24005. * @param {number} trigger - the trigger to process
  24006. * @param evt {BABYLON.ActionEvent} the event details to be processed
  24007. */
  24008. ActionManager.prototype.processTrigger = function (trigger, evt) {
  24009. for (var index = 0; index < this.actions.length; index++) {
  24010. var action = this.actions[index];
  24011. if (action.trigger === trigger) {
  24012. if (trigger === ActionManager.OnKeyUpTrigger || trigger === ActionManager.OnKeyDownTrigger) {
  24013. var parameter = action.getTriggerParameter();
  24014. if (parameter) {
  24015. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  24016. var actualkey = String.fromCharCode(unicode).toLowerCase();
  24017. if (actualkey !== parameter.toLowerCase()) {
  24018. continue;
  24019. }
  24020. }
  24021. }
  24022. action._executeCurrent(evt);
  24023. }
  24024. }
  24025. };
  24026. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  24027. var properties = propertyPath.split(".");
  24028. for (var index = 0; index < properties.length - 1; index++) {
  24029. target = target[properties[index]];
  24030. }
  24031. return target;
  24032. };
  24033. ActionManager.prototype._getProperty = function (propertyPath) {
  24034. var properties = propertyPath.split(".");
  24035. return properties[properties.length - 1];
  24036. };
  24037. // Statics
  24038. ActionManager._NothingTrigger = 0;
  24039. ActionManager._OnPickTrigger = 1;
  24040. ActionManager._OnLeftPickTrigger = 2;
  24041. ActionManager._OnRightPickTrigger = 3;
  24042. ActionManager._OnCenterPickTrigger = 4;
  24043. ActionManager._OnPointerOverTrigger = 5;
  24044. ActionManager._OnPointerOutTrigger = 6;
  24045. ActionManager._OnEveryFrameTrigger = 7;
  24046. ActionManager._OnIntersectionEnterTrigger = 8;
  24047. ActionManager._OnIntersectionExitTrigger = 9;
  24048. ActionManager._OnKeyDownTrigger = 10;
  24049. ActionManager._OnKeyUpTrigger = 11;
  24050. return ActionManager;
  24051. })();
  24052. BABYLON.ActionManager = ActionManager;
  24053. })(BABYLON || (BABYLON = {}));
  24054. //# sourceMappingURL=babylon.actionManager.js.map
  24055. var BABYLON;
  24056. (function (BABYLON) {
  24057. var InterpolateValueAction = (function (_super) {
  24058. __extends(InterpolateValueAction, _super);
  24059. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations) {
  24060. if (duration === void 0) { duration = 1000; }
  24061. _super.call(this, triggerOptions, condition);
  24062. this.propertyPath = propertyPath;
  24063. this.value = value;
  24064. this.duration = duration;
  24065. this.stopOtherAnimations = stopOtherAnimations;
  24066. this._target = target;
  24067. }
  24068. InterpolateValueAction.prototype._prepare = function () {
  24069. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  24070. this._property = this._getProperty(this.propertyPath);
  24071. };
  24072. InterpolateValueAction.prototype.execute = function () {
  24073. var scene = this._actionManager.getScene();
  24074. var keys = [
  24075. {
  24076. frame: 0,
  24077. value: this._target[this._property]
  24078. },
  24079. {
  24080. frame: 100,
  24081. value: this.value
  24082. }
  24083. ];
  24084. var dataType;
  24085. if (typeof this.value === "number") {
  24086. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  24087. }
  24088. else if (this.value instanceof BABYLON.Color3) {
  24089. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  24090. }
  24091. else if (this.value instanceof BABYLON.Vector3) {
  24092. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  24093. }
  24094. else if (this.value instanceof BABYLON.Matrix) {
  24095. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  24096. }
  24097. else if (this.value instanceof BABYLON.Quaternion) {
  24098. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  24099. }
  24100. else {
  24101. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  24102. return;
  24103. }
  24104. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  24105. animation.setKeys(keys);
  24106. if (this.stopOtherAnimations) {
  24107. scene.stopAnimation(this._target);
  24108. }
  24109. scene.beginDirectAnimation(this._target, [animation], 0, 100);
  24110. };
  24111. return InterpolateValueAction;
  24112. })(BABYLON.Action);
  24113. BABYLON.InterpolateValueAction = InterpolateValueAction;
  24114. })(BABYLON || (BABYLON = {}));
  24115. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  24116. var BABYLON;
  24117. (function (BABYLON) {
  24118. var SwitchBooleanAction = (function (_super) {
  24119. __extends(SwitchBooleanAction, _super);
  24120. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  24121. _super.call(this, triggerOptions, condition);
  24122. this.propertyPath = propertyPath;
  24123. this._target = target;
  24124. }
  24125. SwitchBooleanAction.prototype._prepare = function () {
  24126. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  24127. this._property = this._getProperty(this.propertyPath);
  24128. };
  24129. SwitchBooleanAction.prototype.execute = function () {
  24130. this._target[this._property] = !this._target[this._property];
  24131. };
  24132. return SwitchBooleanAction;
  24133. })(BABYLON.Action);
  24134. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  24135. var SetStateAction = (function (_super) {
  24136. __extends(SetStateAction, _super);
  24137. function SetStateAction(triggerOptions, target, value, condition) {
  24138. _super.call(this, triggerOptions, condition);
  24139. this.value = value;
  24140. this._target = target;
  24141. }
  24142. SetStateAction.prototype.execute = function () {
  24143. this._target.state = this.value;
  24144. };
  24145. return SetStateAction;
  24146. })(BABYLON.Action);
  24147. BABYLON.SetStateAction = SetStateAction;
  24148. var SetValueAction = (function (_super) {
  24149. __extends(SetValueAction, _super);
  24150. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  24151. _super.call(this, triggerOptions, condition);
  24152. this.propertyPath = propertyPath;
  24153. this.value = value;
  24154. this._target = target;
  24155. }
  24156. SetValueAction.prototype._prepare = function () {
  24157. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  24158. this._property = this._getProperty(this.propertyPath);
  24159. };
  24160. SetValueAction.prototype.execute = function () {
  24161. this._target[this._property] = this.value;
  24162. };
  24163. return SetValueAction;
  24164. })(BABYLON.Action);
  24165. BABYLON.SetValueAction = SetValueAction;
  24166. var IncrementValueAction = (function (_super) {
  24167. __extends(IncrementValueAction, _super);
  24168. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  24169. _super.call(this, triggerOptions, condition);
  24170. this.propertyPath = propertyPath;
  24171. this.value = value;
  24172. this._target = target;
  24173. }
  24174. IncrementValueAction.prototype._prepare = function () {
  24175. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  24176. this._property = this._getProperty(this.propertyPath);
  24177. if (typeof this._target[this._property] !== "number") {
  24178. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  24179. }
  24180. };
  24181. IncrementValueAction.prototype.execute = function () {
  24182. this._target[this._property] += this.value;
  24183. };
  24184. return IncrementValueAction;
  24185. })(BABYLON.Action);
  24186. BABYLON.IncrementValueAction = IncrementValueAction;
  24187. var PlayAnimationAction = (function (_super) {
  24188. __extends(PlayAnimationAction, _super);
  24189. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  24190. _super.call(this, triggerOptions, condition);
  24191. this.from = from;
  24192. this.to = to;
  24193. this.loop = loop;
  24194. this._target = target;
  24195. }
  24196. PlayAnimationAction.prototype._prepare = function () {
  24197. };
  24198. PlayAnimationAction.prototype.execute = function () {
  24199. var scene = this._actionManager.getScene();
  24200. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  24201. };
  24202. return PlayAnimationAction;
  24203. })(BABYLON.Action);
  24204. BABYLON.PlayAnimationAction = PlayAnimationAction;
  24205. var StopAnimationAction = (function (_super) {
  24206. __extends(StopAnimationAction, _super);
  24207. function StopAnimationAction(triggerOptions, target, condition) {
  24208. _super.call(this, triggerOptions, condition);
  24209. this._target = target;
  24210. }
  24211. StopAnimationAction.prototype._prepare = function () {
  24212. };
  24213. StopAnimationAction.prototype.execute = function () {
  24214. var scene = this._actionManager.getScene();
  24215. scene.stopAnimation(this._target);
  24216. };
  24217. return StopAnimationAction;
  24218. })(BABYLON.Action);
  24219. BABYLON.StopAnimationAction = StopAnimationAction;
  24220. var DoNothingAction = (function (_super) {
  24221. __extends(DoNothingAction, _super);
  24222. function DoNothingAction(triggerOptions, condition) {
  24223. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  24224. _super.call(this, triggerOptions, condition);
  24225. }
  24226. DoNothingAction.prototype.execute = function () {
  24227. };
  24228. return DoNothingAction;
  24229. })(BABYLON.Action);
  24230. BABYLON.DoNothingAction = DoNothingAction;
  24231. var CombineAction = (function (_super) {
  24232. __extends(CombineAction, _super);
  24233. function CombineAction(triggerOptions, children, condition) {
  24234. _super.call(this, triggerOptions, condition);
  24235. this.children = children;
  24236. }
  24237. CombineAction.prototype._prepare = function () {
  24238. for (var index = 0; index < this.children.length; index++) {
  24239. this.children[index]._actionManager = this._actionManager;
  24240. this.children[index]._prepare();
  24241. }
  24242. };
  24243. CombineAction.prototype.execute = function (evt) {
  24244. for (var index = 0; index < this.children.length; index++) {
  24245. this.children[index].execute(evt);
  24246. }
  24247. };
  24248. return CombineAction;
  24249. })(BABYLON.Action);
  24250. BABYLON.CombineAction = CombineAction;
  24251. var ExecuteCodeAction = (function (_super) {
  24252. __extends(ExecuteCodeAction, _super);
  24253. function ExecuteCodeAction(triggerOptions, func, condition) {
  24254. _super.call(this, triggerOptions, condition);
  24255. this.func = func;
  24256. }
  24257. ExecuteCodeAction.prototype.execute = function (evt) {
  24258. this.func(evt);
  24259. };
  24260. return ExecuteCodeAction;
  24261. })(BABYLON.Action);
  24262. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  24263. var SetParentAction = (function (_super) {
  24264. __extends(SetParentAction, _super);
  24265. function SetParentAction(triggerOptions, target, parent, condition) {
  24266. _super.call(this, triggerOptions, condition);
  24267. this._target = target;
  24268. this._parent = parent;
  24269. }
  24270. SetParentAction.prototype._prepare = function () {
  24271. };
  24272. SetParentAction.prototype.execute = function () {
  24273. if (this._target.parent === this._parent) {
  24274. return;
  24275. }
  24276. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  24277. invertParentWorldMatrix.invert();
  24278. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  24279. this._target.parent = this._parent;
  24280. };
  24281. return SetParentAction;
  24282. })(BABYLON.Action);
  24283. BABYLON.SetParentAction = SetParentAction;
  24284. var PlaySoundAction = (function (_super) {
  24285. __extends(PlaySoundAction, _super);
  24286. function PlaySoundAction(triggerOptions, sound, condition) {
  24287. _super.call(this, triggerOptions, condition);
  24288. this._sound = sound;
  24289. }
  24290. PlaySoundAction.prototype._prepare = function () {
  24291. };
  24292. PlaySoundAction.prototype.execute = function () {
  24293. if (this._sound !== undefined)
  24294. this._sound.play();
  24295. };
  24296. return PlaySoundAction;
  24297. })(BABYLON.Action);
  24298. BABYLON.PlaySoundAction = PlaySoundAction;
  24299. var StopSoundAction = (function (_super) {
  24300. __extends(StopSoundAction, _super);
  24301. function StopSoundAction(triggerOptions, sound, condition) {
  24302. _super.call(this, triggerOptions, condition);
  24303. this._sound = sound;
  24304. }
  24305. StopSoundAction.prototype._prepare = function () {
  24306. };
  24307. StopSoundAction.prototype.execute = function () {
  24308. if (this._sound !== undefined)
  24309. this._sound.stop();
  24310. };
  24311. return StopSoundAction;
  24312. })(BABYLON.Action);
  24313. BABYLON.StopSoundAction = StopSoundAction;
  24314. })(BABYLON || (BABYLON = {}));
  24315. //# sourceMappingURL=babylon.directActions.js.map
  24316. var BABYLON;
  24317. (function (BABYLON) {
  24318. var Geometry = (function () {
  24319. function Geometry(id, scene, vertexData, updatable, mesh) {
  24320. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  24321. this._totalVertices = 0;
  24322. this._indices = [];
  24323. this.id = id;
  24324. this._engine = scene.getEngine();
  24325. this._meshes = [];
  24326. this._scene = scene;
  24327. // vertexData
  24328. if (vertexData) {
  24329. this.setAllVerticesData(vertexData, updatable);
  24330. }
  24331. else {
  24332. this._totalVertices = 0;
  24333. this._indices = [];
  24334. }
  24335. // applyToMesh
  24336. if (mesh) {
  24337. this.applyToMesh(mesh);
  24338. mesh.computeWorldMatrix(true);
  24339. }
  24340. }
  24341. Geometry.prototype.getScene = function () {
  24342. return this._scene;
  24343. };
  24344. Geometry.prototype.getEngine = function () {
  24345. return this._engine;
  24346. };
  24347. Geometry.prototype.isReady = function () {
  24348. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  24349. };
  24350. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  24351. vertexData.applyToGeometry(this, updatable);
  24352. };
  24353. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  24354. this._vertexBuffers = this._vertexBuffers || {};
  24355. if (this._vertexBuffers[kind]) {
  24356. this._vertexBuffers[kind].dispose();
  24357. }
  24358. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  24359. if (kind === BABYLON.VertexBuffer.PositionKind) {
  24360. stride = this._vertexBuffers[kind].getStrideSize();
  24361. this._totalVertices = data.length / stride;
  24362. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  24363. var meshes = this._meshes;
  24364. var numOfMeshes = meshes.length;
  24365. for (var index = 0; index < numOfMeshes; index++) {
  24366. var mesh = meshes[index];
  24367. mesh._resetPointsArrayCache();
  24368. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  24369. mesh._createGlobalSubMesh();
  24370. mesh.computeWorldMatrix(true);
  24371. }
  24372. }
  24373. };
  24374. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  24375. var vertexBuffer = this.getVertexBuffer(kind);
  24376. if (!vertexBuffer) {
  24377. return;
  24378. }
  24379. vertexBuffer.updateDirectly(data, offset);
  24380. };
  24381. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  24382. var vertexBuffer = this.getVertexBuffer(kind);
  24383. if (!vertexBuffer) {
  24384. return;
  24385. }
  24386. vertexBuffer.update(data);
  24387. if (kind === BABYLON.VertexBuffer.PositionKind) {
  24388. var extend;
  24389. var stride = vertexBuffer.getStrideSize();
  24390. this._totalVertices = data.length / stride;
  24391. if (updateExtends) {
  24392. extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  24393. }
  24394. var meshes = this._meshes;
  24395. var numOfMeshes = meshes.length;
  24396. for (var index = 0; index < numOfMeshes; index++) {
  24397. var mesh = meshes[index];
  24398. mesh._resetPointsArrayCache();
  24399. if (updateExtends) {
  24400. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  24401. }
  24402. }
  24403. }
  24404. };
  24405. Geometry.prototype.getTotalVertices = function () {
  24406. if (!this.isReady()) {
  24407. return 0;
  24408. }
  24409. return this._totalVertices;
  24410. };
  24411. Geometry.prototype.getVerticesData = function (kind) {
  24412. var vertexBuffer = this.getVertexBuffer(kind);
  24413. if (!vertexBuffer) {
  24414. return null;
  24415. }
  24416. return vertexBuffer.getData();
  24417. };
  24418. Geometry.prototype.getVertexBuffer = function (kind) {
  24419. if (!this.isReady()) {
  24420. return null;
  24421. }
  24422. return this._vertexBuffers[kind];
  24423. };
  24424. Geometry.prototype.getVertexBuffers = function () {
  24425. if (!this.isReady()) {
  24426. return null;
  24427. }
  24428. return this._vertexBuffers;
  24429. };
  24430. Geometry.prototype.isVerticesDataPresent = function (kind) {
  24431. if (!this._vertexBuffers) {
  24432. if (this._delayInfo) {
  24433. return this._delayInfo.indexOf(kind) !== -1;
  24434. }
  24435. return false;
  24436. }
  24437. return this._vertexBuffers[kind] !== undefined;
  24438. };
  24439. Geometry.prototype.getVerticesDataKinds = function () {
  24440. var result = [];
  24441. if (!this._vertexBuffers && this._delayInfo) {
  24442. for (var kind in this._delayInfo) {
  24443. result.push(kind);
  24444. }
  24445. }
  24446. else {
  24447. for (kind in this._vertexBuffers) {
  24448. result.push(kind);
  24449. }
  24450. }
  24451. return result;
  24452. };
  24453. Geometry.prototype.setIndices = function (indices, totalVertices) {
  24454. if (this._indexBuffer) {
  24455. this._engine._releaseBuffer(this._indexBuffer);
  24456. }
  24457. this._indices = indices;
  24458. if (this._meshes.length !== 0 && this._indices) {
  24459. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  24460. }
  24461. if (totalVertices !== undefined) {
  24462. this._totalVertices = totalVertices;
  24463. }
  24464. var meshes = this._meshes;
  24465. var numOfMeshes = meshes.length;
  24466. for (var index = 0; index < numOfMeshes; index++) {
  24467. meshes[index]._createGlobalSubMesh();
  24468. }
  24469. };
  24470. Geometry.prototype.getTotalIndices = function () {
  24471. if (!this.isReady()) {
  24472. return 0;
  24473. }
  24474. return this._indices.length;
  24475. };
  24476. Geometry.prototype.getIndices = function () {
  24477. if (!this.isReady()) {
  24478. return null;
  24479. }
  24480. return this._indices;
  24481. };
  24482. Geometry.prototype.getIndexBuffer = function () {
  24483. if (!this.isReady()) {
  24484. return null;
  24485. }
  24486. return this._indexBuffer;
  24487. };
  24488. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  24489. var meshes = this._meshes;
  24490. var index = meshes.indexOf(mesh);
  24491. if (index === -1) {
  24492. return;
  24493. }
  24494. for (var kind in this._vertexBuffers) {
  24495. this._vertexBuffers[kind].dispose();
  24496. }
  24497. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  24498. this._indexBuffer = null;
  24499. }
  24500. meshes.splice(index, 1);
  24501. mesh._geometry = null;
  24502. if (meshes.length === 0 && shouldDispose) {
  24503. this.dispose();
  24504. }
  24505. };
  24506. Geometry.prototype.applyToMesh = function (mesh) {
  24507. if (mesh._geometry === this) {
  24508. return;
  24509. }
  24510. var previousGeometry = mesh._geometry;
  24511. if (previousGeometry) {
  24512. previousGeometry.releaseForMesh(mesh);
  24513. }
  24514. var meshes = this._meshes;
  24515. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  24516. mesh._geometry = this;
  24517. this._scene.pushGeometry(this);
  24518. meshes.push(mesh);
  24519. if (this.isReady()) {
  24520. this._applyToMesh(mesh);
  24521. }
  24522. else {
  24523. mesh._boundingInfo = this._boundingInfo;
  24524. }
  24525. };
  24526. Geometry.prototype._applyToMesh = function (mesh) {
  24527. var numOfMeshes = this._meshes.length;
  24528. for (var kind in this._vertexBuffers) {
  24529. if (numOfMeshes === 1) {
  24530. this._vertexBuffers[kind].create();
  24531. }
  24532. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  24533. if (kind === BABYLON.VertexBuffer.PositionKind) {
  24534. mesh._resetPointsArrayCache();
  24535. var extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  24536. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  24537. mesh._createGlobalSubMesh();
  24538. //bounding info was just created again, world matrix should be applied again.
  24539. mesh._updateBoundingInfo();
  24540. }
  24541. }
  24542. // indexBuffer
  24543. if (numOfMeshes === 1 && this._indices) {
  24544. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  24545. }
  24546. if (this._indexBuffer) {
  24547. this._indexBuffer.references = numOfMeshes;
  24548. }
  24549. };
  24550. Geometry.prototype.load = function (scene, onLoaded) {
  24551. var _this = this;
  24552. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  24553. return;
  24554. }
  24555. if (this.isReady()) {
  24556. if (onLoaded) {
  24557. onLoaded();
  24558. }
  24559. return;
  24560. }
  24561. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  24562. scene._addPendingData(this);
  24563. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  24564. _this._delayLoadingFunction(JSON.parse(data), _this);
  24565. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  24566. _this._delayInfo = [];
  24567. scene._removePendingData(_this);
  24568. var meshes = _this._meshes;
  24569. var numOfMeshes = meshes.length;
  24570. for (var index = 0; index < numOfMeshes; index++) {
  24571. _this._applyToMesh(meshes[index]);
  24572. }
  24573. if (onLoaded) {
  24574. onLoaded();
  24575. }
  24576. }, function () {
  24577. }, scene.database);
  24578. };
  24579. Geometry.prototype.dispose = function () {
  24580. var meshes = this._meshes;
  24581. var numOfMeshes = meshes.length;
  24582. var index;
  24583. for (index = 0; index < numOfMeshes; index++) {
  24584. this.releaseForMesh(meshes[index]);
  24585. }
  24586. this._meshes = [];
  24587. for (var kind in this._vertexBuffers) {
  24588. this._vertexBuffers[kind].dispose();
  24589. }
  24590. this._vertexBuffers = [];
  24591. this._totalVertices = 0;
  24592. if (this._indexBuffer) {
  24593. this._engine._releaseBuffer(this._indexBuffer);
  24594. }
  24595. this._indexBuffer = null;
  24596. this._indices = [];
  24597. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  24598. this.delayLoadingFile = null;
  24599. this._delayLoadingFunction = null;
  24600. this._delayInfo = [];
  24601. this._boundingInfo = null; // todo: .dispose()
  24602. var geometries = this._scene.getGeometries();
  24603. index = geometries.indexOf(this);
  24604. if (index > -1) {
  24605. geometries.splice(index, 1);
  24606. }
  24607. };
  24608. Geometry.prototype.copy = function (id) {
  24609. var vertexData = new BABYLON.VertexData();
  24610. vertexData.indices = [];
  24611. var indices = this.getIndices();
  24612. for (var index = 0; index < indices.length; index++) {
  24613. vertexData.indices.push(indices[index]);
  24614. }
  24615. var updatable = false;
  24616. var stopChecking = false;
  24617. for (var kind in this._vertexBuffers) {
  24618. vertexData.set(this.getVerticesData(kind), kind);
  24619. if (!stopChecking) {
  24620. updatable = this.getVertexBuffer(kind).isUpdatable();
  24621. stopChecking = !updatable;
  24622. }
  24623. }
  24624. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  24625. geometry.delayLoadState = this.delayLoadState;
  24626. geometry.delayLoadingFile = this.delayLoadingFile;
  24627. geometry._delayLoadingFunction = this._delayLoadingFunction;
  24628. for (kind in this._delayInfo) {
  24629. geometry._delayInfo = geometry._delayInfo || [];
  24630. geometry._delayInfo.push(kind);
  24631. }
  24632. // Bounding info
  24633. var extend = BABYLON.Tools.ExtractMinAndMax(this.getVerticesData(BABYLON.VertexBuffer.PositionKind), 0, this.getTotalVertices());
  24634. geometry._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  24635. return geometry;
  24636. };
  24637. // Statics
  24638. Geometry.ExtractFromMesh = function (mesh, id) {
  24639. var geometry = mesh._geometry;
  24640. if (!geometry) {
  24641. return null;
  24642. }
  24643. return geometry.copy(id);
  24644. };
  24645. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  24646. // be aware Math.random() could cause collisions
  24647. Geometry.RandomId = function () {
  24648. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  24649. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  24650. return v.toString(16);
  24651. });
  24652. };
  24653. return Geometry;
  24654. })();
  24655. BABYLON.Geometry = Geometry;
  24656. /////// Primitives //////////////////////////////////////////////
  24657. var Geometry;
  24658. (function (Geometry) {
  24659. var Primitives;
  24660. (function (Primitives) {
  24661. /// Abstract class
  24662. var _Primitive = (function (_super) {
  24663. __extends(_Primitive, _super);
  24664. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  24665. this._beingRegenerated = true;
  24666. this._canBeRegenerated = canBeRegenerated;
  24667. _super.call(this, id, scene, vertexData, false, mesh); // updatable = false to be sure not to update vertices
  24668. this._beingRegenerated = false;
  24669. }
  24670. _Primitive.prototype.canBeRegenerated = function () {
  24671. return this._canBeRegenerated;
  24672. };
  24673. _Primitive.prototype.regenerate = function () {
  24674. if (!this._canBeRegenerated) {
  24675. return;
  24676. }
  24677. this._beingRegenerated = true;
  24678. this.setAllVerticesData(this._regenerateVertexData(), false);
  24679. this._beingRegenerated = false;
  24680. };
  24681. _Primitive.prototype.asNewGeometry = function (id) {
  24682. return _super.prototype.copy.call(this, id);
  24683. };
  24684. // overrides
  24685. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  24686. if (!this._beingRegenerated) {
  24687. return;
  24688. }
  24689. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  24690. };
  24691. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  24692. if (!this._beingRegenerated) {
  24693. return;
  24694. }
  24695. _super.prototype.setVerticesData.call(this, kind, data, false);
  24696. };
  24697. // to override
  24698. // protected
  24699. _Primitive.prototype._regenerateVertexData = function () {
  24700. throw new Error("Abstract method");
  24701. };
  24702. _Primitive.prototype.copy = function (id) {
  24703. throw new Error("Must be overriden in sub-classes.");
  24704. };
  24705. return _Primitive;
  24706. })(Geometry);
  24707. Primitives._Primitive = _Primitive;
  24708. var Ribbon = (function (_super) {
  24709. __extends(Ribbon, _super);
  24710. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  24711. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  24712. this.pathArray = pathArray;
  24713. this.closeArray = closeArray;
  24714. this.closePath = closePath;
  24715. this.offset = offset;
  24716. this.side = side;
  24717. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  24718. }
  24719. Ribbon.prototype._regenerateVertexData = function () {
  24720. return BABYLON.VertexData.CreateRibbon(this.pathArray, this.closeArray, this.closePath, this.offset, this.side);
  24721. };
  24722. Ribbon.prototype.copy = function (id) {
  24723. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  24724. };
  24725. return Ribbon;
  24726. })(_Primitive);
  24727. Primitives.Ribbon = Ribbon;
  24728. var Box = (function (_super) {
  24729. __extends(Box, _super);
  24730. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  24731. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  24732. this.size = size;
  24733. this.side = side;
  24734. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  24735. }
  24736. Box.prototype._regenerateVertexData = function () {
  24737. return BABYLON.VertexData.CreateBox(this.size, this.side);
  24738. };
  24739. Box.prototype.copy = function (id) {
  24740. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  24741. };
  24742. return Box;
  24743. })(_Primitive);
  24744. Primitives.Box = Box;
  24745. var Sphere = (function (_super) {
  24746. __extends(Sphere, _super);
  24747. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  24748. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  24749. this.segments = segments;
  24750. this.diameter = diameter;
  24751. this.side = side;
  24752. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  24753. }
  24754. Sphere.prototype._regenerateVertexData = function () {
  24755. return BABYLON.VertexData.CreateSphere(this.segments, this.diameter, this.side);
  24756. };
  24757. Sphere.prototype.copy = function (id) {
  24758. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  24759. };
  24760. return Sphere;
  24761. })(_Primitive);
  24762. Primitives.Sphere = Sphere;
  24763. var Cylinder = (function (_super) {
  24764. __extends(Cylinder, _super);
  24765. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  24766. if (subdivisions === void 0) { subdivisions = 1; }
  24767. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  24768. this.height = height;
  24769. this.diameterTop = diameterTop;
  24770. this.diameterBottom = diameterBottom;
  24771. this.tessellation = tessellation;
  24772. this.subdivisions = subdivisions;
  24773. this.side = side;
  24774. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  24775. }
  24776. Cylinder.prototype._regenerateVertexData = function () {
  24777. return BABYLON.VertexData.CreateCylinder(this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.side);
  24778. };
  24779. Cylinder.prototype.copy = function (id) {
  24780. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  24781. };
  24782. return Cylinder;
  24783. })(_Primitive);
  24784. Primitives.Cylinder = Cylinder;
  24785. var Torus = (function (_super) {
  24786. __extends(Torus, _super);
  24787. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  24788. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  24789. this.diameter = diameter;
  24790. this.thickness = thickness;
  24791. this.tessellation = tessellation;
  24792. this.side = side;
  24793. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  24794. }
  24795. Torus.prototype._regenerateVertexData = function () {
  24796. return BABYLON.VertexData.CreateTorus(this.diameter, this.thickness, this.tessellation, this.side);
  24797. };
  24798. Torus.prototype.copy = function (id) {
  24799. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  24800. };
  24801. return Torus;
  24802. })(_Primitive);
  24803. Primitives.Torus = Torus;
  24804. var Ground = (function (_super) {
  24805. __extends(Ground, _super);
  24806. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  24807. this.width = width;
  24808. this.height = height;
  24809. this.subdivisions = subdivisions;
  24810. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  24811. }
  24812. Ground.prototype._regenerateVertexData = function () {
  24813. return BABYLON.VertexData.CreateGround(this.width, this.height, this.subdivisions);
  24814. };
  24815. Ground.prototype.copy = function (id) {
  24816. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  24817. };
  24818. return Ground;
  24819. })(_Primitive);
  24820. Primitives.Ground = Ground;
  24821. var TiledGround = (function (_super) {
  24822. __extends(TiledGround, _super);
  24823. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  24824. this.xmin = xmin;
  24825. this.zmin = zmin;
  24826. this.xmax = xmax;
  24827. this.zmax = zmax;
  24828. this.subdivisions = subdivisions;
  24829. this.precision = precision;
  24830. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  24831. }
  24832. TiledGround.prototype._regenerateVertexData = function () {
  24833. return BABYLON.VertexData.CreateTiledGround(this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision);
  24834. };
  24835. TiledGround.prototype.copy = function (id) {
  24836. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  24837. };
  24838. return TiledGround;
  24839. })(_Primitive);
  24840. Primitives.TiledGround = TiledGround;
  24841. var Plane = (function (_super) {
  24842. __extends(Plane, _super);
  24843. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  24844. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  24845. this.size = size;
  24846. this.side = side;
  24847. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  24848. }
  24849. Plane.prototype._regenerateVertexData = function () {
  24850. return BABYLON.VertexData.CreatePlane(this.size, this.side);
  24851. };
  24852. Plane.prototype.copy = function (id) {
  24853. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  24854. };
  24855. return Plane;
  24856. })(_Primitive);
  24857. Primitives.Plane = Plane;
  24858. var TorusKnot = (function (_super) {
  24859. __extends(TorusKnot, _super);
  24860. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  24861. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  24862. this.radius = radius;
  24863. this.tube = tube;
  24864. this.radialSegments = radialSegments;
  24865. this.tubularSegments = tubularSegments;
  24866. this.p = p;
  24867. this.q = q;
  24868. this.side = side;
  24869. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  24870. }
  24871. TorusKnot.prototype._regenerateVertexData = function () {
  24872. return BABYLON.VertexData.CreateTorusKnot(this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.side);
  24873. };
  24874. TorusKnot.prototype.copy = function (id) {
  24875. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  24876. };
  24877. return TorusKnot;
  24878. })(_Primitive);
  24879. Primitives.TorusKnot = TorusKnot;
  24880. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  24881. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  24882. })(BABYLON || (BABYLON = {}));
  24883. //# sourceMappingURL=babylon.geometry.js.map
  24884. var BABYLON;
  24885. (function (BABYLON) {
  24886. var Gamepads = (function () {
  24887. function Gamepads(ongamedpadconnected) {
  24888. var _this = this;
  24889. this.babylonGamepads = [];
  24890. this.oneGamepadConnected = false;
  24891. this.isMonitoring = false;
  24892. this.gamepadEventSupported = 'GamepadEvent' in window;
  24893. this.gamepadSupportAvailable = (navigator.getGamepads || !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  24894. 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=";
  24895. this._callbackGamepadConnected = ongamedpadconnected;
  24896. if (this.gamepadSupportAvailable) {
  24897. // Checking if the gamepad connected event is supported (like in Firefox)
  24898. if (this.gamepadEventSupported) {
  24899. window.addEventListener('gamepadconnected', function (evt) {
  24900. _this._onGamepadConnected(evt);
  24901. }, false);
  24902. window.addEventListener('gamepaddisconnected', function (evt) {
  24903. _this._onGamepadDisconnected(evt);
  24904. }, false);
  24905. }
  24906. else {
  24907. this._startMonitoringGamepads();
  24908. }
  24909. if (!this.oneGamepadConnected) {
  24910. this._insertGamepadDOMInstructions();
  24911. }
  24912. }
  24913. else {
  24914. this._insertGamepadDOMNotSupported();
  24915. }
  24916. }
  24917. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  24918. Gamepads.gamepadDOMInfo = document.createElement("div");
  24919. var buttonAImage = document.createElement("img");
  24920. buttonAImage.src = this.buttonADataURL;
  24921. var spanMessage = document.createElement("span");
  24922. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  24923. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  24924. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  24925. Gamepads.gamepadDOMInfo.style.position = "absolute";
  24926. Gamepads.gamepadDOMInfo.style.width = "100%";
  24927. Gamepads.gamepadDOMInfo.style.height = "48px";
  24928. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  24929. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  24930. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  24931. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  24932. buttonAImage.style.position = "relative";
  24933. buttonAImage.style.bottom = "8px";
  24934. spanMessage.style.position = "relative";
  24935. spanMessage.style.fontSize = "32px";
  24936. spanMessage.style.bottom = "32px";
  24937. spanMessage.style.color = "green";
  24938. document.body.appendChild(Gamepads.gamepadDOMInfo);
  24939. };
  24940. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  24941. Gamepads.gamepadDOMInfo = document.createElement("div");
  24942. var spanMessage = document.createElement("span");
  24943. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  24944. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  24945. Gamepads.gamepadDOMInfo.style.position = "absolute";
  24946. Gamepads.gamepadDOMInfo.style.width = "100%";
  24947. Gamepads.gamepadDOMInfo.style.height = "40px";
  24948. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  24949. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  24950. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  24951. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  24952. spanMessage.style.position = "relative";
  24953. spanMessage.style.fontSize = "32px";
  24954. spanMessage.style.color = "red";
  24955. document.body.appendChild(Gamepads.gamepadDOMInfo);
  24956. };
  24957. Gamepads.prototype.dispose = function () {
  24958. if (Gamepads.gamepadDOMInfo) {
  24959. document.body.removeChild(Gamepads.gamepadDOMInfo);
  24960. }
  24961. };
  24962. Gamepads.prototype._onGamepadConnected = function (evt) {
  24963. var newGamepad = this._addNewGamepad(evt.gamepad);
  24964. if (this._callbackGamepadConnected)
  24965. this._callbackGamepadConnected(newGamepad);
  24966. this._startMonitoringGamepads();
  24967. };
  24968. Gamepads.prototype._addNewGamepad = function (gamepad) {
  24969. if (!this.oneGamepadConnected) {
  24970. this.oneGamepadConnected = true;
  24971. if (Gamepads.gamepadDOMInfo) {
  24972. document.body.removeChild(Gamepads.gamepadDOMInfo);
  24973. Gamepads.gamepadDOMInfo = null;
  24974. }
  24975. }
  24976. var newGamepad;
  24977. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  24978. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  24979. }
  24980. else {
  24981. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  24982. }
  24983. this.babylonGamepads.push(newGamepad);
  24984. return newGamepad;
  24985. };
  24986. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  24987. for (var i in this.babylonGamepads) {
  24988. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  24989. this.babylonGamepads.splice(i, 1);
  24990. break;
  24991. }
  24992. }
  24993. // If no gamepads are left, stop the polling loop.
  24994. if (this.babylonGamepads.length == 0) {
  24995. this._stopMonitoringGamepads();
  24996. }
  24997. };
  24998. Gamepads.prototype._startMonitoringGamepads = function () {
  24999. if (!this.isMonitoring) {
  25000. this.isMonitoring = true;
  25001. this._checkGamepadsStatus();
  25002. }
  25003. };
  25004. Gamepads.prototype._stopMonitoringGamepads = function () {
  25005. this.isMonitoring = false;
  25006. };
  25007. Gamepads.prototype._checkGamepadsStatus = function () {
  25008. var _this = this;
  25009. // updating gamepad objects
  25010. this._updateGamepadObjects();
  25011. for (var i in this.babylonGamepads) {
  25012. this.babylonGamepads[i].update();
  25013. }
  25014. if (this.isMonitoring) {
  25015. if (window.requestAnimationFrame) {
  25016. window.requestAnimationFrame(function () {
  25017. _this._checkGamepadsStatus();
  25018. });
  25019. }
  25020. else if (window.mozRequestAnimationFrame) {
  25021. window.mozRequestAnimationFrame(function () {
  25022. _this._checkGamepadsStatus();
  25023. });
  25024. }
  25025. else if (window.webkitRequestAnimationFrame) {
  25026. window.webkitRequestAnimationFrame(function () {
  25027. _this._checkGamepadsStatus();
  25028. });
  25029. }
  25030. }
  25031. };
  25032. // This function is called only on Chrome, which does not yet support
  25033. // connection/disconnection events, but requires you to monitor
  25034. // an array for changes.
  25035. Gamepads.prototype._updateGamepadObjects = function () {
  25036. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  25037. for (var i = 0; i < gamepads.length; i++) {
  25038. if (gamepads[i]) {
  25039. if (!(gamepads[i].index in this.babylonGamepads)) {
  25040. var newGamepad = this._addNewGamepad(gamepads[i]);
  25041. if (this._callbackGamepadConnected) {
  25042. this._callbackGamepadConnected(newGamepad);
  25043. }
  25044. }
  25045. else {
  25046. this.babylonGamepads[i].browserGamepad = gamepads[i];
  25047. }
  25048. }
  25049. }
  25050. };
  25051. return Gamepads;
  25052. })();
  25053. BABYLON.Gamepads = Gamepads;
  25054. var StickValues = (function () {
  25055. function StickValues(x, y) {
  25056. this.x = x;
  25057. this.y = y;
  25058. }
  25059. return StickValues;
  25060. })();
  25061. BABYLON.StickValues = StickValues;
  25062. var Gamepad = (function () {
  25063. function Gamepad(id, index, browserGamepad) {
  25064. this.id = id;
  25065. this.index = index;
  25066. this.browserGamepad = browserGamepad;
  25067. if (this.browserGamepad.axes.length >= 2) {
  25068. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  25069. }
  25070. if (this.browserGamepad.axes.length >= 4) {
  25071. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  25072. }
  25073. }
  25074. Gamepad.prototype.onleftstickchanged = function (callback) {
  25075. this._onleftstickchanged = callback;
  25076. };
  25077. Gamepad.prototype.onrightstickchanged = function (callback) {
  25078. this._onrightstickchanged = callback;
  25079. };
  25080. Object.defineProperty(Gamepad.prototype, "leftStick", {
  25081. get: function () {
  25082. return this._leftStick;
  25083. },
  25084. set: function (newValues) {
  25085. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  25086. this._onleftstickchanged(newValues);
  25087. }
  25088. this._leftStick = newValues;
  25089. },
  25090. enumerable: true,
  25091. configurable: true
  25092. });
  25093. Object.defineProperty(Gamepad.prototype, "rightStick", {
  25094. get: function () {
  25095. return this._rightStick;
  25096. },
  25097. set: function (newValues) {
  25098. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  25099. this._onrightstickchanged(newValues);
  25100. }
  25101. this._rightStick = newValues;
  25102. },
  25103. enumerable: true,
  25104. configurable: true
  25105. });
  25106. Gamepad.prototype.update = function () {
  25107. if (this._leftStick) {
  25108. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  25109. }
  25110. if (this._rightStick) {
  25111. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  25112. }
  25113. };
  25114. return Gamepad;
  25115. })();
  25116. BABYLON.Gamepad = Gamepad;
  25117. var GenericPad = (function (_super) {
  25118. __extends(GenericPad, _super);
  25119. function GenericPad(id, index, gamepad) {
  25120. _super.call(this, id, index, gamepad);
  25121. this.id = id;
  25122. this.index = index;
  25123. this.gamepad = gamepad;
  25124. this._buttons = new Array(gamepad.buttons.length);
  25125. }
  25126. GenericPad.prototype.onbuttondown = function (callback) {
  25127. this._onbuttondown = callback;
  25128. };
  25129. GenericPad.prototype.onbuttonup = function (callback) {
  25130. this._onbuttonup = callback;
  25131. };
  25132. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  25133. if (newValue !== currentValue) {
  25134. if (this._onbuttondown && newValue === 1) {
  25135. this._onbuttondown(buttonIndex);
  25136. }
  25137. if (this._onbuttonup && newValue === 0) {
  25138. this._onbuttonup(buttonIndex);
  25139. }
  25140. }
  25141. return newValue;
  25142. };
  25143. GenericPad.prototype.update = function () {
  25144. _super.prototype.update.call(this);
  25145. for (var index = 0; index < this._buttons.length; index++) {
  25146. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  25147. }
  25148. };
  25149. return GenericPad;
  25150. })(Gamepad);
  25151. BABYLON.GenericPad = GenericPad;
  25152. (function (Xbox360Button) {
  25153. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  25154. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  25155. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  25156. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  25157. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  25158. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  25159. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  25160. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  25161. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  25162. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  25163. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  25164. var Xbox360Button = BABYLON.Xbox360Button;
  25165. (function (Xbox360Dpad) {
  25166. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  25167. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  25168. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  25169. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  25170. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  25171. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  25172. var Xbox360Pad = (function (_super) {
  25173. __extends(Xbox360Pad, _super);
  25174. function Xbox360Pad() {
  25175. _super.apply(this, arguments);
  25176. this._leftTrigger = 0;
  25177. this._rightTrigger = 0;
  25178. this._buttonA = 0;
  25179. this._buttonB = 0;
  25180. this._buttonX = 0;
  25181. this._buttonY = 0;
  25182. this._buttonBack = 0;
  25183. this._buttonStart = 0;
  25184. this._buttonLB = 0;
  25185. this._buttonRB = 0;
  25186. this._buttonLeftStick = 0;
  25187. this._buttonRightStick = 0;
  25188. this._dPadUp = 0;
  25189. this._dPadDown = 0;
  25190. this._dPadLeft = 0;
  25191. this._dPadRight = 0;
  25192. }
  25193. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  25194. this._onlefttriggerchanged = callback;
  25195. };
  25196. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  25197. this._onrighttriggerchanged = callback;
  25198. };
  25199. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  25200. get: function () {
  25201. return this._leftTrigger;
  25202. },
  25203. set: function (newValue) {
  25204. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  25205. this._onlefttriggerchanged(newValue);
  25206. }
  25207. this._leftTrigger = newValue;
  25208. },
  25209. enumerable: true,
  25210. configurable: true
  25211. });
  25212. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  25213. get: function () {
  25214. return this._rightTrigger;
  25215. },
  25216. set: function (newValue) {
  25217. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  25218. this._onrighttriggerchanged(newValue);
  25219. }
  25220. this._rightTrigger = newValue;
  25221. },
  25222. enumerable: true,
  25223. configurable: true
  25224. });
  25225. Xbox360Pad.prototype.onbuttondown = function (callback) {
  25226. this._onbuttondown = callback;
  25227. };
  25228. Xbox360Pad.prototype.onbuttonup = function (callback) {
  25229. this._onbuttonup = callback;
  25230. };
  25231. Xbox360Pad.prototype.ondpaddown = function (callback) {
  25232. this._ondpaddown = callback;
  25233. };
  25234. Xbox360Pad.prototype.ondpadup = function (callback) {
  25235. this._ondpadup = callback;
  25236. };
  25237. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  25238. if (newValue !== currentValue) {
  25239. if (this._onbuttondown && newValue === 1) {
  25240. this._onbuttondown(buttonType);
  25241. }
  25242. if (this._onbuttonup && newValue === 0) {
  25243. this._onbuttonup(buttonType);
  25244. }
  25245. }
  25246. return newValue;
  25247. };
  25248. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  25249. if (newValue !== currentValue) {
  25250. if (this._ondpaddown && newValue === 1) {
  25251. this._ondpaddown(buttonType);
  25252. }
  25253. if (this._ondpadup && newValue === 0) {
  25254. this._ondpadup(buttonType);
  25255. }
  25256. }
  25257. return newValue;
  25258. };
  25259. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  25260. get: function () {
  25261. return this._buttonA;
  25262. },
  25263. set: function (value) {
  25264. this._buttonA = this._setButtonValue(value, this._buttonA, 0 /* A */);
  25265. },
  25266. enumerable: true,
  25267. configurable: true
  25268. });
  25269. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  25270. get: function () {
  25271. return this._buttonB;
  25272. },
  25273. set: function (value) {
  25274. this._buttonB = this._setButtonValue(value, this._buttonB, 1 /* B */);
  25275. },
  25276. enumerable: true,
  25277. configurable: true
  25278. });
  25279. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  25280. get: function () {
  25281. return this._buttonX;
  25282. },
  25283. set: function (value) {
  25284. this._buttonX = this._setButtonValue(value, this._buttonX, 2 /* X */);
  25285. },
  25286. enumerable: true,
  25287. configurable: true
  25288. });
  25289. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  25290. get: function () {
  25291. return this._buttonY;
  25292. },
  25293. set: function (value) {
  25294. this._buttonY = this._setButtonValue(value, this._buttonY, 3 /* Y */);
  25295. },
  25296. enumerable: true,
  25297. configurable: true
  25298. });
  25299. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  25300. get: function () {
  25301. return this._buttonStart;
  25302. },
  25303. set: function (value) {
  25304. this._buttonStart = this._setButtonValue(value, this._buttonStart, 4 /* Start */);
  25305. },
  25306. enumerable: true,
  25307. configurable: true
  25308. });
  25309. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  25310. get: function () {
  25311. return this._buttonBack;
  25312. },
  25313. set: function (value) {
  25314. this._buttonBack = this._setButtonValue(value, this._buttonBack, 5 /* Back */);
  25315. },
  25316. enumerable: true,
  25317. configurable: true
  25318. });
  25319. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  25320. get: function () {
  25321. return this._buttonLB;
  25322. },
  25323. set: function (value) {
  25324. this._buttonLB = this._setButtonValue(value, this._buttonLB, 6 /* LB */);
  25325. },
  25326. enumerable: true,
  25327. configurable: true
  25328. });
  25329. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  25330. get: function () {
  25331. return this._buttonRB;
  25332. },
  25333. set: function (value) {
  25334. this._buttonRB = this._setButtonValue(value, this._buttonRB, 7 /* RB */);
  25335. },
  25336. enumerable: true,
  25337. configurable: true
  25338. });
  25339. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  25340. get: function () {
  25341. return this._buttonLeftStick;
  25342. },
  25343. set: function (value) {
  25344. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, 8 /* LeftStick */);
  25345. },
  25346. enumerable: true,
  25347. configurable: true
  25348. });
  25349. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  25350. get: function () {
  25351. return this._buttonRightStick;
  25352. },
  25353. set: function (value) {
  25354. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, 9 /* RightStick */);
  25355. },
  25356. enumerable: true,
  25357. configurable: true
  25358. });
  25359. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  25360. get: function () {
  25361. return this._dPadUp;
  25362. },
  25363. set: function (value) {
  25364. this._dPadUp = this._setDPadValue(value, this._dPadUp, 0 /* Up */);
  25365. },
  25366. enumerable: true,
  25367. configurable: true
  25368. });
  25369. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  25370. get: function () {
  25371. return this._dPadDown;
  25372. },
  25373. set: function (value) {
  25374. this._dPadDown = this._setDPadValue(value, this._dPadDown, 1 /* Down */);
  25375. },
  25376. enumerable: true,
  25377. configurable: true
  25378. });
  25379. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  25380. get: function () {
  25381. return this._dPadLeft;
  25382. },
  25383. set: function (value) {
  25384. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, 2 /* Left */);
  25385. },
  25386. enumerable: true,
  25387. configurable: true
  25388. });
  25389. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  25390. get: function () {
  25391. return this._dPadRight;
  25392. },
  25393. set: function (value) {
  25394. this._dPadRight = this._setDPadValue(value, this._dPadRight, 3 /* Right */);
  25395. },
  25396. enumerable: true,
  25397. configurable: true
  25398. });
  25399. Xbox360Pad.prototype.update = function () {
  25400. _super.prototype.update.call(this);
  25401. this.buttonA = this.browserGamepad.buttons[0].value;
  25402. this.buttonB = this.browserGamepad.buttons[1].value;
  25403. this.buttonX = this.browserGamepad.buttons[2].value;
  25404. this.buttonY = this.browserGamepad.buttons[3].value;
  25405. this.buttonLB = this.browserGamepad.buttons[4].value;
  25406. this.buttonRB = this.browserGamepad.buttons[5].value;
  25407. this.leftTrigger = this.browserGamepad.buttons[6].value;
  25408. this.rightTrigger = this.browserGamepad.buttons[7].value;
  25409. this.buttonBack = this.browserGamepad.buttons[8].value;
  25410. this.buttonStart = this.browserGamepad.buttons[9].value;
  25411. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  25412. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  25413. this.dPadUp = this.browserGamepad.buttons[12].value;
  25414. this.dPadDown = this.browserGamepad.buttons[13].value;
  25415. this.dPadLeft = this.browserGamepad.buttons[14].value;
  25416. this.dPadRight = this.browserGamepad.buttons[15].value;
  25417. };
  25418. return Xbox360Pad;
  25419. })(Gamepad);
  25420. BABYLON.Xbox360Pad = Xbox360Pad;
  25421. })(BABYLON || (BABYLON = {}));
  25422. //# sourceMappingURL=babylon.gamepads.js.map
  25423. var BABYLON;
  25424. (function (BABYLON) {
  25425. // We're mainly based on the logic defined into the FreeCamera code
  25426. var GamepadCamera = (function (_super) {
  25427. __extends(GamepadCamera, _super);
  25428. function GamepadCamera(name, position, scene) {
  25429. var _this = this;
  25430. _super.call(this, name, position, scene);
  25431. this.angularSensibility = 200;
  25432. this.moveSensibility = 75;
  25433. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  25434. _this._onNewGameConnected(gamepad);
  25435. });
  25436. }
  25437. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  25438. // Only the first gamepad can control the camera
  25439. if (gamepad.index === 0) {
  25440. this._gamepad = gamepad;
  25441. }
  25442. };
  25443. GamepadCamera.prototype._checkInputs = function () {
  25444. if (!this._gamepad) {
  25445. return;
  25446. }
  25447. var LSValues = this._gamepad.leftStick;
  25448. var normalizedLX = LSValues.x / this.moveSensibility;
  25449. var normalizedLY = LSValues.y / this.moveSensibility;
  25450. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  25451. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  25452. var RSValues = this._gamepad.rightStick;
  25453. var normalizedRX = RSValues.x / this.angularSensibility;
  25454. var normalizedRY = RSValues.y / this.angularSensibility;
  25455. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  25456. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  25457. ;
  25458. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  25459. var speed = this._computeLocalCameraSpeed() * 50.0;
  25460. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  25461. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  25462. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  25463. };
  25464. GamepadCamera.prototype.dispose = function () {
  25465. this._gamepads.dispose();
  25466. _super.prototype.dispose.call(this);
  25467. };
  25468. return GamepadCamera;
  25469. })(BABYLON.FreeCamera);
  25470. BABYLON.GamepadCamera = GamepadCamera;
  25471. })(BABYLON || (BABYLON = {}));
  25472. //# sourceMappingURL=babylon.gamepadCamera.js.map
  25473. var BABYLON;
  25474. (function (BABYLON) {
  25475. var LinesMesh = (function (_super) {
  25476. __extends(LinesMesh, _super);
  25477. function LinesMesh(name, scene, updatable) {
  25478. if (updatable === void 0) { updatable = false; }
  25479. _super.call(this, name, scene);
  25480. this.color = new BABYLON.Color3(1, 1, 1);
  25481. this.alpha = 1;
  25482. this._indices = new Array();
  25483. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  25484. attributes: ["position"],
  25485. uniforms: ["worldViewProjection", "color"],
  25486. needAlphaBlending: true
  25487. });
  25488. }
  25489. Object.defineProperty(LinesMesh.prototype, "material", {
  25490. get: function () {
  25491. return this._colorShader;
  25492. },
  25493. enumerable: true,
  25494. configurable: true
  25495. });
  25496. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  25497. get: function () {
  25498. return false;
  25499. },
  25500. enumerable: true,
  25501. configurable: true
  25502. });
  25503. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  25504. get: function () {
  25505. return false;
  25506. },
  25507. enumerable: true,
  25508. configurable: true
  25509. });
  25510. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  25511. var engine = this.getScene().getEngine();
  25512. var indexToBind = this._geometry.getIndexBuffer();
  25513. // VBOs
  25514. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  25515. // Color
  25516. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  25517. };
  25518. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  25519. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  25520. return;
  25521. }
  25522. var engine = this.getScene().getEngine();
  25523. // Draw order
  25524. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  25525. };
  25526. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  25527. return null;
  25528. };
  25529. LinesMesh.prototype.dispose = function (doNotRecurse) {
  25530. this._colorShader.dispose();
  25531. _super.prototype.dispose.call(this, doNotRecurse);
  25532. };
  25533. return LinesMesh;
  25534. })(BABYLON.Mesh);
  25535. BABYLON.LinesMesh = LinesMesh;
  25536. })(BABYLON || (BABYLON = {}));
  25537. //# sourceMappingURL=babylon.linesMesh.js.mapvar BABYLON;
  25538. (function (BABYLON) {
  25539. var OutlineRenderer = (function () {
  25540. function OutlineRenderer(scene) {
  25541. this._scene = scene;
  25542. }
  25543. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  25544. var _this = this;
  25545. if (useOverlay === void 0) { useOverlay = false; }
  25546. var scene = this._scene;
  25547. var engine = this._scene.getEngine();
  25548. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  25549. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  25550. return;
  25551. }
  25552. var mesh = subMesh.getRenderingMesh();
  25553. var material = subMesh.getMaterial();
  25554. engine.enableEffect(this._effect);
  25555. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  25556. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  25557. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  25558. // Bones
  25559. if (mesh.useBones) {
  25560. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  25561. }
  25562. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  25563. // Alpha test
  25564. if (material && material.needAlphaTesting()) {
  25565. var alphaTexture = material.getAlphaTestTexture();
  25566. this._effect.setTexture("diffuseSampler", alphaTexture);
  25567. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  25568. }
  25569. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  25570. _this._effect.setMatrix("world", world);
  25571. });
  25572. };
  25573. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  25574. var defines = [];
  25575. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  25576. var mesh = subMesh.getMesh();
  25577. var material = subMesh.getMaterial();
  25578. // Alpha test
  25579. if (material && material.needAlphaTesting()) {
  25580. defines.push("#define ALPHATEST");
  25581. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  25582. attribs.push(BABYLON.VertexBuffer.UVKind);
  25583. defines.push("#define UV1");
  25584. }
  25585. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  25586. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  25587. defines.push("#define UV2");
  25588. }
  25589. }
  25590. // Bones
  25591. if (mesh.useBones) {
  25592. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  25593. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  25594. defines.push("#define BONES");
  25595. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  25596. }
  25597. // Instances
  25598. if (useInstances) {
  25599. defines.push("#define INSTANCES");
  25600. attribs.push("world0");
  25601. attribs.push("world1");
  25602. attribs.push("world2");
  25603. attribs.push("world3");
  25604. }
  25605. // Get correct effect
  25606. var join = defines.join("\n");
  25607. if (this._cachedDefines !== join) {
  25608. this._cachedDefines = join;
  25609. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  25610. }
  25611. return this._effect.isReady();
  25612. };
  25613. return OutlineRenderer;
  25614. })();
  25615. BABYLON.OutlineRenderer = OutlineRenderer;
  25616. })(BABYLON || (BABYLON = {}));
  25617. //# sourceMappingURL=babylon.outlineRenderer.js.mapvar BABYLON;
  25618. (function (BABYLON) {
  25619. var MeshAssetTask = (function () {
  25620. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  25621. this.name = name;
  25622. this.meshesNames = meshesNames;
  25623. this.rootUrl = rootUrl;
  25624. this.sceneFilename = sceneFilename;
  25625. this.isCompleted = false;
  25626. }
  25627. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  25628. var _this = this;
  25629. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  25630. _this.loadedMeshes = meshes;
  25631. _this.loadedParticleSystems = particleSystems;
  25632. _this.loadedSkeletons = skeletons;
  25633. _this.isCompleted = true;
  25634. if (_this.onSuccess) {
  25635. _this.onSuccess(_this);
  25636. }
  25637. onSuccess();
  25638. }, null, function () {
  25639. if (_this.onError) {
  25640. _this.onError(_this);
  25641. }
  25642. onError();
  25643. });
  25644. };
  25645. return MeshAssetTask;
  25646. })();
  25647. BABYLON.MeshAssetTask = MeshAssetTask;
  25648. var TextFileAssetTask = (function () {
  25649. function TextFileAssetTask(name, url) {
  25650. this.name = name;
  25651. this.url = url;
  25652. this.isCompleted = false;
  25653. }
  25654. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  25655. var _this = this;
  25656. BABYLON.Tools.LoadFile(this.url, function (data) {
  25657. _this.text = data;
  25658. _this.isCompleted = true;
  25659. if (_this.onSuccess) {
  25660. _this.onSuccess(_this);
  25661. }
  25662. onSuccess();
  25663. }, null, scene.database, false, function () {
  25664. if (_this.onError) {
  25665. _this.onError(_this);
  25666. }
  25667. onError();
  25668. });
  25669. };
  25670. return TextFileAssetTask;
  25671. })();
  25672. BABYLON.TextFileAssetTask = TextFileAssetTask;
  25673. var BinaryFileAssetTask = (function () {
  25674. function BinaryFileAssetTask(name, url) {
  25675. this.name = name;
  25676. this.url = url;
  25677. this.isCompleted = false;
  25678. }
  25679. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  25680. var _this = this;
  25681. BABYLON.Tools.LoadFile(this.url, function (data) {
  25682. _this.data = data;
  25683. _this.isCompleted = true;
  25684. if (_this.onSuccess) {
  25685. _this.onSuccess(_this);
  25686. }
  25687. onSuccess();
  25688. }, null, scene.database, true, function () {
  25689. if (_this.onError) {
  25690. _this.onError(_this);
  25691. }
  25692. onError();
  25693. });
  25694. };
  25695. return BinaryFileAssetTask;
  25696. })();
  25697. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  25698. var ImageAssetTask = (function () {
  25699. function ImageAssetTask(name, url) {
  25700. this.name = name;
  25701. this.url = url;
  25702. this.isCompleted = false;
  25703. }
  25704. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  25705. var _this = this;
  25706. var img = new Image();
  25707. img.onload = function () {
  25708. _this.image = img;
  25709. _this.isCompleted = true;
  25710. if (_this.onSuccess) {
  25711. _this.onSuccess(_this);
  25712. }
  25713. onSuccess();
  25714. };
  25715. img.onerror = function () {
  25716. if (_this.onError) {
  25717. _this.onError(_this);
  25718. }
  25719. onError();
  25720. };
  25721. img.src = this.url;
  25722. };
  25723. return ImageAssetTask;
  25724. })();
  25725. BABYLON.ImageAssetTask = ImageAssetTask;
  25726. var TextureAssetTask = (function () {
  25727. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  25728. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  25729. this.name = name;
  25730. this.url = url;
  25731. this.noMipmap = noMipmap;
  25732. this.invertY = invertY;
  25733. this.samplingMode = samplingMode;
  25734. this.isCompleted = false;
  25735. }
  25736. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  25737. var _this = this;
  25738. var onload = function () {
  25739. _this.isCompleted = true;
  25740. if (_this.onSuccess) {
  25741. _this.onSuccess(_this);
  25742. }
  25743. onSuccess();
  25744. };
  25745. var onerror = function () {
  25746. if (_this.onError) {
  25747. _this.onError(_this);
  25748. }
  25749. onError();
  25750. };
  25751. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onError);
  25752. };
  25753. return TextureAssetTask;
  25754. })();
  25755. BABYLON.TextureAssetTask = TextureAssetTask;
  25756. var AssetsManager = (function () {
  25757. function AssetsManager(scene) {
  25758. this._tasks = new Array();
  25759. this._waitingTasksCount = 0;
  25760. this.useDefaultLoadingScreen = true;
  25761. this._scene = scene;
  25762. }
  25763. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  25764. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  25765. this._tasks.push(task);
  25766. return task;
  25767. };
  25768. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  25769. var task = new TextFileAssetTask(taskName, url);
  25770. this._tasks.push(task);
  25771. return task;
  25772. };
  25773. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  25774. var task = new BinaryFileAssetTask(taskName, url);
  25775. this._tasks.push(task);
  25776. return task;
  25777. };
  25778. AssetsManager.prototype.addImageTask = function (taskName, url) {
  25779. var task = new ImageAssetTask(taskName, url);
  25780. this._tasks.push(task);
  25781. return task;
  25782. };
  25783. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  25784. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  25785. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  25786. this._tasks.push(task);
  25787. return task;
  25788. };
  25789. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  25790. this._waitingTasksCount--;
  25791. if (this._waitingTasksCount === 0) {
  25792. if (this.onFinish) {
  25793. this.onFinish(this._tasks);
  25794. }
  25795. this._scene.getEngine().hideLoadingUI();
  25796. }
  25797. };
  25798. AssetsManager.prototype._runTask = function (task) {
  25799. var _this = this;
  25800. task.run(this._scene, function () {
  25801. if (_this.onTaskSuccess) {
  25802. _this.onTaskSuccess(task);
  25803. }
  25804. _this._decreaseWaitingTasksCount();
  25805. }, function () {
  25806. if (_this.onTaskError) {
  25807. _this.onTaskError(task);
  25808. }
  25809. _this._decreaseWaitingTasksCount();
  25810. });
  25811. };
  25812. AssetsManager.prototype.reset = function () {
  25813. this._tasks = new Array();
  25814. return this;
  25815. };
  25816. AssetsManager.prototype.load = function () {
  25817. this._waitingTasksCount = this._tasks.length;
  25818. if (this._waitingTasksCount === 0) {
  25819. if (this.onFinish) {
  25820. this.onFinish(this._tasks);
  25821. }
  25822. return this;
  25823. }
  25824. if (this.useDefaultLoadingScreen) {
  25825. this._scene.getEngine().displayLoadingUI();
  25826. }
  25827. for (var index = 0; index < this._tasks.length; index++) {
  25828. var task = this._tasks[index];
  25829. this._runTask(task);
  25830. }
  25831. return this;
  25832. };
  25833. return AssetsManager;
  25834. })();
  25835. BABYLON.AssetsManager = AssetsManager;
  25836. })(BABYLON || (BABYLON = {}));
  25837. //# sourceMappingURL=babylon.assetsManager.js.map
  25838. var BABYLON;
  25839. (function (BABYLON) {
  25840. var VRDeviceOrientationCamera = (function (_super) {
  25841. __extends(VRDeviceOrientationCamera, _super);
  25842. function VRDeviceOrientationCamera(name, position, scene) {
  25843. _super.call(this, name, position, scene);
  25844. this._alpha = 0;
  25845. this._beta = 0;
  25846. this._gamma = 0;
  25847. }
  25848. VRDeviceOrientationCamera.prototype._onOrientationEvent = function (evt) {
  25849. this._alpha = +evt.alpha | 0;
  25850. this._beta = +evt.beta | 0;
  25851. this._gamma = +evt.gamma | 0;
  25852. if (this._gamma < 0) {
  25853. this._gamma = 90 + this._gamma;
  25854. }
  25855. else {
  25856. // Incline it in the correct angle.
  25857. this._gamma = 270 - this._gamma;
  25858. }
  25859. this.rotation.x = this._gamma / 180.0 * Math.PI;
  25860. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  25861. this.rotation.z = this._beta / 180.0 * Math.PI;
  25862. };
  25863. return VRDeviceOrientationCamera;
  25864. })(BABYLON.OculusCamera);
  25865. BABYLON.VRDeviceOrientationCamera = VRDeviceOrientationCamera;
  25866. })(BABYLON || (BABYLON = {}));
  25867. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  25868. var BABYLON;
  25869. (function (BABYLON) {
  25870. var WebVRCamera = (function (_super) {
  25871. __extends(WebVRCamera, _super);
  25872. function WebVRCamera(name, position, scene) {
  25873. _super.call(this, name, position, scene);
  25874. this._hmdDevice = null;
  25875. this._sensorDevice = null;
  25876. this._cacheState = null;
  25877. this._cacheQuaternion = new BABYLON.Quaternion();
  25878. this._cacheRotation = BABYLON.Vector3.Zero();
  25879. this._vrEnabled = false;
  25880. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  25881. }
  25882. WebVRCamera.prototype._getWebVRDevices = function (devices) {
  25883. var size = devices.length;
  25884. var i = 0;
  25885. // Reset devices.
  25886. this._sensorDevice = null;
  25887. this._hmdDevice = null;
  25888. while (i < size && this._hmdDevice === null) {
  25889. if (devices[i] instanceof HMDVRDevice) {
  25890. this._hmdDevice = devices[i];
  25891. }
  25892. i++;
  25893. }
  25894. i = 0;
  25895. while (i < size && this._sensorDevice === null) {
  25896. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  25897. this._sensorDevice = devices[i];
  25898. }
  25899. i++;
  25900. }
  25901. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  25902. };
  25903. WebVRCamera.prototype._update = function () {
  25904. if (this._vrEnabled) {
  25905. this._cacheState = this._sensorDevice.getState();
  25906. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  25907. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  25908. this.rotation.x = -this._cacheRotation.z;
  25909. this.rotation.y = -this._cacheRotation.y;
  25910. this.rotation.z = this._cacheRotation.x;
  25911. }
  25912. _super.prototype._update.call(this);
  25913. };
  25914. WebVRCamera.prototype.attachControl = function (element, noPreventDefault) {
  25915. _super.prototype.attachControl.call(this, element, noPreventDefault);
  25916. if (navigator.getVRDevices) {
  25917. navigator.getVRDevices().then(this._getWebVRDevices);
  25918. }
  25919. else if (navigator.mozGetVRDevices) {
  25920. navigator.mozGetVRDevices(this._getWebVRDevices);
  25921. }
  25922. };
  25923. WebVRCamera.prototype.detachControl = function (element) {
  25924. _super.prototype.detachControl.call(this, element);
  25925. this._vrEnabled = false;
  25926. };
  25927. return WebVRCamera;
  25928. })(BABYLON.OculusCamera);
  25929. BABYLON.WebVRCamera = WebVRCamera;
  25930. })(BABYLON || (BABYLON = {}));
  25931. //# sourceMappingURL=babylon.webVRCamera.js.map
  25932. var BABYLON;
  25933. (function (BABYLON) {
  25934. // Standard optimizations
  25935. var SceneOptimization = (function () {
  25936. function SceneOptimization(priority) {
  25937. if (priority === void 0) { priority = 0; }
  25938. this.priority = priority;
  25939. this.apply = function (scene) {
  25940. return true; // Return true if everything that can be done was applied
  25941. };
  25942. }
  25943. return SceneOptimization;
  25944. })();
  25945. BABYLON.SceneOptimization = SceneOptimization;
  25946. var TextureOptimization = (function (_super) {
  25947. __extends(TextureOptimization, _super);
  25948. function TextureOptimization(priority, maximumSize) {
  25949. var _this = this;
  25950. if (priority === void 0) { priority = 0; }
  25951. if (maximumSize === void 0) { maximumSize = 1024; }
  25952. _super.call(this, priority);
  25953. this.priority = priority;
  25954. this.maximumSize = maximumSize;
  25955. this.apply = function (scene) {
  25956. var allDone = true;
  25957. for (var index = 0; index < scene.textures.length; index++) {
  25958. var texture = scene.textures[index];
  25959. if (!texture.canRescale) {
  25960. continue;
  25961. }
  25962. var currentSize = texture.getSize();
  25963. var maxDimension = Math.max(currentSize.width, currentSize.height);
  25964. if (maxDimension > _this.maximumSize) {
  25965. texture.scale(0.5);
  25966. allDone = false;
  25967. }
  25968. }
  25969. return allDone;
  25970. };
  25971. }
  25972. return TextureOptimization;
  25973. })(SceneOptimization);
  25974. BABYLON.TextureOptimization = TextureOptimization;
  25975. var HardwareScalingOptimization = (function (_super) {
  25976. __extends(HardwareScalingOptimization, _super);
  25977. function HardwareScalingOptimization(priority, maximumScale) {
  25978. var _this = this;
  25979. if (priority === void 0) { priority = 0; }
  25980. if (maximumScale === void 0) { maximumScale = 2; }
  25981. _super.call(this, priority);
  25982. this.priority = priority;
  25983. this.maximumScale = maximumScale;
  25984. this._currentScale = 1;
  25985. this.apply = function (scene) {
  25986. _this._currentScale++;
  25987. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  25988. return _this._currentScale >= _this.maximumScale;
  25989. };
  25990. }
  25991. return HardwareScalingOptimization;
  25992. })(SceneOptimization);
  25993. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  25994. var ShadowsOptimization = (function (_super) {
  25995. __extends(ShadowsOptimization, _super);
  25996. function ShadowsOptimization() {
  25997. _super.apply(this, arguments);
  25998. this.apply = function (scene) {
  25999. scene.shadowsEnabled = false;
  26000. return true;
  26001. };
  26002. }
  26003. return ShadowsOptimization;
  26004. })(SceneOptimization);
  26005. BABYLON.ShadowsOptimization = ShadowsOptimization;
  26006. var PostProcessesOptimization = (function (_super) {
  26007. __extends(PostProcessesOptimization, _super);
  26008. function PostProcessesOptimization() {
  26009. _super.apply(this, arguments);
  26010. this.apply = function (scene) {
  26011. scene.postProcessesEnabled = false;
  26012. return true;
  26013. };
  26014. }
  26015. return PostProcessesOptimization;
  26016. })(SceneOptimization);
  26017. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  26018. var LensFlaresOptimization = (function (_super) {
  26019. __extends(LensFlaresOptimization, _super);
  26020. function LensFlaresOptimization() {
  26021. _super.apply(this, arguments);
  26022. this.apply = function (scene) {
  26023. scene.lensFlaresEnabled = false;
  26024. return true;
  26025. };
  26026. }
  26027. return LensFlaresOptimization;
  26028. })(SceneOptimization);
  26029. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  26030. var ParticlesOptimization = (function (_super) {
  26031. __extends(ParticlesOptimization, _super);
  26032. function ParticlesOptimization() {
  26033. _super.apply(this, arguments);
  26034. this.apply = function (scene) {
  26035. scene.particlesEnabled = false;
  26036. return true;
  26037. };
  26038. }
  26039. return ParticlesOptimization;
  26040. })(SceneOptimization);
  26041. BABYLON.ParticlesOptimization = ParticlesOptimization;
  26042. var RenderTargetsOptimization = (function (_super) {
  26043. __extends(RenderTargetsOptimization, _super);
  26044. function RenderTargetsOptimization() {
  26045. _super.apply(this, arguments);
  26046. this.apply = function (scene) {
  26047. scene.renderTargetsEnabled = false;
  26048. return true;
  26049. };
  26050. }
  26051. return RenderTargetsOptimization;
  26052. })(SceneOptimization);
  26053. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  26054. var MergeMeshesOptimization = (function (_super) {
  26055. __extends(MergeMeshesOptimization, _super);
  26056. function MergeMeshesOptimization() {
  26057. var _this = this;
  26058. _super.apply(this, arguments);
  26059. this._canBeMerged = function (abstractMesh) {
  26060. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  26061. return false;
  26062. }
  26063. var mesh = abstractMesh;
  26064. if (!mesh.isVisible || !mesh.isEnabled()) {
  26065. return false;
  26066. }
  26067. if (mesh.instances.length > 0) {
  26068. return false;
  26069. }
  26070. if (mesh.skeleton || mesh.hasLODLevels) {
  26071. return false;
  26072. }
  26073. return true;
  26074. };
  26075. this.apply = function (scene) {
  26076. var globalPool = scene.meshes.slice(0);
  26077. var globalLength = globalPool.length;
  26078. for (var index = 0; index < globalLength; index++) {
  26079. var currentPool = new Array();
  26080. var current = globalPool[index];
  26081. // Checks
  26082. if (!_this._canBeMerged(current)) {
  26083. continue;
  26084. }
  26085. currentPool.push(current);
  26086. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  26087. var otherMesh = globalPool[subIndex];
  26088. if (!_this._canBeMerged(otherMesh)) {
  26089. continue;
  26090. }
  26091. if (otherMesh.material !== current.material) {
  26092. continue;
  26093. }
  26094. if (otherMesh.checkCollisions !== current.checkCollisions) {
  26095. continue;
  26096. }
  26097. currentPool.push(otherMesh);
  26098. globalLength--;
  26099. globalPool.splice(subIndex, 1);
  26100. subIndex--;
  26101. }
  26102. if (currentPool.length < 2) {
  26103. continue;
  26104. }
  26105. // Merge meshes
  26106. BABYLON.Mesh.MergeMeshes(currentPool);
  26107. }
  26108. return true;
  26109. };
  26110. }
  26111. return MergeMeshesOptimization;
  26112. })(SceneOptimization);
  26113. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  26114. // Options
  26115. var SceneOptimizerOptions = (function () {
  26116. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  26117. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  26118. if (trackerDuration === void 0) { trackerDuration = 2000; }
  26119. this.targetFrameRate = targetFrameRate;
  26120. this.trackerDuration = trackerDuration;
  26121. this.optimizations = new Array();
  26122. }
  26123. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  26124. var result = new SceneOptimizerOptions(targetFrameRate);
  26125. var priority = 0;
  26126. result.optimizations.push(new MergeMeshesOptimization(priority));
  26127. result.optimizations.push(new ShadowsOptimization(priority));
  26128. result.optimizations.push(new LensFlaresOptimization(priority));
  26129. // Next priority
  26130. priority++;
  26131. result.optimizations.push(new PostProcessesOptimization(priority));
  26132. result.optimizations.push(new ParticlesOptimization(priority));
  26133. // Next priority
  26134. priority++;
  26135. result.optimizations.push(new TextureOptimization(priority, 1024));
  26136. return result;
  26137. };
  26138. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  26139. var result = new SceneOptimizerOptions(targetFrameRate);
  26140. var priority = 0;
  26141. result.optimizations.push(new MergeMeshesOptimization(priority));
  26142. result.optimizations.push(new ShadowsOptimization(priority));
  26143. result.optimizations.push(new LensFlaresOptimization(priority));
  26144. // Next priority
  26145. priority++;
  26146. result.optimizations.push(new PostProcessesOptimization(priority));
  26147. result.optimizations.push(new ParticlesOptimization(priority));
  26148. // Next priority
  26149. priority++;
  26150. result.optimizations.push(new TextureOptimization(priority, 512));
  26151. // Next priority
  26152. priority++;
  26153. result.optimizations.push(new RenderTargetsOptimization(priority));
  26154. // Next priority
  26155. priority++;
  26156. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  26157. return result;
  26158. };
  26159. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  26160. var result = new SceneOptimizerOptions(targetFrameRate);
  26161. var priority = 0;
  26162. result.optimizations.push(new MergeMeshesOptimization(priority));
  26163. result.optimizations.push(new ShadowsOptimization(priority));
  26164. result.optimizations.push(new LensFlaresOptimization(priority));
  26165. // Next priority
  26166. priority++;
  26167. result.optimizations.push(new PostProcessesOptimization(priority));
  26168. result.optimizations.push(new ParticlesOptimization(priority));
  26169. // Next priority
  26170. priority++;
  26171. result.optimizations.push(new TextureOptimization(priority, 256));
  26172. // Next priority
  26173. priority++;
  26174. result.optimizations.push(new RenderTargetsOptimization(priority));
  26175. // Next priority
  26176. priority++;
  26177. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  26178. return result;
  26179. };
  26180. return SceneOptimizerOptions;
  26181. })();
  26182. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  26183. // Scene optimizer tool
  26184. var SceneOptimizer = (function () {
  26185. function SceneOptimizer() {
  26186. }
  26187. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  26188. // TODO: add an epsilon
  26189. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  26190. if (onSuccess) {
  26191. onSuccess();
  26192. }
  26193. return;
  26194. }
  26195. // Apply current level of optimizations
  26196. var allDone = true;
  26197. var noOptimizationApplied = true;
  26198. for (var index = 0; index < options.optimizations.length; index++) {
  26199. var optimization = options.optimizations[index];
  26200. if (optimization.priority === currentPriorityLevel) {
  26201. noOptimizationApplied = false;
  26202. allDone = allDone && optimization.apply(scene);
  26203. }
  26204. }
  26205. // If no optimization was applied, this is a failure :(
  26206. if (noOptimizationApplied) {
  26207. if (onFailure) {
  26208. onFailure();
  26209. }
  26210. return;
  26211. }
  26212. // If all optimizations were done, move to next level
  26213. if (allDone) {
  26214. currentPriorityLevel++;
  26215. }
  26216. // Let's the system running for a specific amount of time before checking FPS
  26217. scene.executeWhenReady(function () {
  26218. setTimeout(function () {
  26219. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  26220. }, options.trackerDuration);
  26221. });
  26222. };
  26223. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  26224. if (!options) {
  26225. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  26226. }
  26227. // Let's the system running for a specific amount of time before checking FPS
  26228. scene.executeWhenReady(function () {
  26229. setTimeout(function () {
  26230. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  26231. }, options.trackerDuration);
  26232. });
  26233. };
  26234. return SceneOptimizer;
  26235. })();
  26236. BABYLON.SceneOptimizer = SceneOptimizer;
  26237. })(BABYLON || (BABYLON = {}));
  26238. //# sourceMappingURL=babylon.sceneOptimizer.js.mapvar BABYLON;
  26239. (function (BABYLON) {
  26240. var Internals;
  26241. (function (Internals) {
  26242. var MeshLODLevel = (function () {
  26243. function MeshLODLevel(distance, mesh) {
  26244. this.distance = distance;
  26245. this.mesh = mesh;
  26246. }
  26247. return MeshLODLevel;
  26248. })();
  26249. Internals.MeshLODLevel = MeshLODLevel;
  26250. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  26251. })(BABYLON || (BABYLON = {}));
  26252. //# sourceMappingURL=babylon.meshLODLevel.js.mapvar BABYLON;
  26253. (function (BABYLON) {
  26254. var AudioEngine = (function () {
  26255. function AudioEngine() {
  26256. this.audioContext = null;
  26257. this.canUseWebAudio = false;
  26258. this.WarnedWebAudioUnsupported = false;
  26259. try {
  26260. if (typeof AudioContext !== 'undefined') {
  26261. this.audioContext = new AudioContext();
  26262. this.canUseWebAudio = true;
  26263. }
  26264. else if (typeof webkitAudioContext !== 'undefined') {
  26265. this.audioContext = new webkitAudioContext();
  26266. this.canUseWebAudio = true;
  26267. }
  26268. }
  26269. catch (e) {
  26270. this.canUseWebAudio = false;
  26271. BABYLON.Tools.Error("Web Audio: " + e.message);
  26272. }
  26273. // create a global volume gain node
  26274. if (this.canUseWebAudio) {
  26275. this.masterGain = this.audioContext.createGain();
  26276. this.masterGain.gain.value = 1;
  26277. this.masterGain.connect(this.audioContext.destination);
  26278. }
  26279. }
  26280. AudioEngine.prototype.dispose = function () {
  26281. if (this.canUseWebAudio) {
  26282. if (this._connectedAnalyser) {
  26283. this._connectedAnalyser.stopDebugCanvas();
  26284. this._connectedAnalyser.dispose();
  26285. this.masterGain.disconnect();
  26286. this.masterGain.connect(this.audioContext.destination);
  26287. this._connectedAnalyser = null;
  26288. }
  26289. this.masterGain.gain.value = 1;
  26290. }
  26291. this.WarnedWebAudioUnsupported = false;
  26292. };
  26293. AudioEngine.prototype.getGlobalVolume = function () {
  26294. if (this.canUseWebAudio) {
  26295. return this.masterGain.gain.value;
  26296. }
  26297. else {
  26298. return -1;
  26299. }
  26300. };
  26301. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  26302. if (this.canUseWebAudio) {
  26303. this.masterGain.gain.value = newVolume;
  26304. }
  26305. };
  26306. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  26307. if (this._connectedAnalyser) {
  26308. this._connectedAnalyser.stopDebugCanvas();
  26309. }
  26310. this._connectedAnalyser = analyser;
  26311. if (this.canUseWebAudio) {
  26312. this.masterGain.disconnect();
  26313. this._connectedAnalyser.connectAudioNodes(this.masterGain, this.audioContext.destination);
  26314. }
  26315. };
  26316. return AudioEngine;
  26317. })();
  26318. BABYLON.AudioEngine = AudioEngine;
  26319. })(BABYLON || (BABYLON = {}));
  26320. //# sourceMappingURL=babylon.audioengine.js.mapvar BABYLON;
  26321. (function (BABYLON) {
  26322. var Sound = (function () {
  26323. /**
  26324. * Create a sound and attach it to a scene
  26325. * @param name Name of your sound
  26326. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  26327. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  26328. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel
  26329. */
  26330. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  26331. var _this = this;
  26332. this.autoplay = false;
  26333. this.loop = false;
  26334. this.useCustomAttenuation = false;
  26335. this.spatialSound = false;
  26336. this.refDistance = 1;
  26337. this.rolloffFactor = 1;
  26338. this.maxDistance = 100;
  26339. this.distanceModel = "linear";
  26340. this.panningModel = "HRTF";
  26341. this._playbackRate = 1;
  26342. this._startTime = 0;
  26343. this._startOffset = 0;
  26344. this._position = BABYLON.Vector3.Zero();
  26345. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  26346. this._volume = 1;
  26347. this._isLoaded = false;
  26348. this._isReadyToPlay = false;
  26349. this.isPlaying = false;
  26350. this.isPaused = false;
  26351. this._isDirectional = false;
  26352. // Used if you'd like to create a directional sound.
  26353. // If not set, the sound will be omnidirectional
  26354. this._coneInnerAngle = 360;
  26355. this._coneOuterAngle = 360;
  26356. this._coneOuterGain = 0;
  26357. this.name = name;
  26358. this._scene = scene;
  26359. this._readyToPlayCallback = readyToPlayCallback;
  26360. // Default custom attenuation function is a linear attenuation
  26361. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  26362. if (currentDistance < maxDistance) {
  26363. return currentVolume * (1 - currentDistance / maxDistance);
  26364. }
  26365. else {
  26366. return 0;
  26367. }
  26368. };
  26369. if (options) {
  26370. this.autoplay = options.autoplay || false;
  26371. this.loop = options.loop || false;
  26372. // if volume === 0, we need another way to check this option
  26373. if (options.volume !== undefined) {
  26374. this._volume = options.volume;
  26375. }
  26376. this.spatialSound = options.spatialSound || false;
  26377. this.maxDistance = options.maxDistance || 100;
  26378. this.useCustomAttenuation = options.useCustomAttenuation || false;
  26379. this.rolloffFactor = options.rolloffFactor || 1;
  26380. this.refDistance = options.refDistance || 1;
  26381. this.distanceModel = options.distanceModel || "linear";
  26382. this.panningModel = options.panningModel || "HRTF";
  26383. this._playbackRate = options.playbackRate || 1;
  26384. }
  26385. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  26386. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  26387. this._soundGain.gain.value = this._volume;
  26388. this._inputAudioNode = this._soundGain;
  26389. this._ouputAudioNode = this._soundGain;
  26390. if (this.spatialSound) {
  26391. this._createSpatialParameters();
  26392. }
  26393. this._scene.mainSoundTrack.AddSound(this);
  26394. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  26395. if (urlOrArrayBuffer) {
  26396. // If it's an URL
  26397. if (typeof (urlOrArrayBuffer) === "string") {
  26398. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) {
  26399. _this._soundLoaded(data);
  26400. }, null, null, true);
  26401. }
  26402. else {
  26403. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  26404. this._soundLoaded(urlOrArrayBuffer);
  26405. }
  26406. else {
  26407. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  26408. }
  26409. }
  26410. }
  26411. }
  26412. else {
  26413. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  26414. this._scene.mainSoundTrack.AddSound(this);
  26415. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  26416. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  26417. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  26418. }
  26419. }
  26420. }
  26421. Sound.prototype.dispose = function () {
  26422. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  26423. if (this.isPlaying) {
  26424. this.stop();
  26425. }
  26426. this._isReadyToPlay = false;
  26427. if (this.soundTrackId === -1) {
  26428. this._scene.mainSoundTrack.RemoveSound(this);
  26429. }
  26430. else {
  26431. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  26432. }
  26433. if (this._soundGain) {
  26434. this._soundGain.disconnect();
  26435. this._soundGain = null;
  26436. }
  26437. if (this._soundPanner) {
  26438. this._soundPanner.disconnect();
  26439. this._soundPanner = null;
  26440. }
  26441. if (this._soundSource) {
  26442. this._soundSource.disconnect();
  26443. this._soundSource = null;
  26444. }
  26445. this._audioBuffer = null;
  26446. if (this._connectedMesh) {
  26447. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  26448. this._connectedMesh = null;
  26449. }
  26450. }
  26451. };
  26452. Sound.prototype._soundLoaded = function (audioData) {
  26453. var _this = this;
  26454. this._isLoaded = true;
  26455. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  26456. _this._audioBuffer = buffer;
  26457. _this._isReadyToPlay = true;
  26458. if (_this.autoplay) {
  26459. _this.play();
  26460. }
  26461. if (_this._readyToPlayCallback) {
  26462. _this._readyToPlayCallback();
  26463. }
  26464. }, function (error) {
  26465. BABYLON.Tools.Error("Error while decoding audio data: " + error.err);
  26466. });
  26467. };
  26468. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  26469. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  26470. this._audioBuffer = audioBuffer;
  26471. this._isReadyToPlay = true;
  26472. }
  26473. };
  26474. Sound.prototype.updateOptions = function (options) {
  26475. if (options) {
  26476. this.loop = options.loop || this.loop;
  26477. this.maxDistance = options.maxDistance || this.maxDistance;
  26478. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  26479. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  26480. this.refDistance = options.refDistance || this.refDistance;
  26481. this.distanceModel = options.distanceModel || this.distanceModel;
  26482. this.panningModel = options.panningModel || this.panningModel;
  26483. this._playbackRate = options.playbackRate || this._playbackRate;
  26484. }
  26485. };
  26486. Sound.prototype._createSpatialParameters = function () {
  26487. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  26488. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  26489. if (this.useCustomAttenuation) {
  26490. // Tricks to disable in a way embedded Web Audio attenuation
  26491. this._soundPanner.distanceModel = "linear";
  26492. this._soundPanner.maxDistance = Number.MAX_VALUE;
  26493. this._soundPanner.refDistance = 1;
  26494. this._soundPanner.rolloffFactor = 1;
  26495. this._soundPanner.panningModel = "HRTF";
  26496. }
  26497. else {
  26498. this._soundPanner.distanceModel = this.distanceModel;
  26499. this._soundPanner.maxDistance = this.maxDistance;
  26500. this._soundPanner.refDistance = this.refDistance;
  26501. this._soundPanner.rolloffFactor = this.rolloffFactor;
  26502. this._soundPanner.panningModel = this.panningModel;
  26503. }
  26504. this._soundPanner.connect(this._ouputAudioNode);
  26505. this._inputAudioNode = this._soundPanner;
  26506. }
  26507. };
  26508. Sound.prototype.switchPanningModelToHRTF = function () {
  26509. this._switchPanningModel("HRTF");
  26510. };
  26511. Sound.prototype.switchPanningModelToEqualPower = function () {
  26512. this._switchPanningModel("equalpower");
  26513. };
  26514. Sound.prototype._switchPanningModel = function (newModel) {
  26515. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  26516. this._soundPanner.panningModel = newModel;
  26517. }
  26518. };
  26519. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  26520. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  26521. this._ouputAudioNode.disconnect();
  26522. this._ouputAudioNode.connect(soundTrackAudioNode);
  26523. }
  26524. };
  26525. /**
  26526. * Transform this sound into a directional source
  26527. * @param coneInnerAngle Size of the inner cone in degree
  26528. * @param coneOuterAngle Size of the outer cone in degree
  26529. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  26530. */
  26531. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  26532. if (coneOuterAngle < coneInnerAngle) {
  26533. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  26534. return;
  26535. }
  26536. this._coneInnerAngle = coneInnerAngle;
  26537. this._coneOuterAngle = coneOuterAngle;
  26538. this._coneOuterGain = coneOuterGain;
  26539. this._isDirectional = true;
  26540. if (this.isPlaying && this.loop) {
  26541. this.stop();
  26542. this.play();
  26543. }
  26544. };
  26545. Sound.prototype.setPosition = function (newPosition) {
  26546. this._position = newPosition;
  26547. if (this.isPlaying && this.spatialSound) {
  26548. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  26549. }
  26550. };
  26551. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  26552. this._localDirection = newLocalDirection;
  26553. if (this._connectedMesh && this.isPlaying) {
  26554. this._updateDirection();
  26555. }
  26556. };
  26557. Sound.prototype._updateDirection = function () {
  26558. var mat = this._connectedMesh.getWorldMatrix();
  26559. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  26560. direction.normalize();
  26561. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  26562. };
  26563. Sound.prototype.updateDistanceFromListener = function () {
  26564. if (this._connectedMesh && this.useCustomAttenuation) {
  26565. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  26566. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  26567. }
  26568. };
  26569. Sound.prototype.setAttenuationFunction = function (callback) {
  26570. this._customAttenuationFunction = callback;
  26571. };
  26572. /**
  26573. * Play the sound
  26574. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  26575. */
  26576. Sound.prototype.play = function (time) {
  26577. var _this = this;
  26578. if (this._isReadyToPlay && this._scene.audioEnabled) {
  26579. try {
  26580. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  26581. if (!this._soundSource) {
  26582. if (this.spatialSound) {
  26583. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  26584. if (this._isDirectional) {
  26585. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  26586. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  26587. this._soundPanner.coneOuterGain = this._coneOuterGain;
  26588. if (this._connectedMesh) {
  26589. this._updateDirection();
  26590. }
  26591. else {
  26592. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  26593. }
  26594. }
  26595. }
  26596. }
  26597. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  26598. this._soundSource.buffer = this._audioBuffer;
  26599. this._soundSource.connect(this._inputAudioNode);
  26600. this._soundSource.loop = this.loop;
  26601. this._soundSource.playbackRate.value = this._playbackRate;
  26602. this._startTime = startTime;
  26603. this._soundSource.onended = function () {
  26604. _this._onended();
  26605. };
  26606. this._soundSource.start(this._startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : 0);
  26607. this.isPlaying = true;
  26608. this.isPaused = false;
  26609. }
  26610. catch (ex) {
  26611. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  26612. }
  26613. }
  26614. };
  26615. Sound.prototype._onended = function () {
  26616. this.isPlaying = false;
  26617. if (this.onended) {
  26618. this.onended();
  26619. }
  26620. };
  26621. /**
  26622. * Stop the sound
  26623. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  26624. */
  26625. Sound.prototype.stop = function (time) {
  26626. if (this.isPlaying) {
  26627. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  26628. this._soundSource.stop(stopTime);
  26629. this.isPlaying = false;
  26630. }
  26631. };
  26632. Sound.prototype.pause = function () {
  26633. if (this.isPlaying) {
  26634. this.stop(0);
  26635. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  26636. this.isPaused = true;
  26637. }
  26638. };
  26639. Sound.prototype.setVolume = function (newVolume, time) {
  26640. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  26641. if (time) {
  26642. this._soundGain.gain.linearRampToValueAtTime(this._volume, BABYLON.Engine.audioEngine.audioContext.currentTime);
  26643. this._soundGain.gain.linearRampToValueAtTime(newVolume, time);
  26644. }
  26645. else {
  26646. this._soundGain.gain.value = newVolume;
  26647. }
  26648. }
  26649. this._volume = newVolume;
  26650. };
  26651. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  26652. this._playbackRate = newPlaybackRate;
  26653. if (this.isPlaying) {
  26654. this._soundSource.playbackRate.value = this._playbackRate;
  26655. }
  26656. };
  26657. Sound.prototype.getVolume = function () {
  26658. return this._volume;
  26659. };
  26660. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  26661. var _this = this;
  26662. this._connectedMesh = meshToConnectTo;
  26663. if (!this.spatialSound) {
  26664. this._createSpatialParameters();
  26665. this.spatialSound = true;
  26666. if (this.isPlaying && this.loop) {
  26667. this.stop();
  26668. this.play();
  26669. }
  26670. }
  26671. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  26672. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  26673. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  26674. };
  26675. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  26676. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  26677. if (this._isDirectional && this.isPlaying) {
  26678. this._updateDirection();
  26679. }
  26680. };
  26681. return Sound;
  26682. })();
  26683. BABYLON.Sound = Sound;
  26684. })(BABYLON || (BABYLON = {}));
  26685. //# sourceMappingURL=babylon.sound.js.mapvar BABYLON;
  26686. (function (BABYLON) {
  26687. var SoundTrack = (function () {
  26688. function SoundTrack(scene, options) {
  26689. this.id = -1;
  26690. this._isMainTrack = false;
  26691. this._scene = scene;
  26692. this._audioEngine = BABYLON.Engine.audioEngine;
  26693. this.soundCollection = new Array();
  26694. if (this._audioEngine.canUseWebAudio) {
  26695. this._trackGain = this._audioEngine.audioContext.createGain();
  26696. this._trackGain.connect(this._audioEngine.masterGain);
  26697. if (options) {
  26698. if (options.volume) {
  26699. this._trackGain.gain.value = options.volume;
  26700. }
  26701. if (options.mainTrack) {
  26702. this._isMainTrack = options.mainTrack;
  26703. }
  26704. }
  26705. }
  26706. if (!this._isMainTrack) {
  26707. this._scene.soundTracks.push(this);
  26708. this.id = this._scene.soundTracks.length - 1;
  26709. }
  26710. }
  26711. SoundTrack.prototype.dispose = function () {
  26712. if (this._audioEngine.canUseWebAudio) {
  26713. if (this._connectedAnalyser) {
  26714. this._connectedAnalyser.stopDebugCanvas();
  26715. }
  26716. while (this.soundCollection.length) {
  26717. this.soundCollection[0].dispose();
  26718. }
  26719. this._trackGain.disconnect();
  26720. this._trackGain = null;
  26721. }
  26722. };
  26723. SoundTrack.prototype.AddSound = function (sound) {
  26724. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  26725. sound.connectToSoundTrackAudioNode(this._trackGain);
  26726. }
  26727. if (sound.soundTrackId) {
  26728. if (sound.soundTrackId === -1) {
  26729. this._scene.mainSoundTrack.RemoveSound(sound);
  26730. }
  26731. else {
  26732. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  26733. }
  26734. }
  26735. this.soundCollection.push(sound);
  26736. sound.soundTrackId = this.id;
  26737. };
  26738. SoundTrack.prototype.RemoveSound = function (sound) {
  26739. var index = this.soundCollection.indexOf(sound);
  26740. if (index !== -1) {
  26741. this.soundCollection.splice(index, 1);
  26742. }
  26743. };
  26744. SoundTrack.prototype.setVolume = function (newVolume) {
  26745. if (this._audioEngine.canUseWebAudio) {
  26746. this._trackGain.gain.value = newVolume;
  26747. }
  26748. };
  26749. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  26750. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  26751. for (var i = 0; i < this.soundCollection.length; i++) {
  26752. this.soundCollection[i].switchPanningModelToHRTF();
  26753. }
  26754. }
  26755. };
  26756. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  26757. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  26758. for (var i = 0; i < this.soundCollection.length; i++) {
  26759. this.soundCollection[i].switchPanningModelToEqualPower();
  26760. }
  26761. }
  26762. };
  26763. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  26764. if (this._connectedAnalyser) {
  26765. this._connectedAnalyser.stopDebugCanvas();
  26766. }
  26767. this._connectedAnalyser = analyser;
  26768. if (this._audioEngine.canUseWebAudio) {
  26769. this._trackGain.disconnect();
  26770. this._connectedAnalyser.connectAudioNodes(this._trackGain, this._audioEngine.masterGain);
  26771. }
  26772. };
  26773. return SoundTrack;
  26774. })();
  26775. BABYLON.SoundTrack = SoundTrack;
  26776. })(BABYLON || (BABYLON = {}));
  26777. //# sourceMappingURL=babylon.soundtrack.js.mapvar BABYLON;
  26778. (function (BABYLON) {
  26779. var DebugLayer = (function () {
  26780. function DebugLayer(scene) {
  26781. var _this = this;
  26782. this._transformationMatrix = BABYLON.Matrix.Identity();
  26783. this._enabled = false;
  26784. this._labelsEnabled = false;
  26785. this._displayStatistics = true;
  26786. this._displayTree = false;
  26787. this._displayLogs = false;
  26788. this._identityMatrix = BABYLON.Matrix.Identity();
  26789. this.axisRatio = 0.02;
  26790. this.accentColor = "orange";
  26791. this._scene = scene;
  26792. this._syncPositions = function () {
  26793. var engine = _this._scene.getEngine();
  26794. var canvasRect = engine.getRenderingCanvasClientRect();
  26795. if (_this._showUI) {
  26796. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  26797. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  26798. _this._statsDiv.style.width = "400px";
  26799. _this._statsDiv.style.height = "auto";
  26800. _this._statsSubsetDiv.style.maxHeight = "240px";
  26801. _this._optionsDiv.style.left = "0px";
  26802. _this._optionsDiv.style.top = "10px";
  26803. _this._optionsDiv.style.width = "200px";
  26804. _this._optionsDiv.style.height = "auto";
  26805. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  26806. _this._logDiv.style.left = "0px";
  26807. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  26808. _this._logDiv.style.width = "600px";
  26809. _this._logDiv.style.height = "160px";
  26810. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  26811. _this._treeDiv.style.top = "10px";
  26812. _this._treeDiv.style.width = "300px";
  26813. _this._treeDiv.style.height = "auto";
  26814. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  26815. }
  26816. _this._globalDiv.style.left = canvasRect.left + "px";
  26817. _this._globalDiv.style.top = canvasRect.top + "px";
  26818. _this._drawingCanvas.style.left = "0px";
  26819. _this._drawingCanvas.style.top = "0px";
  26820. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  26821. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  26822. var devicePixelRatio = window.devicePixelRatio || 1;
  26823. var context = _this._drawingContext;
  26824. var backingStoreRatio = context.webkitBackingStorePixelRatio || context.mozBackingStorePixelRatio || context.msBackingStorePixelRatio || context.oBackingStorePixelRatio || context.backingStorePixelRatio || 1;
  26825. _this._ratio = devicePixelRatio / backingStoreRatio;
  26826. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  26827. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  26828. };
  26829. this._onCanvasClick = function (evt) {
  26830. _this._clickPosition = {
  26831. x: evt.clientX * _this._ratio,
  26832. y: evt.clientY * _this._ratio
  26833. };
  26834. };
  26835. this._syncData = function () {
  26836. if (_this._showUI) {
  26837. if (_this._displayStatistics) {
  26838. _this._displayStats();
  26839. _this._statsDiv.style.display = "";
  26840. }
  26841. else {
  26842. _this._statsDiv.style.display = "none";
  26843. }
  26844. if (_this._displayLogs) {
  26845. _this._logDiv.style.display = "";
  26846. }
  26847. else {
  26848. _this._logDiv.style.display = "none";
  26849. }
  26850. if (_this._displayTree) {
  26851. _this._treeDiv.style.display = "";
  26852. if (_this._needToRefreshMeshesTree) {
  26853. _this._needToRefreshMeshesTree = false;
  26854. _this._refreshMeshesTreeContent();
  26855. }
  26856. }
  26857. else {
  26858. _this._treeDiv.style.display = "none";
  26859. }
  26860. }
  26861. if (_this._labelsEnabled || !_this._showUI) {
  26862. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  26863. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  26864. var engine = _this._scene.getEngine();
  26865. var viewport = _this._camera.viewport;
  26866. var globalViewport = viewport.toGlobal(engine);
  26867. // Meshes
  26868. var meshes = _this._camera.getActiveMeshes();
  26869. for (var index = 0; index < meshes.length; index++) {
  26870. var mesh = meshes.data[index];
  26871. var position = mesh.getBoundingInfo().boundingSphere.center;
  26872. var projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  26873. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  26874. _this._renderAxis(projectedPosition, mesh, globalViewport);
  26875. }
  26876. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  26877. _this._renderLabel(mesh.name, projectedPosition, 12, function () {
  26878. mesh.renderOverlay = !mesh.renderOverlay;
  26879. }, function () {
  26880. return mesh.renderOverlay ? 'red' : 'black';
  26881. });
  26882. }
  26883. }
  26884. // Cameras
  26885. var cameras = _this._scene.cameras;
  26886. for (index = 0; index < cameras.length; index++) {
  26887. var camera = cameras[index];
  26888. if (camera === _this._camera) {
  26889. continue;
  26890. }
  26891. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  26892. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  26893. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  26894. _this._camera.detachControl(engine.getRenderingCanvas());
  26895. _this._camera = camera;
  26896. _this._camera.attachControl(engine.getRenderingCanvas());
  26897. }, function () {
  26898. return "purple";
  26899. });
  26900. }
  26901. }
  26902. // Lights
  26903. var lights = _this._scene.lights;
  26904. for (index = 0; index < lights.length; index++) {
  26905. var light = lights[index];
  26906. if (light.position) {
  26907. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  26908. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  26909. _this._renderLabel(light.name, projectedPosition, -20, function () {
  26910. light.setEnabled(!light.isEnabled());
  26911. }, function () {
  26912. return light.isEnabled() ? "orange" : "gray";
  26913. });
  26914. }
  26915. }
  26916. }
  26917. }
  26918. _this._clickPosition = undefined;
  26919. };
  26920. }
  26921. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  26922. while (this._treeSubsetDiv.hasChildNodes()) {
  26923. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  26924. }
  26925. // Add meshes
  26926. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  26927. sortedArray.sort(function (a, b) {
  26928. if (a.name === b.name) {
  26929. return 0;
  26930. }
  26931. return (a.name > b.name) ? 1 : -1;
  26932. });
  26933. for (var index = 0; index < sortedArray.length; index++) {
  26934. var mesh = sortedArray[index];
  26935. if (!mesh.isEnabled()) {
  26936. continue;
  26937. }
  26938. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  26939. m.isVisible = element.checked;
  26940. }, mesh);
  26941. }
  26942. };
  26943. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  26944. this._drawingContext.beginPath();
  26945. this._drawingContext.moveTo(zero.x, zero.y);
  26946. this._drawingContext.lineTo(unit.x, unit.y);
  26947. this._drawingContext.strokeStyle = color;
  26948. this._drawingContext.lineWidth = 4;
  26949. this._drawingContext.stroke();
  26950. this._drawingContext.font = "normal 14px Segoe UI";
  26951. this._drawingContext.fillStyle = color;
  26952. this._drawingContext.fillText(label, unitText.x, unitText.y);
  26953. };
  26954. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  26955. var position = mesh.getBoundingInfo().boundingSphere.center;
  26956. var worldMatrix = mesh.getWorldMatrix();
  26957. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  26958. var unit = (unprojectedVector.subtract(position)).length();
  26959. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  26960. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  26961. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  26962. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  26963. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  26964. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  26965. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  26966. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  26967. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  26968. };
  26969. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  26970. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  26971. this._drawingContext.font = "normal 12px Segoe UI";
  26972. var textMetrics = this._drawingContext.measureText(text);
  26973. var centerX = projectedPosition.x - textMetrics.width / 2;
  26974. var centerY = projectedPosition.y;
  26975. var clientRect = this._drawingCanvas.getBoundingClientRect();
  26976. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  26977. onClick();
  26978. }
  26979. this._drawingContext.beginPath();
  26980. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  26981. this._drawingContext.fillStyle = getFillStyle();
  26982. this._drawingContext.globalAlpha = 0.5;
  26983. this._drawingContext.fill();
  26984. this._drawingContext.globalAlpha = 1.0;
  26985. this._drawingContext.strokeStyle = '#FFFFFF';
  26986. this._drawingContext.lineWidth = 1;
  26987. this._drawingContext.stroke();
  26988. this._drawingContext.fillStyle = "#FFFFFF";
  26989. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  26990. this._drawingContext.beginPath();
  26991. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  26992. this._drawingContext.fill();
  26993. }
  26994. };
  26995. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  26996. if (!this._clickPosition) {
  26997. return false;
  26998. }
  26999. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  27000. return false;
  27001. }
  27002. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  27003. return false;
  27004. }
  27005. return true;
  27006. };
  27007. DebugLayer.prototype.isVisible = function () {
  27008. return this._enabled;
  27009. };
  27010. DebugLayer.prototype.hide = function () {
  27011. if (!this._enabled) {
  27012. return;
  27013. }
  27014. this._enabled = false;
  27015. var engine = this._scene.getEngine();
  27016. this._scene.unregisterBeforeRender(this._syncData);
  27017. document.body.removeChild(this._globalDiv);
  27018. window.removeEventListener("resize", this._syncPositions);
  27019. this._scene.forceShowBoundingBoxes = false;
  27020. this._scene.forceWireframe = false;
  27021. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  27022. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  27023. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  27024. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  27025. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  27026. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  27027. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  27028. this._scene.shadowsEnabled = true;
  27029. this._scene.particlesEnabled = true;
  27030. this._scene.postProcessesEnabled = true;
  27031. this._scene.collisionsEnabled = true;
  27032. this._scene.lightsEnabled = true;
  27033. this._scene.texturesEnabled = true;
  27034. this._scene.lensFlaresEnabled = true;
  27035. this._scene.proceduralTexturesEnabled = true;
  27036. this._scene.renderTargetsEnabled = true;
  27037. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  27038. };
  27039. DebugLayer.prototype.show = function (showUI, camera) {
  27040. if (showUI === void 0) { showUI = true; }
  27041. if (camera === void 0) { camera = null; }
  27042. if (this._enabled) {
  27043. return;
  27044. }
  27045. if (camera) {
  27046. this._camera = camera;
  27047. }
  27048. else {
  27049. this._camera = this._scene.activeCamera;
  27050. }
  27051. this._enabled = true;
  27052. this._showUI = showUI;
  27053. var engine = this._scene.getEngine();
  27054. this._globalDiv = document.createElement("div");
  27055. document.body.appendChild(this._globalDiv);
  27056. this._generateDOMelements();
  27057. window.addEventListener("resize", this._syncPositions);
  27058. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  27059. this._syncPositions();
  27060. this._scene.registerBeforeRender(this._syncData);
  27061. };
  27062. DebugLayer.prototype._clearLabels = function () {
  27063. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  27064. for (var index = 0; index < this._scene.meshes.length; index++) {
  27065. var mesh = this._scene.meshes[index];
  27066. mesh.renderOverlay = false;
  27067. }
  27068. };
  27069. DebugLayer.prototype._generateheader = function (root, text) {
  27070. var header = document.createElement("div");
  27071. header.innerHTML = text + "&nbsp;";
  27072. header.style.textAlign = "right";
  27073. header.style.width = "100%";
  27074. header.style.color = "white";
  27075. header.style.backgroundColor = "Black";
  27076. header.style.padding = "5px 5px 4px 0px";
  27077. header.style.marginLeft = "-5px";
  27078. header.style.fontWeight = "bold";
  27079. root.appendChild(header);
  27080. };
  27081. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  27082. var label = document.createElement("label");
  27083. label.innerHTML = title;
  27084. label.style.color = color;
  27085. root.appendChild(label);
  27086. root.appendChild(document.createElement("br"));
  27087. };
  27088. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  27089. if (tag === void 0) { tag = null; }
  27090. var label = document.createElement("label");
  27091. var boundingBoxesCheckbox = document.createElement("input");
  27092. boundingBoxesCheckbox.type = "checkbox";
  27093. boundingBoxesCheckbox.checked = initialState;
  27094. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  27095. task(evt.target, tag);
  27096. });
  27097. label.appendChild(boundingBoxesCheckbox);
  27098. var container = document.createElement("span");
  27099. var leftPart = document.createElement("span");
  27100. var rightPart = document.createElement("span");
  27101. rightPart.style.cssFloat = "right";
  27102. leftPart.innerHTML = leftTitle;
  27103. rightPart.innerHTML = rightTitle;
  27104. rightPart.style.fontSize = "12px";
  27105. rightPart.style.maxWidth = "200px";
  27106. container.appendChild(leftPart);
  27107. container.appendChild(rightPart);
  27108. label.appendChild(container);
  27109. root.appendChild(label);
  27110. root.appendChild(document.createElement("br"));
  27111. };
  27112. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  27113. if (tag === void 0) { tag = null; }
  27114. var label = document.createElement("label");
  27115. var checkBox = document.createElement("input");
  27116. checkBox.type = "checkbox";
  27117. checkBox.checked = initialState;
  27118. checkBox.addEventListener("change", function (evt) {
  27119. task(evt.target, tag);
  27120. });
  27121. label.appendChild(checkBox);
  27122. label.appendChild(document.createTextNode(title));
  27123. root.appendChild(label);
  27124. root.appendChild(document.createElement("br"));
  27125. };
  27126. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  27127. if (tag === void 0) { tag = null; }
  27128. var button = document.createElement("button");
  27129. button.innerHTML = title;
  27130. button.style.height = "20px";
  27131. button.style.color = "#222222";
  27132. button.addEventListener("click", function (evt) {
  27133. task(evt.target, tag);
  27134. });
  27135. root.appendChild(button);
  27136. root.appendChild(document.createElement("br"));
  27137. };
  27138. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  27139. if (tag === void 0) { tag = null; }
  27140. var label = document.createElement("label");
  27141. var boundingBoxesRadio = document.createElement("input");
  27142. boundingBoxesRadio.type = "radio";
  27143. boundingBoxesRadio.name = name;
  27144. boundingBoxesRadio.checked = initialState;
  27145. boundingBoxesRadio.addEventListener("change", function (evt) {
  27146. task(evt.target, tag);
  27147. });
  27148. label.appendChild(boundingBoxesRadio);
  27149. label.appendChild(document.createTextNode(title));
  27150. root.appendChild(label);
  27151. root.appendChild(document.createElement("br"));
  27152. };
  27153. DebugLayer.prototype._generateDOMelements = function () {
  27154. var _this = this;
  27155. this._globalDiv.id = "DebugLayer";
  27156. this._globalDiv.style.position = "absolute";
  27157. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  27158. this._globalDiv.style.fontSize = "14px";
  27159. this._globalDiv.style.color = "white";
  27160. // Drawing canvas
  27161. this._drawingCanvas = document.createElement("canvas");
  27162. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  27163. this._drawingCanvas.style.position = "absolute";
  27164. this._drawingCanvas.style.pointerEvents = "none";
  27165. this._drawingContext = this._drawingCanvas.getContext("2d");
  27166. this._globalDiv.appendChild(this._drawingCanvas);
  27167. if (this._showUI) {
  27168. var background = "rgba(128, 128, 128, 0.4)";
  27169. var border = "rgb(180, 180, 180) solid 1px";
  27170. // Stats
  27171. this._statsDiv = document.createElement("div");
  27172. this._statsDiv.id = "DebugLayerStats";
  27173. this._statsDiv.style.border = border;
  27174. this._statsDiv.style.position = "absolute";
  27175. this._statsDiv.style.background = background;
  27176. this._statsDiv.style.padding = "0px 0px 0px 5px";
  27177. this._generateheader(this._statsDiv, "STATISTICS");
  27178. this._statsSubsetDiv = document.createElement("div");
  27179. this._statsSubsetDiv.style.paddingTop = "5px";
  27180. this._statsSubsetDiv.style.paddingBottom = "5px";
  27181. this._statsSubsetDiv.style.overflowY = "auto";
  27182. this._statsDiv.appendChild(this._statsSubsetDiv);
  27183. // Tree
  27184. this._treeDiv = document.createElement("div");
  27185. this._treeDiv.id = "DebugLayerTree";
  27186. this._treeDiv.style.border = border;
  27187. this._treeDiv.style.position = "absolute";
  27188. this._treeDiv.style.background = background;
  27189. this._treeDiv.style.padding = "0px 0px 0px 5px";
  27190. this._treeDiv.style.display = "none";
  27191. this._generateheader(this._treeDiv, "MESHES TREE");
  27192. this._treeSubsetDiv = document.createElement("div");
  27193. this._treeSubsetDiv.style.paddingTop = "5px";
  27194. this._treeSubsetDiv.style.paddingRight = "5px";
  27195. this._treeSubsetDiv.style.overflowY = "auto";
  27196. this._treeSubsetDiv.style.maxHeight = "300px";
  27197. this._treeDiv.appendChild(this._treeSubsetDiv);
  27198. this._needToRefreshMeshesTree = true;
  27199. // Logs
  27200. this._logDiv = document.createElement("div");
  27201. this._logDiv.style.border = border;
  27202. this._logDiv.id = "DebugLayerLogs";
  27203. this._logDiv.style.position = "absolute";
  27204. this._logDiv.style.background = background;
  27205. this._logDiv.style.padding = "0px 0px 0px 5px";
  27206. this._logDiv.style.display = "none";
  27207. this._generateheader(this._logDiv, "LOGS");
  27208. this._logSubsetDiv = document.createElement("div");
  27209. this._logSubsetDiv.style.height = "127px";
  27210. this._logSubsetDiv.style.paddingTop = "5px";
  27211. this._logSubsetDiv.style.overflowY = "auto";
  27212. this._logSubsetDiv.style.fontSize = "12px";
  27213. this._logSubsetDiv.style.fontFamily = "consolas";
  27214. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  27215. this._logDiv.appendChild(this._logSubsetDiv);
  27216. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  27217. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  27218. };
  27219. // Options
  27220. this._optionsDiv = document.createElement("div");
  27221. this._optionsDiv.id = "DebugLayerOptions";
  27222. this._optionsDiv.style.border = border;
  27223. this._optionsDiv.style.position = "absolute";
  27224. this._optionsDiv.style.background = background;
  27225. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  27226. this._optionsDiv.style.overflowY = "auto";
  27227. this._generateheader(this._optionsDiv, "OPTIONS");
  27228. this._optionsSubsetDiv = document.createElement("div");
  27229. this._optionsSubsetDiv.style.paddingTop = "5px";
  27230. this._optionsSubsetDiv.style.paddingBottom = "5px";
  27231. this._optionsSubsetDiv.style.overflowY = "auto";
  27232. this._optionsSubsetDiv.style.maxHeight = "200px";
  27233. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  27234. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  27235. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) {
  27236. _this._displayStatistics = element.checked;
  27237. });
  27238. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) {
  27239. _this._displayLogs = element.checked;
  27240. });
  27241. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  27242. _this._displayTree = element.checked;
  27243. _this._needToRefreshMeshesTree = true;
  27244. });
  27245. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27246. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  27247. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) {
  27248. _this._scene.forceShowBoundingBoxes = element.checked;
  27249. });
  27250. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  27251. _this._labelsEnabled = element.checked;
  27252. if (!_this._labelsEnabled) {
  27253. _this._clearLabels();
  27254. }
  27255. });
  27256. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  27257. if (element.checked) {
  27258. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  27259. }
  27260. else {
  27261. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  27262. }
  27263. });
  27264. ;
  27265. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27266. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  27267. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  27268. if (element.checked) {
  27269. _this._scene.forceWireframe = false;
  27270. _this._scene.forcePointsCloud = false;
  27271. }
  27272. });
  27273. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  27274. if (element.checked) {
  27275. _this._scene.forceWireframe = true;
  27276. _this._scene.forcePointsCloud = false;
  27277. }
  27278. });
  27279. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  27280. if (element.checked) {
  27281. _this._scene.forceWireframe = false;
  27282. _this._scene.forcePointsCloud = true;
  27283. }
  27284. });
  27285. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27286. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  27287. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) {
  27288. BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked;
  27289. });
  27290. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) {
  27291. BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked;
  27292. });
  27293. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) {
  27294. BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked;
  27295. });
  27296. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) {
  27297. BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked;
  27298. });
  27299. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) {
  27300. BABYLON.StandardMaterial.BumpTextureEnabled = element.checked;
  27301. });
  27302. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) {
  27303. BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked;
  27304. });
  27305. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) {
  27306. BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked;
  27307. });
  27308. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) {
  27309. BABYLON.StandardMaterial.FresnelEnabled = element.checked;
  27310. });
  27311. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27312. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  27313. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) {
  27314. _this._scene.animationsEnabled = element.checked;
  27315. });
  27316. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) {
  27317. _this._scene.collisionsEnabled = element.checked;
  27318. });
  27319. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) {
  27320. _this._scene.fogEnabled = element.checked;
  27321. });
  27322. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) {
  27323. _this._scene.lensFlaresEnabled = element.checked;
  27324. });
  27325. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) {
  27326. _this._scene.lightsEnabled = element.checked;
  27327. });
  27328. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) {
  27329. _this._scene.particlesEnabled = element.checked;
  27330. });
  27331. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) {
  27332. _this._scene.postProcessesEnabled = element.checked;
  27333. });
  27334. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) {
  27335. _this._scene.proceduralTexturesEnabled = element.checked;
  27336. });
  27337. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) {
  27338. _this._scene.renderTargetsEnabled = element.checked;
  27339. });
  27340. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) {
  27341. _this._scene.shadowsEnabled = element.checked;
  27342. });
  27343. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) {
  27344. _this._scene.skeletonsEnabled = element.checked;
  27345. });
  27346. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) {
  27347. _this._scene.spritesEnabled = element.checked;
  27348. });
  27349. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) {
  27350. _this._scene.texturesEnabled = element.checked;
  27351. });
  27352. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27353. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27354. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  27355. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", true, function (element) {
  27356. if (element.checked) {
  27357. _this._scene.switchAudioModeForHeadphones();
  27358. }
  27359. });
  27360. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", false, function (element) {
  27361. if (element.checked) {
  27362. _this._scene.switchAudioModeForNormalSpeakers();
  27363. }
  27364. });
  27365. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  27366. _this._scene.audioEnabled = !element.checked;
  27367. });
  27368. }
  27369. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27370. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  27371. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) {
  27372. _this._scene.dumpNextRenderTargets = true;
  27373. });
  27374. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27375. this._globalDiv.appendChild(this._statsDiv);
  27376. this._globalDiv.appendChild(this._logDiv);
  27377. this._globalDiv.appendChild(this._optionsDiv);
  27378. this._globalDiv.appendChild(this._treeDiv);
  27379. }
  27380. };
  27381. DebugLayer.prototype._displayStats = function () {
  27382. var scene = this._scene;
  27383. var engine = scene.getEngine();
  27384. var glInfo = engine.getGlInfo();
  27385. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>" + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>" + "<b>Count</b><br>" + "Total meshes: " + scene.meshes.length + "<br>" + "Total vertices: " + scene.getTotalVertices() + "<br>" + "Total materials: " + scene.materials.length + "<br>" + "Total textures: " + scene.textures.length + "<br>" + "Active meshes: " + scene.getActiveMeshes().length + "<br>" + "Active vertices: " + scene.getActiveVertices() + "<br>" + "Active bones: " + scene.getActiveBones() + "<br>" + "Active particles: " + scene.getActiveParticles() + "<br>" + "<b>Draw calls: " + engine.drawCalls + "</b><br><br>" + "<b>Duration</b><br>" + "Meshes selection:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>" + "Render Targets: " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>" + "Particles: " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>" + "Sprites: " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br><br>" + "Render: <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b><br>" + "Frame: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>" + "Potential FPS: " + BABYLON.Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br><br>" + "</div>" + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>" + "<b>Extensions</b><br>" + "Std derivatives: " + (engine.getCaps().standardDerivatives ? "Yes" : "No") + "<br>" + "Compressed textures: " + (engine.getCaps().s3tc ? "Yes" : "No") + "<br>" + "Hardware instances: " + (engine.getCaps().instancedArrays ? "Yes" : "No") + "<br>" + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br>" + "32bits indices: " + (engine.getCaps().uintIndices ? "Yes" : "No") + "<br>" + "<b>Caps.</b><br>" + "Max textures units: " + engine.getCaps().maxTexturesImageUnits + "<br>" + "Max textures size: " + engine.getCaps().maxTextureSize + "<br>" + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br><br><br>" + "</div><br>" + "<b>Info</b><br>" + glInfo.version + "<br>" + glInfo.renderer + "<br>";
  27386. if (this.customStatsFunction) {
  27387. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  27388. }
  27389. };
  27390. return DebugLayer;
  27391. })();
  27392. BABYLON.DebugLayer = DebugLayer;
  27393. })(BABYLON || (BABYLON = {}));
  27394. //# sourceMappingURL=babylon.debugLayer.js.map
  27395. var BABYLON;
  27396. (function (BABYLON) {
  27397. var RawTexture = (function (_super) {
  27398. __extends(RawTexture, _super);
  27399. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  27400. if (generateMipMaps === void 0) { generateMipMaps = true; }
  27401. if (invertY === void 0) { invertY = false; }
  27402. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  27403. _super.call(this, null, scene, !generateMipMaps, invertY);
  27404. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  27405. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  27406. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  27407. }
  27408. // Statics
  27409. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  27410. if (generateMipMaps === void 0) { generateMipMaps = true; }
  27411. if (invertY === void 0) { invertY = false; }
  27412. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  27413. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  27414. };
  27415. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  27416. if (generateMipMaps === void 0) { generateMipMaps = true; }
  27417. if (invertY === void 0) { invertY = false; }
  27418. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  27419. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  27420. };
  27421. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  27422. if (generateMipMaps === void 0) { generateMipMaps = true; }
  27423. if (invertY === void 0) { invertY = false; }
  27424. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  27425. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  27426. };
  27427. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  27428. if (generateMipMaps === void 0) { generateMipMaps = true; }
  27429. if (invertY === void 0) { invertY = false; }
  27430. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  27431. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  27432. };
  27433. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  27434. if (generateMipMaps === void 0) { generateMipMaps = true; }
  27435. if (invertY === void 0) { invertY = false; }
  27436. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  27437. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  27438. };
  27439. return RawTexture;
  27440. })(BABYLON.Texture);
  27441. BABYLON.RawTexture = RawTexture;
  27442. })(BABYLON || (BABYLON = {}));
  27443. //# sourceMappingURL=babylon.rawTexture.js.map
  27444. var BABYLON;
  27445. (function (BABYLON) {
  27446. var IndexedVector2 = (function (_super) {
  27447. __extends(IndexedVector2, _super);
  27448. function IndexedVector2(original, index) {
  27449. _super.call(this, original.x, original.y);
  27450. this.index = index;
  27451. }
  27452. return IndexedVector2;
  27453. })(BABYLON.Vector2);
  27454. var PolygonPoints = (function () {
  27455. function PolygonPoints() {
  27456. this.elements = new Array();
  27457. }
  27458. PolygonPoints.prototype.add = function (originalPoints) {
  27459. var _this = this;
  27460. var result = new Array();
  27461. originalPoints.forEach(function (point) {
  27462. if (result.length === 0 || !(BABYLON.Tools.WithinEpsilon(point.x, result[0].x, 0.00001) && BABYLON.Tools.WithinEpsilon(point.y, result[0].y, 0.00001))) {
  27463. var newPoint = new IndexedVector2(point, _this.elements.length);
  27464. result.push(newPoint);
  27465. _this.elements.push(newPoint);
  27466. }
  27467. });
  27468. return result;
  27469. };
  27470. PolygonPoints.prototype.computeBounds = function () {
  27471. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  27472. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  27473. this.elements.forEach(function (point) {
  27474. // x
  27475. if (point.x < lmin.x) {
  27476. lmin.x = point.x;
  27477. }
  27478. else if (point.x > lmax.x) {
  27479. lmax.x = point.x;
  27480. }
  27481. // y
  27482. if (point.y < lmin.y) {
  27483. lmin.y = point.y;
  27484. }
  27485. else if (point.y > lmax.y) {
  27486. lmax.y = point.y;
  27487. }
  27488. });
  27489. return {
  27490. min: lmin,
  27491. max: lmax,
  27492. width: lmax.x - lmin.x,
  27493. height: lmax.y - lmin.y
  27494. };
  27495. };
  27496. return PolygonPoints;
  27497. })();
  27498. var Polygon = (function () {
  27499. function Polygon() {
  27500. }
  27501. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  27502. return [
  27503. new BABYLON.Vector2(xmin, ymin),
  27504. new BABYLON.Vector2(xmax, ymin),
  27505. new BABYLON.Vector2(xmax, ymax),
  27506. new BABYLON.Vector2(xmin, ymax)
  27507. ];
  27508. };
  27509. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  27510. if (cx === void 0) { cx = 0; }
  27511. if (cy === void 0) { cy = 0; }
  27512. if (numberOfSides === void 0) { numberOfSides = 32; }
  27513. var result = new Array();
  27514. var angle = 0;
  27515. var increment = (Math.PI * 2) / numberOfSides;
  27516. for (var i = 0; i < numberOfSides; i++) {
  27517. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  27518. angle -= increment;
  27519. }
  27520. return result;
  27521. };
  27522. Polygon.Parse = function (input) {
  27523. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  27524. var i, result = [];
  27525. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  27526. result.push(new poly2tri.Point(floats[i], floats[i + 1]));
  27527. }
  27528. return result;
  27529. };
  27530. Polygon.StartingAt = function (x, y) {
  27531. return BABYLON.Path2.StartingAt(x, y);
  27532. };
  27533. return Polygon;
  27534. })();
  27535. BABYLON.Polygon = Polygon;
  27536. var PolygonMeshBuilder = (function () {
  27537. function PolygonMeshBuilder(name, contours, scene) {
  27538. this._points = new PolygonPoints();
  27539. if (!("poly2tri" in window)) {
  27540. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  27541. }
  27542. this._name = name;
  27543. this._scene = scene;
  27544. var points;
  27545. if (contours instanceof BABYLON.Path2) {
  27546. points = contours.getPoints();
  27547. }
  27548. else {
  27549. points = contours;
  27550. }
  27551. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  27552. }
  27553. PolygonMeshBuilder.prototype.addHole = function (hole) {
  27554. this._swctx.addHole(this._points.add(hole));
  27555. return this;
  27556. };
  27557. PolygonMeshBuilder.prototype.build = function (updatable) {
  27558. if (updatable === void 0) { updatable = false; }
  27559. var result = new BABYLON.Mesh(this._name, this._scene);
  27560. var normals = [];
  27561. var positions = [];
  27562. var uvs = [];
  27563. var bounds = this._points.computeBounds();
  27564. this._points.elements.forEach(function (p) {
  27565. normals.push(0, 1.0, 0);
  27566. positions.push(p.x, 0, p.y);
  27567. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  27568. });
  27569. var indices = [];
  27570. this._swctx.triangulate();
  27571. this._swctx.getTriangles().forEach(function (triangle) {
  27572. triangle.getPoints().forEach(function (point) {
  27573. indices.push(point.index);
  27574. });
  27575. });
  27576. result.setVerticesData(positions, BABYLON.VertexBuffer.PositionKind, updatable);
  27577. result.setVerticesData(normals, BABYLON.VertexBuffer.NormalKind, updatable);
  27578. result.setVerticesData(uvs, BABYLON.VertexBuffer.UVKind, updatable);
  27579. result.setIndices(indices);
  27580. return result;
  27581. };
  27582. return PolygonMeshBuilder;
  27583. })();
  27584. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  27585. })(BABYLON || (BABYLON = {}));
  27586. //# sourceMappingURL=babylon.polygonMesh.js.mapvar BABYLON;
  27587. (function (BABYLON) {
  27588. var SimplificationSettings = (function () {
  27589. function SimplificationSettings(quality, distance) {
  27590. this.quality = quality;
  27591. this.distance = distance;
  27592. }
  27593. return SimplificationSettings;
  27594. })();
  27595. BABYLON.SimplificationSettings = SimplificationSettings;
  27596. /**
  27597. * The implemented types of simplification.
  27598. * At the moment only Quadratic Error Decimation is implemented.
  27599. */
  27600. (function (SimplificationType) {
  27601. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  27602. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  27603. var SimplificationType = BABYLON.SimplificationType;
  27604. var DecimationTriangle = (function () {
  27605. function DecimationTriangle(vertices) {
  27606. this.vertices = vertices;
  27607. this.error = new Array(4);
  27608. this.deleted = false;
  27609. this.isDirty = false;
  27610. this.borderFactor = 0;
  27611. }
  27612. return DecimationTriangle;
  27613. })();
  27614. BABYLON.DecimationTriangle = DecimationTriangle;
  27615. var DecimationVertex = (function () {
  27616. function DecimationVertex(position, normal, uv, id) {
  27617. this.position = position;
  27618. this.normal = normal;
  27619. this.uv = uv;
  27620. this.id = id;
  27621. this.isBorder = true;
  27622. this.q = new QuadraticMatrix();
  27623. this.triangleCount = 0;
  27624. this.triangleStart = 0;
  27625. }
  27626. return DecimationVertex;
  27627. })();
  27628. BABYLON.DecimationVertex = DecimationVertex;
  27629. var QuadraticMatrix = (function () {
  27630. function QuadraticMatrix(data) {
  27631. this.data = new Array(10);
  27632. for (var i = 0; i < 10; ++i) {
  27633. if (data && data[i]) {
  27634. this.data[i] = data[i];
  27635. }
  27636. else {
  27637. this.data[i] = 0;
  27638. }
  27639. }
  27640. }
  27641. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  27642. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] + this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] - this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  27643. return det;
  27644. };
  27645. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  27646. for (var i = 0; i < 10; ++i) {
  27647. this.data[i] += matrix.data[i];
  27648. }
  27649. };
  27650. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  27651. for (var i = 0; i < 10; ++i) {
  27652. this.data[i] += data[i];
  27653. }
  27654. };
  27655. QuadraticMatrix.prototype.add = function (matrix) {
  27656. var m = new QuadraticMatrix();
  27657. for (var i = 0; i < 10; ++i) {
  27658. m.data[i] = this.data[i] + matrix.data[i];
  27659. }
  27660. return m;
  27661. };
  27662. QuadraticMatrix.FromData = function (a, b, c, d) {
  27663. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  27664. };
  27665. //returning an array to avoid garbage collection
  27666. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  27667. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  27668. };
  27669. return QuadraticMatrix;
  27670. })();
  27671. BABYLON.QuadraticMatrix = QuadraticMatrix;
  27672. var Reference = (function () {
  27673. function Reference(vertexId, triangleId) {
  27674. this.vertexId = vertexId;
  27675. this.triangleId = triangleId;
  27676. }
  27677. return Reference;
  27678. })();
  27679. BABYLON.Reference = Reference;
  27680. /**
  27681. * An implementation of the Quadratic Error simplification algorithm.
  27682. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  27683. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  27684. * @author RaananW
  27685. */
  27686. var QuadraticErrorSimplification = (function () {
  27687. function QuadraticErrorSimplification(_mesh) {
  27688. this._mesh = _mesh;
  27689. this.initialised = false;
  27690. this.syncIterations = 5000;
  27691. this.aggressiveness = 7;
  27692. this.decimationIterations = 100;
  27693. }
  27694. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  27695. var _this = this;
  27696. this.initWithMesh(this._mesh, function () {
  27697. _this.runDecimation(settings, successCallback);
  27698. });
  27699. };
  27700. QuadraticErrorSimplification.prototype.runDecimation = function (settings, successCallback) {
  27701. var _this = this;
  27702. var targetCount = ~~(this.triangles.length * settings.quality);
  27703. var deletedTriangles = 0;
  27704. var triangleCount = this.triangles.length;
  27705. var iterationFunction = function (iteration, callback) {
  27706. setTimeout(function () {
  27707. if (iteration % 5 === 0) {
  27708. _this.updateMesh(iteration === 0);
  27709. }
  27710. for (var i = 0; i < _this.triangles.length; ++i) {
  27711. _this.triangles[i].isDirty = false;
  27712. }
  27713. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  27714. var trianglesIterator = function (i) {
  27715. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  27716. var t = _this.triangles[tIdx];
  27717. if (!t)
  27718. return;
  27719. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  27720. return;
  27721. }
  27722. for (var j = 0; j < 3; ++j) {
  27723. if (t.error[j] < threshold) {
  27724. var deleted0 = [];
  27725. var deleted1 = [];
  27726. var i0 = t.vertices[j];
  27727. var i1 = t.vertices[(j + 1) % 3];
  27728. var v0 = _this.vertices[i0];
  27729. var v1 = _this.vertices[i1];
  27730. if (v0.isBorder !== v1.isBorder)
  27731. continue;
  27732. var p = BABYLON.Vector3.Zero();
  27733. var n = BABYLON.Vector3.Zero();
  27734. var uv = BABYLON.Vector2.Zero();
  27735. var color = new BABYLON.Color4(0, 0, 0, 1);
  27736. _this.calculateError(v0, v1, p, n, uv, color);
  27737. var delTr = [];
  27738. if (_this.isFlipped(v0, i1, p, deleted0, t.borderFactor, delTr))
  27739. continue;
  27740. if (_this.isFlipped(v1, i0, p, deleted1, t.borderFactor, delTr))
  27741. continue;
  27742. if (delTr.length == 2 || delTr[0] === delTr[1]) {
  27743. continue;
  27744. }
  27745. v0.normal = n;
  27746. if (v0.uv)
  27747. v0.uv = uv;
  27748. else if (v0.color)
  27749. v0.color = color;
  27750. v0.q = v1.q.add(v0.q);
  27751. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  27752. continue;
  27753. if (p.equals(v0.position))
  27754. continue;
  27755. v0.position = p;
  27756. var tStart = _this.references.length;
  27757. deletedTriangles = _this.updateTriangles(v0.id, v0, deleted0, deletedTriangles);
  27758. deletedTriangles = _this.updateTriangles(v0.id, v1, deleted1, deletedTriangles);
  27759. var tCount = _this.references.length - tStart;
  27760. if (tCount <= v0.triangleCount) {
  27761. if (tCount) {
  27762. for (var c = 0; c < tCount; c++) {
  27763. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  27764. }
  27765. }
  27766. }
  27767. else {
  27768. v0.triangleStart = tStart;
  27769. }
  27770. v0.triangleCount = tCount;
  27771. break;
  27772. }
  27773. }
  27774. };
  27775. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () {
  27776. return (triangleCount - deletedTriangles <= targetCount);
  27777. });
  27778. }, 0);
  27779. };
  27780. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  27781. if (triangleCount - deletedTriangles <= targetCount)
  27782. loop.breakLoop();
  27783. else {
  27784. iterationFunction(loop.index, function () {
  27785. loop.executeNext();
  27786. });
  27787. }
  27788. }, function () {
  27789. setTimeout(function () {
  27790. successCallback(_this.reconstructMesh());
  27791. }, 0);
  27792. });
  27793. };
  27794. QuadraticErrorSimplification.prototype.initWithMesh = function (mesh, callback) {
  27795. var _this = this;
  27796. if (!mesh)
  27797. return;
  27798. this.vertices = [];
  27799. this.triangles = [];
  27800. this._mesh = mesh;
  27801. //It is assumed that a mesh has positions, normals and either uvs or colors.
  27802. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27803. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  27804. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  27805. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  27806. var indices = mesh.getIndices();
  27807. var vertexInit = function (i) {
  27808. var vertex = new DecimationVertex(BABYLON.Vector3.FromArray(positionData, i * 3), BABYLON.Vector3.FromArray(normalData, i * 3), null, i);
  27809. if (_this._mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  27810. vertex.uv = BABYLON.Vector2.FromArray(uvs, i * 2);
  27811. }
  27812. else if (_this._mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  27813. vertex.color = BABYLON.Color4.FromArray(colorsData, i * 4);
  27814. }
  27815. _this.vertices.push(vertex);
  27816. };
  27817. var totalVertices = mesh.getTotalVertices();
  27818. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, this.syncIterations, vertexInit, function () {
  27819. var indicesInit = function (i) {
  27820. var pos = i * 3;
  27821. var i0 = indices[pos + 0];
  27822. var i1 = indices[pos + 1];
  27823. var i2 = indices[pos + 2];
  27824. var triangle = new DecimationTriangle([_this.vertices[i0].id, _this.vertices[i1].id, _this.vertices[i2].id]);
  27825. _this.triangles.push(triangle);
  27826. };
  27827. BABYLON.AsyncLoop.SyncAsyncForLoop(indices.length / 3, _this.syncIterations, indicesInit, function () {
  27828. _this.init(callback);
  27829. });
  27830. });
  27831. };
  27832. QuadraticErrorSimplification.prototype.init = function (callback) {
  27833. var _this = this;
  27834. var triangleInit1 = function (i) {
  27835. var t = _this.triangles[i];
  27836. t.normal = BABYLON.Vector3.Cross(_this.vertices[t.vertices[1]].position.subtract(_this.vertices[t.vertices[0]].position), _this.vertices[t.vertices[2]].position.subtract(_this.vertices[t.vertices[0]].position)).normalize();
  27837. for (var j = 0; j < 3; j++) {
  27838. _this.vertices[t.vertices[j]].q.addArrayInPlace(QuadraticMatrix.DataFromNumbers(t.normal.x, t.normal.y, t.normal.z, -(BABYLON.Vector3.Dot(t.normal, _this.vertices[t.vertices[0]].position))));
  27839. }
  27840. };
  27841. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  27842. var triangleInit2 = function (i) {
  27843. var t = _this.triangles[i];
  27844. for (var j = 0; j < 3; ++j) {
  27845. t.error[j] = _this.calculateError(_this.vertices[t.vertices[j]], _this.vertices[t.vertices[(j + 1) % 3]]);
  27846. }
  27847. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  27848. };
  27849. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  27850. _this.initialised = true;
  27851. callback();
  27852. });
  27853. });
  27854. };
  27855. QuadraticErrorSimplification.prototype.reconstructMesh = function () {
  27856. var newTriangles = [];
  27857. var i;
  27858. for (i = 0; i < this.vertices.length; ++i) {
  27859. this.vertices[i].triangleCount = 0;
  27860. }
  27861. var t;
  27862. var j;
  27863. for (i = 0; i < this.triangles.length; ++i) {
  27864. if (!this.triangles[i].deleted) {
  27865. t = this.triangles[i];
  27866. for (j = 0; j < 3; ++j) {
  27867. this.vertices[t.vertices[j]].triangleCount = 1;
  27868. }
  27869. newTriangles.push(t);
  27870. }
  27871. }
  27872. var newVerticesOrder = [];
  27873. //compact vertices, get the IDs of the vertices used.
  27874. var dst = 0;
  27875. for (i = 0; i < this.vertices.length; ++i) {
  27876. if (this.vertices[i].triangleCount) {
  27877. this.vertices[i].triangleStart = dst;
  27878. this.vertices[dst].position = this.vertices[i].position;
  27879. this.vertices[dst].normal = this.vertices[i].normal;
  27880. this.vertices[dst].uv = this.vertices[i].uv;
  27881. this.vertices[dst].color = this.vertices[i].color;
  27882. newVerticesOrder.push(i);
  27883. dst++;
  27884. }
  27885. }
  27886. for (i = 0; i < newTriangles.length; ++i) {
  27887. t = newTriangles[i];
  27888. for (j = 0; j < 3; ++j) {
  27889. t.vertices[j] = this.vertices[t.vertices[j]].triangleStart;
  27890. }
  27891. }
  27892. this.vertices = this.vertices.slice(0, dst);
  27893. var newPositionData = [];
  27894. var newNormalData = [];
  27895. var newUVsData = [];
  27896. var newColorsData = [];
  27897. for (i = 0; i < newVerticesOrder.length; ++i) {
  27898. newPositionData.push(this.vertices[i].position.x);
  27899. newPositionData.push(this.vertices[i].position.y);
  27900. newPositionData.push(this.vertices[i].position.z);
  27901. newNormalData.push(this.vertices[i].normal.x);
  27902. newNormalData.push(this.vertices[i].normal.y);
  27903. newNormalData.push(this.vertices[i].normal.z);
  27904. if (this.vertices[i].uv) {
  27905. newUVsData.push(this.vertices[i].uv.x);
  27906. newUVsData.push(this.vertices[i].uv.y);
  27907. }
  27908. else if (this.vertices[i].color) {
  27909. newColorsData.push(this.vertices[i].color.r);
  27910. newColorsData.push(this.vertices[i].color.g);
  27911. newColorsData.push(this.vertices[i].color.b);
  27912. newColorsData.push(this.vertices[i].color.a);
  27913. }
  27914. }
  27915. var newIndicesArray = [];
  27916. for (i = 0; i < newTriangles.length; ++i) {
  27917. newIndicesArray.push(newTriangles[i].vertices[0]);
  27918. newIndicesArray.push(newTriangles[i].vertices[1]);
  27919. newIndicesArray.push(newTriangles[i].vertices[2]);
  27920. }
  27921. //not cloning, to avoid geometry problems. Creating a whole new mesh.
  27922. var newMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  27923. newMesh.material = this._mesh.material;
  27924. newMesh.parent = this._mesh.parent;
  27925. newMesh.setIndices(newIndicesArray);
  27926. newMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  27927. newMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  27928. if (newUVsData.length > 0)
  27929. newMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  27930. if (newColorsData.length > 0)
  27931. newMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  27932. //preparing the skeleton support
  27933. if (this._mesh.skeleton) {
  27934. }
  27935. return newMesh;
  27936. };
  27937. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, index2, point, deletedArray, borderFactor, delTr) {
  27938. for (var i = 0; i < vertex1.triangleCount; ++i) {
  27939. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  27940. if (t.deleted)
  27941. continue;
  27942. var s = this.references[vertex1.triangleStart + i].vertexId;
  27943. var id1 = t.vertices[(s + 1) % 3];
  27944. var id2 = t.vertices[(s + 2) % 3];
  27945. if ((id1 === index2 || id2 === index2) && borderFactor < 2) {
  27946. deletedArray[i] = true;
  27947. delTr.push(t);
  27948. continue;
  27949. }
  27950. var d1 = this.vertices[id1].position.subtract(point);
  27951. d1 = d1.normalize();
  27952. var d2 = this.vertices[id2].position.subtract(point);
  27953. d2 = d2.normalize();
  27954. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  27955. return true;
  27956. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  27957. deletedArray[i] = false;
  27958. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  27959. return true;
  27960. }
  27961. return false;
  27962. };
  27963. QuadraticErrorSimplification.prototype.updateTriangles = function (vertexId, vertex, deletedArray, deletedTriangles) {
  27964. var newDeleted = deletedTriangles;
  27965. for (var i = 0; i < vertex.triangleCount; ++i) {
  27966. var ref = this.references[vertex.triangleStart + i];
  27967. var t = this.triangles[ref.triangleId];
  27968. if (t.deleted)
  27969. continue;
  27970. if (deletedArray[i]) {
  27971. t.deleted = true;
  27972. newDeleted++;
  27973. continue;
  27974. }
  27975. t.vertices[ref.vertexId] = vertexId;
  27976. t.isDirty = true;
  27977. t.error[0] = this.calculateError(this.vertices[t.vertices[0]], this.vertices[t.vertices[1]]) + (t.borderFactor / 2);
  27978. t.error[1] = this.calculateError(this.vertices[t.vertices[1]], this.vertices[t.vertices[2]]) + (t.borderFactor / 2);
  27979. t.error[2] = this.calculateError(this.vertices[t.vertices[2]], this.vertices[t.vertices[0]]) + (t.borderFactor / 2);
  27980. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  27981. this.references.push(ref);
  27982. }
  27983. return newDeleted;
  27984. };
  27985. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  27986. for (var i = 0; i < this.vertices.length; ++i) {
  27987. var vCount = [];
  27988. var vId = [];
  27989. var v = this.vertices[i];
  27990. var j;
  27991. for (j = 0; j < v.triangleCount; ++j) {
  27992. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  27993. for (var ii = 0; ii < 3; ii++) {
  27994. var ofs = 0;
  27995. var id = triangle.vertices[ii];
  27996. while (ofs < vCount.length) {
  27997. if (vId[ofs] === id)
  27998. break;
  27999. ++ofs;
  28000. }
  28001. if (ofs === vCount.length) {
  28002. vCount.push(1);
  28003. vId.push(id);
  28004. }
  28005. else {
  28006. vCount[ofs]++;
  28007. }
  28008. }
  28009. }
  28010. for (j = 0; j < vCount.length; ++j) {
  28011. if (vCount[j] === 1) {
  28012. this.vertices[vId[j]].isBorder = true;
  28013. }
  28014. else {
  28015. this.vertices[vId[j]].isBorder = false;
  28016. }
  28017. }
  28018. }
  28019. };
  28020. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  28021. if (identifyBorders === void 0) { identifyBorders = false; }
  28022. var i;
  28023. if (!identifyBorders) {
  28024. var newTrianglesVector = [];
  28025. for (i = 0; i < this.triangles.length; ++i) {
  28026. if (!this.triangles[i].deleted) {
  28027. newTrianglesVector.push(this.triangles[i]);
  28028. }
  28029. }
  28030. this.triangles = newTrianglesVector;
  28031. }
  28032. for (i = 0; i < this.vertices.length; ++i) {
  28033. this.vertices[i].triangleCount = 0;
  28034. this.vertices[i].triangleStart = 0;
  28035. }
  28036. var t;
  28037. var j;
  28038. var v;
  28039. for (i = 0; i < this.triangles.length; ++i) {
  28040. t = this.triangles[i];
  28041. for (j = 0; j < 3; ++j) {
  28042. v = this.vertices[t.vertices[j]];
  28043. v.triangleCount++;
  28044. }
  28045. }
  28046. var tStart = 0;
  28047. for (i = 0; i < this.vertices.length; ++i) {
  28048. this.vertices[i].triangleStart = tStart;
  28049. tStart += this.vertices[i].triangleCount;
  28050. this.vertices[i].triangleCount = 0;
  28051. }
  28052. var newReferences = new Array(this.triangles.length * 3);
  28053. for (i = 0; i < this.triangles.length; ++i) {
  28054. t = this.triangles[i];
  28055. for (j = 0; j < 3; ++j) {
  28056. v = this.vertices[t.vertices[j]];
  28057. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  28058. v.triangleCount++;
  28059. }
  28060. }
  28061. this.references = newReferences;
  28062. if (identifyBorders) {
  28063. this.identifyBorder();
  28064. }
  28065. };
  28066. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  28067. var x = point.x;
  28068. var y = point.y;
  28069. var z = point.z;
  28070. return q.data[0] * x * x + 2 * q.data[1] * x * y + 2 * q.data[2] * x * z + 2 * q.data[3] * x + q.data[4] * y * y + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  28071. };
  28072. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  28073. var q = vertex1.q.add(vertex2.q);
  28074. var border = vertex1.isBorder && vertex2.isBorder;
  28075. var error = 0;
  28076. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  28077. if (qDet !== 0 && !border) {
  28078. if (!pointResult) {
  28079. pointResult = BABYLON.Vector3.Zero();
  28080. }
  28081. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  28082. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  28083. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  28084. error = this.vertexError(q, pointResult);
  28085. //TODO this should be correctly calculated
  28086. if (normalResult) {
  28087. normalResult.copyFrom(vertex1.normal);
  28088. if (vertex1.uv)
  28089. uvResult.copyFrom(vertex1.uv);
  28090. else if (vertex1.color)
  28091. colorResult.copyFrom(vertex1.color);
  28092. }
  28093. }
  28094. else {
  28095. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  28096. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  28097. var error1 = this.vertexError(q, vertex1.position);
  28098. var error2 = this.vertexError(q, vertex2.position);
  28099. var error3 = this.vertexError(q, p3);
  28100. error = Math.min(error1, error2, error3);
  28101. if (error === error1) {
  28102. if (pointResult) {
  28103. pointResult.copyFrom(vertex1.position);
  28104. normalResult.copyFrom(vertex1.normal);
  28105. if (vertex1.uv)
  28106. uvResult.copyFrom(vertex1.uv);
  28107. else if (vertex1.color)
  28108. colorResult.copyFrom(vertex1.color);
  28109. }
  28110. }
  28111. else if (error === error2) {
  28112. if (pointResult) {
  28113. pointResult.copyFrom(vertex2.position);
  28114. normalResult.copyFrom(vertex2.normal);
  28115. if (vertex2.uv)
  28116. uvResult.copyFrom(vertex2.uv);
  28117. else if (vertex2.color)
  28118. colorResult.copyFrom(vertex2.color);
  28119. }
  28120. }
  28121. else {
  28122. if (pointResult) {
  28123. pointResult.copyFrom(p3);
  28124. normalResult.copyFrom(vertex1.normal);
  28125. if (vertex1.uv)
  28126. uvResult.copyFrom(vertex1.uv);
  28127. else if (vertex1.color)
  28128. colorResult.copyFrom(vertex1.color);
  28129. }
  28130. }
  28131. }
  28132. return error;
  28133. };
  28134. return QuadraticErrorSimplification;
  28135. })();
  28136. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  28137. })(BABYLON || (BABYLON = {}));
  28138. //# sourceMappingURL=babylon.meshSimplification.js.mapvar BABYLON;
  28139. (function (BABYLON) {
  28140. var Analyser = (function () {
  28141. function Analyser(scene) {
  28142. this.SMOOTHING = 0.75;
  28143. this.FFT_SIZE = 512;
  28144. this.BARGRAPHAMPLITUDE = 256;
  28145. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  28146. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  28147. this._scene = scene;
  28148. this._audioEngine = BABYLON.Engine.audioEngine;
  28149. if (this._audioEngine.canUseWebAudio) {
  28150. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  28151. this._webAudioAnalyser.minDecibels = -140;
  28152. this._webAudioAnalyser.maxDecibels = 0;
  28153. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  28154. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  28155. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  28156. }
  28157. }
  28158. Analyser.prototype.getFrequencyBinCount = function () {
  28159. if (this._audioEngine.canUseWebAudio) {
  28160. return this._webAudioAnalyser.frequencyBinCount;
  28161. }
  28162. else {
  28163. return 0;
  28164. }
  28165. };
  28166. Analyser.prototype.getByteFrequencyData = function () {
  28167. if (this._audioEngine.canUseWebAudio) {
  28168. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  28169. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  28170. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  28171. }
  28172. return this._byteFreqs;
  28173. };
  28174. Analyser.prototype.getByteTimeDomainData = function () {
  28175. if (this._audioEngine.canUseWebAudio) {
  28176. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  28177. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  28178. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  28179. }
  28180. return this._byteTime;
  28181. };
  28182. Analyser.prototype.getFloatFrequencyData = function () {
  28183. if (this._audioEngine.canUseWebAudio) {
  28184. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  28185. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  28186. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  28187. }
  28188. return this._floatFreqs;
  28189. };
  28190. Analyser.prototype.drawDebugCanvas = function () {
  28191. var _this = this;
  28192. if (this._audioEngine.canUseWebAudio) {
  28193. if (!this._debugCanvas) {
  28194. this._debugCanvas = document.createElement("canvas");
  28195. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  28196. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  28197. this._debugCanvas.style.position = "absolute";
  28198. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  28199. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  28200. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  28201. document.body.appendChild(this._debugCanvas);
  28202. this._registerFunc = function () {
  28203. _this.drawDebugCanvas();
  28204. };
  28205. this._scene.registerBeforeRender(this._registerFunc);
  28206. }
  28207. if (this._registerFunc) {
  28208. var workingArray = this.getByteFrequencyData();
  28209. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  28210. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  28211. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  28212. var value = workingArray[i];
  28213. var percent = value / this.BARGRAPHAMPLITUDE;
  28214. var height = this.DEBUGCANVASSIZE.height * percent;
  28215. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  28216. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  28217. var hue = i / this.getFrequencyBinCount() * 360;
  28218. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  28219. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  28220. }
  28221. }
  28222. }
  28223. };
  28224. Analyser.prototype.stopDebugCanvas = function () {
  28225. if (this._debugCanvas) {
  28226. this._scene.unregisterBeforeRender(this._registerFunc);
  28227. this._registerFunc = null;
  28228. document.body.removeChild(this._debugCanvas);
  28229. this._debugCanvas = null;
  28230. this._debugCanvasContext = null;
  28231. }
  28232. };
  28233. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  28234. if (this._audioEngine.canUseWebAudio) {
  28235. inputAudioNode.connect(this._webAudioAnalyser);
  28236. this._webAudioAnalyser.connect(outputAudioNode);
  28237. }
  28238. };
  28239. Analyser.prototype.dispose = function () {
  28240. if (this._audioEngine.canUseWebAudio) {
  28241. this._webAudioAnalyser.disconnect();
  28242. }
  28243. };
  28244. return Analyser;
  28245. })();
  28246. BABYLON.Analyser = Analyser;
  28247. })(BABYLON || (BABYLON = {}));
  28248. //# sourceMappingURL=babylon.analyser.js.mapvar BABYLON;
  28249. (function (BABYLON) {
  28250. var DepthRenderer = (function () {
  28251. function DepthRenderer(scene, type) {
  28252. var _this = this;
  28253. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  28254. this._viewMatrix = BABYLON.Matrix.Zero();
  28255. this._projectionMatrix = BABYLON.Matrix.Zero();
  28256. this._transformMatrix = BABYLON.Matrix.Zero();
  28257. this._worldViewProjection = BABYLON.Matrix.Zero();
  28258. this._scene = scene;
  28259. var engine = scene.getEngine();
  28260. // Render target
  28261. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  28262. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  28263. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  28264. this._depthMap.refreshRate = 1;
  28265. this._depthMap.renderParticles = false;
  28266. this._depthMap.renderList = null;
  28267. // Custom render function
  28268. var renderSubMesh = function (subMesh) {
  28269. var mesh = subMesh.getRenderingMesh();
  28270. var scene = _this._scene;
  28271. var engine = scene.getEngine();
  28272. // Culling
  28273. engine.setState(subMesh.getMaterial().backFaceCulling);
  28274. // Managing instances
  28275. var batch = mesh._getInstancesRenderList(subMesh._id);
  28276. if (batch.mustReturn) {
  28277. return;
  28278. }
  28279. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  28280. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  28281. engine.enableEffect(_this._effect);
  28282. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  28283. var material = subMesh.getMaterial();
  28284. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  28285. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  28286. // Alpha test
  28287. if (material && material.needAlphaTesting()) {
  28288. var alphaTexture = material.getAlphaTestTexture();
  28289. _this._effect.setTexture("diffuseSampler", alphaTexture);
  28290. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  28291. }
  28292. // Bones
  28293. if (mesh.useBones) {
  28294. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  28295. }
  28296. // Draw
  28297. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  28298. }
  28299. };
  28300. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  28301. var index;
  28302. for (index = 0; index < opaqueSubMeshes.length; index++) {
  28303. renderSubMesh(opaqueSubMeshes.data[index]);
  28304. }
  28305. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  28306. renderSubMesh(alphaTestSubMeshes.data[index]);
  28307. }
  28308. };
  28309. }
  28310. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  28311. var defines = [];
  28312. var attribs = [BABYLON.VertexBuffer.PositionKind];
  28313. var mesh = subMesh.getMesh();
  28314. var scene = mesh.getScene();
  28315. var material = subMesh.getMaterial();
  28316. // Alpha test
  28317. if (material && material.needAlphaTesting()) {
  28318. defines.push("#define ALPHATEST");
  28319. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  28320. attribs.push(BABYLON.VertexBuffer.UVKind);
  28321. defines.push("#define UV1");
  28322. }
  28323. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  28324. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  28325. defines.push("#define UV2");
  28326. }
  28327. }
  28328. // Bones
  28329. if (mesh.useBones) {
  28330. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  28331. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  28332. defines.push("#define BONES");
  28333. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  28334. }
  28335. // Instances
  28336. if (useInstances) {
  28337. defines.push("#define INSTANCES");
  28338. attribs.push("world0");
  28339. attribs.push("world1");
  28340. attribs.push("world2");
  28341. attribs.push("world3");
  28342. }
  28343. // Get correct effect
  28344. var join = defines.join("\n");
  28345. if (this._cachedDefines !== join) {
  28346. this._cachedDefines = join;
  28347. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  28348. }
  28349. return this._effect.isReady();
  28350. };
  28351. DepthRenderer.prototype.getDepthMap = function () {
  28352. return this._depthMap;
  28353. };
  28354. // Methods
  28355. DepthRenderer.prototype.dispose = function () {
  28356. this._depthMap.dispose();
  28357. };
  28358. return DepthRenderer;
  28359. })();
  28360. BABYLON.DepthRenderer = DepthRenderer;
  28361. })(BABYLON || (BABYLON = {}));
  28362. //# sourceMappingURL=babylon.depthRenderer.js.map
  28363. var BABYLON;
  28364. (function (BABYLON) {
  28365. var SSAORenderingPipeline = (function (_super) {
  28366. __extends(SSAORenderingPipeline, _super);
  28367. /**
  28368. * @constructor
  28369. * @param {string} name - The rendering pipeline name
  28370. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  28371. * @param {any} ratio - The size of the postprocesses (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)
  28372. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  28373. */
  28374. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  28375. var _this = this;
  28376. _super.call(this, scene.getEngine(), name);
  28377. // Members
  28378. /**
  28379. * The PassPostProcess id in the pipeline that contains the original scene color
  28380. * @type {string}
  28381. */
  28382. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  28383. /**
  28384. * The SSAO PostProcess id in the pipeline
  28385. * @type {string}
  28386. */
  28387. this.SSAORenderEffect = "SSAORenderEffect";
  28388. /**
  28389. * The horizontal blur PostProcess id in the pipeline
  28390. * @type {string}
  28391. */
  28392. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  28393. /**
  28394. * The vertical blur PostProcess id in the pipeline
  28395. * @type {string}
  28396. */
  28397. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  28398. /**
  28399. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  28400. * @type {string}
  28401. */
  28402. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  28403. this._firstUpdate = true;
  28404. this._scene = scene;
  28405. // Set up assets
  28406. this._createRandomTexture();
  28407. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  28408. var ssaoRatio = ratio.ssaoRatio || ratio;
  28409. var combineRatio = ratio.combineRatio || ratio;
  28410. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  28411. this._createSSAOPostProcess(ssaoRatio);
  28412. this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlurH", new BABYLON.Vector2(2.0, 0.0), 1.3, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  28413. this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlurV", new BABYLON.Vector2(0.0, 2.0), 1.3, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  28414. this._createSSAOCombinePostProcess(combineRatio);
  28415. // Set up pipeline
  28416. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () {
  28417. return _this._originalColorPostProcess;
  28418. }, true));
  28419. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () {
  28420. return _this._ssaoPostProcess;
  28421. }, true));
  28422. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () {
  28423. return _this._blurHPostProcess;
  28424. }, true));
  28425. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () {
  28426. return _this._blurVPostProcess;
  28427. }, true));
  28428. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () {
  28429. return _this._ssaoCombinePostProcess;
  28430. }, true));
  28431. // Finish
  28432. scene.postProcessRenderPipelineManager.addPipeline(this);
  28433. if (cameras)
  28434. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  28435. }
  28436. // Public Methods
  28437. /**
  28438. * Returns the horizontal blur PostProcess
  28439. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  28440. */
  28441. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  28442. return this._blurHPostProcess;
  28443. };
  28444. /**
  28445. * Returns the vertical blur PostProcess
  28446. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  28447. */
  28448. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  28449. return this._blurVPostProcess;
  28450. };
  28451. /**
  28452. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  28453. */
  28454. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  28455. if (disableDepthRender === void 0) { disableDepthRender = false; }
  28456. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  28457. this._originalColorPostProcess = undefined;
  28458. this._ssaoPostProcess = undefined;
  28459. this._blurHPostProcess = undefined;
  28460. this._blurVPostProcess = undefined;
  28461. this._ssaoCombinePostProcess = undefined;
  28462. this._randomTexture.dispose();
  28463. if (disableDepthRender)
  28464. this._scene.disableDepthRenderer();
  28465. };
  28466. // Private Methods
  28467. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  28468. var _this = this;
  28469. var sampleSphere = [
  28470. 0.5381,
  28471. 0.1856,
  28472. -0.4319,
  28473. 0.1379,
  28474. 0.2486,
  28475. 0.4430,
  28476. 0.3371,
  28477. 0.5679,
  28478. -0.0057,
  28479. -0.6999,
  28480. -0.0451,
  28481. -0.0019,
  28482. 0.0689,
  28483. -0.1598,
  28484. -0.8547,
  28485. 0.0560,
  28486. 0.0069,
  28487. -0.1843,
  28488. -0.0146,
  28489. 0.1402,
  28490. 0.0762,
  28491. 0.0100,
  28492. -0.1924,
  28493. -0.0344,
  28494. -0.3577,
  28495. -0.5301,
  28496. -0.4358,
  28497. -0.3169,
  28498. 0.1063,
  28499. 0.0158,
  28500. 0.0103,
  28501. -0.5869,
  28502. 0.0046,
  28503. -0.0897,
  28504. -0.4940,
  28505. 0.3287,
  28506. 0.7119,
  28507. -0.0154,
  28508. -0.0918,
  28509. -0.0533,
  28510. 0.0596,
  28511. -0.5411,
  28512. 0.0352,
  28513. -0.0631,
  28514. 0.5460,
  28515. -0.4776,
  28516. 0.2847,
  28517. -0.0271
  28518. ];
  28519. var samplesFactor = 1.0 / 16.0;
  28520. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", ["sampleSphere", "samplesFactor", "randTextureTiles"], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  28521. this._ssaoPostProcess.onApply = function (effect) {
  28522. if (_this._firstUpdate) {
  28523. effect.setArray3("sampleSphere", sampleSphere);
  28524. effect.setFloat("samplesFactor", samplesFactor);
  28525. effect.setFloat("randTextureTiles", 4.0 / ratio);
  28526. _this._firstUpdate = false;
  28527. }
  28528. effect.setTexture("textureSampler", _this._depthTexture);
  28529. effect.setTexture("randomSampler", _this._randomTexture);
  28530. };
  28531. };
  28532. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  28533. var _this = this;
  28534. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  28535. this._ssaoCombinePostProcess.onApply = function (effect) {
  28536. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  28537. };
  28538. };
  28539. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  28540. var size = 512;
  28541. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  28542. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  28543. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  28544. var context = this._randomTexture.getContext();
  28545. var rand = function (min, max) {
  28546. return Math.random() * (max - min) + min;
  28547. };
  28548. for (var x = 0; x < size; x++) {
  28549. for (var y = 0; y < size; y++) {
  28550. var randVector = BABYLON.Vector3.Zero();
  28551. randVector.x = Math.floor(rand(0.0, 1.0) * 255);
  28552. randVector.y = Math.floor(rand(0.0, 1.0) * 255);
  28553. randVector.z = Math.floor(rand(0.0, 1.0) * 255);
  28554. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  28555. context.fillRect(x, y, 1, 1);
  28556. }
  28557. }
  28558. this._randomTexture.update(false);
  28559. };
  28560. return SSAORenderingPipeline;
  28561. })(BABYLON.PostProcessRenderPipeline);
  28562. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  28563. })(BABYLON || (BABYLON = {}));
  28564. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  28565. var BABYLON;
  28566. (function (BABYLON) {
  28567. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  28568. var VolumetricLightScatteringPostProcess = (function (_super) {
  28569. __extends(VolumetricLightScatteringPostProcess, _super);
  28570. /**
  28571. * @constructor
  28572. * @param {string} name - The post-process name
  28573. * @param {any} ratio - The size of the post-process and/or internal pass (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)
  28574. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  28575. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  28576. * @param {number} samples - The post-process quality, default 100
  28577. * @param {number} samplingMode - The post-process filtering mode
  28578. * @param {BABYLON.Engine} engine - The babylon engine
  28579. * @param {boolean} reusable - If the post-process is reusable
  28580. */
  28581. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable) {
  28582. var _this = this;
  28583. if (samples === void 0) { samples = 100; }
  28584. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  28585. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  28586. this._screenCoordinates = BABYLON.Vector2.Zero();
  28587. /**
  28588. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  28589. * @type {boolean}
  28590. */
  28591. this.useCustomMeshPosition = false;
  28592. /**
  28593. * If the post-process should inverse the light scattering direction
  28594. * @type {boolean}
  28595. */
  28596. this.invert = true;
  28597. /**
  28598. * Array containing the excluded meshes not rendered in the internal pass
  28599. */
  28600. this.excludedMeshes = new Array();
  28601. this.exposure = 0.3;
  28602. this.decay = 0.96815;
  28603. this.weight = 0.58767;
  28604. this.density = 0.926;
  28605. var scene = camera.getScene();
  28606. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(scene.getEngine());
  28607. // Configure mesh
  28608. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  28609. // Configure
  28610. this._createPass(scene, ratio.passRatio || ratio);
  28611. this.onApply = function (effect) {
  28612. _this._updateMeshScreenCoordinates(scene);
  28613. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  28614. effect.setFloat("exposure", _this.exposure);
  28615. effect.setFloat("decay", _this.decay);
  28616. effect.setFloat("weight", _this.weight);
  28617. effect.setFloat("density", _this.density);
  28618. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  28619. };
  28620. }
  28621. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  28622. var mesh = subMesh.getMesh();
  28623. var defines = [];
  28624. var attribs = [BABYLON.VertexBuffer.PositionKind];
  28625. var material = subMesh.getMaterial();
  28626. // Render this.mesh as default
  28627. if (mesh === this.mesh) {
  28628. defines.push("#define BASIC_RENDER");
  28629. }
  28630. // Alpha test
  28631. if (material) {
  28632. if (material.needAlphaTesting() || mesh === this.mesh)
  28633. defines.push("#define ALPHATEST");
  28634. if (material.opacityTexture !== undefined)
  28635. defines.push("#define OPACITY");
  28636. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  28637. attribs.push(BABYLON.VertexBuffer.UVKind);
  28638. defines.push("#define UV1");
  28639. }
  28640. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  28641. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  28642. defines.push("#define UV2");
  28643. }
  28644. }
  28645. // Bones
  28646. if (mesh.useBones) {
  28647. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  28648. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  28649. defines.push("#define BONES");
  28650. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  28651. }
  28652. // Instances
  28653. if (useInstances) {
  28654. defines.push("#define INSTANCES");
  28655. attribs.push("world0");
  28656. attribs.push("world1");
  28657. attribs.push("world2");
  28658. attribs.push("world3");
  28659. }
  28660. // Get correct effect
  28661. var join = defines.join("\n");
  28662. if (this._cachedDefines !== join) {
  28663. this._cachedDefines = join;
  28664. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler", "opacitySampler"], join);
  28665. }
  28666. return this._volumetricLightScatteringPass.isReady();
  28667. };
  28668. /**
  28669. * Sets the new light position for light scattering effect
  28670. * @param {BABYLON.Vector3} The new custom light position
  28671. */
  28672. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  28673. this._customMeshPosition = position;
  28674. };
  28675. /**
  28676. * Returns the light position for light scattering effect
  28677. * @return {BABYLON.Vector3} The custom light position
  28678. */
  28679. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  28680. return this._customMeshPosition;
  28681. };
  28682. /**
  28683. * Disposes the internal assets and detaches the post-process from the camera
  28684. */
  28685. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  28686. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  28687. if (rttIndex !== -1) {
  28688. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  28689. }
  28690. this._volumetricLightScatteringRTT.dispose();
  28691. _super.prototype.dispose.call(this, camera);
  28692. };
  28693. /**
  28694. * Returns the render target texture used by the post-process
  28695. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  28696. */
  28697. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  28698. return this._volumetricLightScatteringRTT;
  28699. };
  28700. // Private methods
  28701. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  28702. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  28703. return true;
  28704. }
  28705. return false;
  28706. };
  28707. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  28708. var _this = this;
  28709. var engine = scene.getEngine();
  28710. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  28711. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  28712. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  28713. this._volumetricLightScatteringRTT.renderList = null;
  28714. this._volumetricLightScatteringRTT.renderParticles = false;
  28715. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  28716. // Custom render function for submeshes
  28717. var renderSubMesh = function (subMesh) {
  28718. var mesh = subMesh.getRenderingMesh();
  28719. if (_this._meshExcluded(mesh)) {
  28720. return;
  28721. }
  28722. var scene = mesh.getScene();
  28723. var engine = scene.getEngine();
  28724. // Culling
  28725. engine.setState(subMesh.getMaterial().backFaceCulling);
  28726. // Managing instances
  28727. var batch = mesh._getInstancesRenderList(subMesh._id);
  28728. if (batch.mustReturn) {
  28729. return;
  28730. }
  28731. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  28732. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  28733. engine.enableEffect(_this._volumetricLightScatteringPass);
  28734. mesh._bind(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode);
  28735. var material = subMesh.getMaterial();
  28736. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  28737. // Alpha test
  28738. if (material && (mesh === _this.mesh || material.needAlphaTesting() || material.opacityTexture !== undefined)) {
  28739. var alphaTexture = material.getAlphaTestTexture();
  28740. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  28741. if (_this.mesh.material && alphaTexture)
  28742. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  28743. if (material.opacityTexture !== undefined)
  28744. _this._volumetricLightScatteringPass.setTexture("opacitySampler", material.opacityTexture);
  28745. }
  28746. // Bones
  28747. if (mesh.useBones) {
  28748. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  28749. }
  28750. // Draw
  28751. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._volumetricLightScatteringPass.setMatrix("world", world); });
  28752. }
  28753. };
  28754. // Render target texture callbacks
  28755. var savedSceneClearColor;
  28756. var sceneClearColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  28757. this._volumetricLightScatteringRTT.onBeforeRender = function () {
  28758. savedSceneClearColor = scene.clearColor;
  28759. scene.clearColor = sceneClearColor;
  28760. };
  28761. this._volumetricLightScatteringRTT.onAfterRender = function () {
  28762. scene.clearColor = savedSceneClearColor;
  28763. };
  28764. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  28765. var index;
  28766. for (index = 0; index < opaqueSubMeshes.length; index++) {
  28767. renderSubMesh(opaqueSubMeshes.data[index]);
  28768. }
  28769. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  28770. renderSubMesh(alphaTestSubMeshes.data[index]);
  28771. }
  28772. for (index = 0; index < transparentSubMeshes.length; index++) {
  28773. renderSubMesh(transparentSubMeshes.data[index]);
  28774. }
  28775. };
  28776. };
  28777. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  28778. var transform = scene.getTransformMatrix();
  28779. var pos = BABYLON.Vector3.Project(this.useCustomMeshPosition ? this._customMeshPosition : this.mesh.position, BABYLON.Matrix.Identity(), transform, this._viewPort);
  28780. this._screenCoordinates.x = pos.x / this._viewPort.width;
  28781. this._screenCoordinates.y = pos.y / this._viewPort.height;
  28782. if (this.invert)
  28783. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  28784. };
  28785. // Static methods
  28786. /**
  28787. * Creates a default mesh for the Volumeric Light Scattering post-process
  28788. * @param {string} The mesh name
  28789. * @param {BABYLON.Scene} The scene where to create the mesh
  28790. * @return {BABYLON.Mesh} the default mesh
  28791. */
  28792. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  28793. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  28794. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  28795. mesh.material = new BABYLON.StandardMaterial(name + "Material", scene);
  28796. return mesh;
  28797. };
  28798. return VolumetricLightScatteringPostProcess;
  28799. })(BABYLON.PostProcess);
  28800. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  28801. })(BABYLON || (BABYLON = {}));
  28802. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  28803. var BABYLON;
  28804. (function (BABYLON) {
  28805. var LensRenderingPipeline = (function (_super) {
  28806. __extends(LensRenderingPipeline, _super);
  28807. /**
  28808. * @constructor
  28809. * @param {string} name - The rendering pipeline name
  28810. * @param {object} parameters - An object containing all parameters (see below)
  28811. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  28812. * @param {number} ratio - The size of the postprocesses (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)
  28813. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  28814. Effect parameters are as follow:
  28815. {
  28816. chromatic_aberration: number; // from 0 to x (1 for realism)
  28817. edge_blur: number; // from 0 to x (1 for realism)
  28818. distortion: number; // from 0 to x (1 for realism)
  28819. grain_amount: number; // from 0 to 1
  28820. grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  28821. dof_focus_depth: number; // depth-of-field: focus depth; unset to disable
  28822. dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  28823. dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  28824. dof_gain: boolean; // depth-of-field: depthOfField gain (default: 1)
  28825. dof_threshold: boolean; // depth-of-field: depthOfField threshold (default: 1)
  28826. blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  28827. }
  28828. Note: if an effect parameter is unset, effect is disabled
  28829. */
  28830. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  28831. var _this = this;
  28832. if (ratio === void 0) { ratio = 1.0; }
  28833. _super.call(this, scene.getEngine(), name);
  28834. // Lens effects can be of the following:
  28835. // - chromatic aberration (slight shift of RGB colors)
  28836. // - blur on the edge of the lens
  28837. // - lens distortion
  28838. // - depth-of-field 'bokeh' effect (shapes appearing in blured areas, stronger highlights)
  28839. // - grain/dust-on-lens effect
  28840. // Two additional texture samplers are needed:
  28841. // - depth map (for depth-of-field)
  28842. // - grain texture
  28843. /**
  28844. * The chromatic aberration PostProcess id in the pipeline
  28845. * @type {string}
  28846. */
  28847. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  28848. /**
  28849. * The depth-of-field PostProcess id in the pipeline
  28850. * @type {string}
  28851. */
  28852. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  28853. this._scene = scene;
  28854. // Fetch texture samplers
  28855. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  28856. if (parameters.grain_texture) {
  28857. this._grainTexture = parameters.grain_texture;
  28858. }
  28859. else {
  28860. this._createGrainTexture();
  28861. }
  28862. // save parameters
  28863. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  28864. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  28865. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  28866. this._distortion = parameters.distortion ? parameters.distortion : 0;
  28867. this._highlightsGain = parameters.dof_gain ? parameters.dof_gain : 1;
  28868. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  28869. this._dofDepth = parameters.dof_focus_depth !== undefined ? parameters.dof_focus_depth : -1;
  28870. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  28871. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  28872. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  28873. // Create effects
  28874. this._createChromaticAberrationPostProcess(ratio);
  28875. this._createDepthOfFieldPostProcess(ratio);
  28876. // Set up pipeline
  28877. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () {
  28878. return _this._chromaticAberrationPostProcess;
  28879. }, true));
  28880. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () {
  28881. return _this._depthOfFieldPostProcess;
  28882. }, true));
  28883. // Finish
  28884. scene.postProcessRenderPipelineManager.addPipeline(this);
  28885. if (cameras) {
  28886. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  28887. }
  28888. }
  28889. // public methods
  28890. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) {
  28891. this._edgeBlur = amount;
  28892. };
  28893. LensRenderingPipeline.prototype.disableEdgeBlur = function () {
  28894. this._edgeBlur = 0;
  28895. };
  28896. LensRenderingPipeline.prototype.setGrainAmount = function (amount) {
  28897. this._grainAmount = amount;
  28898. };
  28899. LensRenderingPipeline.prototype.disableGrain = function () {
  28900. this._grainAmount = 0;
  28901. };
  28902. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) {
  28903. this._chromaticAberration = amount;
  28904. };
  28905. LensRenderingPipeline.prototype.disableChromaticAberration = function () {
  28906. this._chromaticAberration = 0;
  28907. };
  28908. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) {
  28909. this._distortion = amount;
  28910. };
  28911. LensRenderingPipeline.prototype.disableEdgeDistortion = function () {
  28912. this._distortion = 0;
  28913. };
  28914. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  28915. this._highlightsGain = amount;
  28916. };
  28917. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  28918. this._highlightsThreshold = amount;
  28919. };
  28920. LensRenderingPipeline.prototype.setFocusDepth = function (amount) {
  28921. this._dofDepth = amount;
  28922. };
  28923. LensRenderingPipeline.prototype.disableDepthOfField = function () {
  28924. this._dofDepth = -1;
  28925. };
  28926. LensRenderingPipeline.prototype.setAperture = function (amount) {
  28927. this._dofAperture = amount;
  28928. };
  28929. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  28930. this._dofPentagon = true;
  28931. };
  28932. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  28933. this._dofPentagon = false;
  28934. };
  28935. LensRenderingPipeline.prototype.enableNoiseBlur = function () {
  28936. this._blurNoise = true;
  28937. };
  28938. LensRenderingPipeline.prototype.disableNoiseBlur = function () {
  28939. this._blurNoise = false;
  28940. };
  28941. /**
  28942. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  28943. */
  28944. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  28945. if (disableDepthRender === void 0) { disableDepthRender = false; }
  28946. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  28947. this._chromaticAberrationPostProcess = undefined;
  28948. this._depthOfFieldPostProcess = undefined;
  28949. this._grainTexture.dispose();
  28950. if (disableDepthRender)
  28951. this._scene.disableDepthRenderer();
  28952. };
  28953. // colors shifting and distortion
  28954. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  28955. var _this = this;
  28956. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], [], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  28957. this._chromaticAberrationPostProcess.onApply = function (effect) {
  28958. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  28959. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  28960. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  28961. };
  28962. };
  28963. // colors shifting and distortion
  28964. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  28965. var _this = this;
  28966. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  28967. "gain",
  28968. "threshold",
  28969. "focus_depth",
  28970. "aperture",
  28971. "pentagon",
  28972. "maxZ",
  28973. "edge_blur",
  28974. "chromatic_aberration",
  28975. "distortion",
  28976. "blur_noise",
  28977. "grain_amount",
  28978. "screen_width",
  28979. "screen_height"
  28980. ], ["depthSampler", "grainSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  28981. this._depthOfFieldPostProcess.onApply = function (effect) {
  28982. effect.setBool('pentagon', _this._dofPentagon);
  28983. effect.setBool('blur_noise', _this._blurNoise);
  28984. effect.setFloat('maxZ', _this._scene.activeCamera.maxZ);
  28985. effect.setFloat('grain_amount', _this._grainAmount);
  28986. effect.setTexture("depthSampler", _this._depthTexture);
  28987. effect.setTexture("grainSampler", _this._grainTexture);
  28988. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  28989. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  28990. effect.setFloat('distortion', _this._distortion);
  28991. effect.setFloat('focus_depth', _this._dofDepth);
  28992. effect.setFloat('aperture', _this._dofAperture);
  28993. effect.setFloat('gain', _this._highlightsGain);
  28994. effect.setFloat('threshold', _this._highlightsThreshold);
  28995. effect.setFloat('edge_blur', _this._edgeBlur);
  28996. };
  28997. };
  28998. // creates a black and white random noise texture, 512x512
  28999. LensRenderingPipeline.prototype._createGrainTexture = function () {
  29000. var size = 512;
  29001. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  29002. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  29003. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  29004. var context = this._grainTexture.getContext();
  29005. var rand = function (min, max) {
  29006. return Math.random() * (max - min) + min;
  29007. };
  29008. var value;
  29009. for (var x = 0; x < size; x++) {
  29010. for (var y = 0; y < size; y++) {
  29011. value = Math.floor(rand(0.42, 0.58) * 255);
  29012. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  29013. context.fillRect(x, y, 1, 1);
  29014. }
  29015. }
  29016. this._grainTexture.update(false);
  29017. };
  29018. return LensRenderingPipeline;
  29019. })(BABYLON.PostProcessRenderPipeline);
  29020. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  29021. })(BABYLON || (BABYLON = {}));
  29022. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map