babylon.2.1-alpha.debug.js 1.4 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915
  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.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  639. var v = SIMD.float32x4.loadXYZ(vector._data, 0);
  640. var m0 = SIMD.float32x4.load(transformation.m, 0);
  641. var m1 = SIMD.float32x4.load(transformation.m, 4);
  642. var m2 = SIMD.float32x4.load(transformation.m, 8);
  643. var m3 = SIMD.float32x4.load(transformation.m, 12);
  644. var r = SIMD.float32x4.add(SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(v, 0, 0, 0, 0), m0), SIMD.float32x4.mul(SIMD.float32x4.swizzle(v, 1, 1, 1, 1), m1)), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(v, 2, 2, 2, 2), m2), m3));
  645. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  646. SIMD.float32x4.storeXYZ(result._data, 0, r);
  647. };
  648. Vector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  649. var v0 = SIMD.float32x4.splat(x);
  650. var v1 = SIMD.float32x4.splat(y);
  651. var v2 = SIMD.float32x4.splat(z);
  652. var m0 = SIMD.float32x4.load(transformation.m, 0);
  653. var m1 = SIMD.float32x4.load(transformation.m, 4);
  654. var m2 = SIMD.float32x4.load(transformation.m, 8);
  655. var m3 = SIMD.float32x4.load(transformation.m, 12);
  656. var r = SIMD.float32x4.add(SIMD.float32x4.add(SIMD.float32x4.mul(v0, m0), SIMD.float32x4.mul(v1, m1)), SIMD.float32x4.add(SIMD.float32x4.mul(v2, m2), m3));
  657. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  658. SIMD.float32x4.storeXYZ(result._data, 0, r);
  659. };
  660. Vector3.TransformNormal = function (vector, transformation) {
  661. var result = Vector3.Zero();
  662. Vector3.TransformNormalToRef(vector, transformation, result);
  663. return result;
  664. };
  665. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  666. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  667. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  668. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  669. };
  670. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  671. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  672. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  673. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  674. };
  675. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  676. var squared = amount * amount;
  677. var cubed = amount * squared;
  678. 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));
  679. 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));
  680. 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));
  681. return new Vector3(x, y, z);
  682. };
  683. Vector3.Clamp = function (value, min, max) {
  684. var x = value.x;
  685. x = (x > max.x) ? max.x : x;
  686. x = (x < min.x) ? min.x : x;
  687. var y = value.y;
  688. y = (y > max.y) ? max.y : y;
  689. y = (y < min.y) ? min.y : y;
  690. var z = value.z;
  691. z = (z > max.z) ? max.z : z;
  692. z = (z < min.z) ? min.z : z;
  693. return new Vector3(x, y, z);
  694. };
  695. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  696. var squared = amount * amount;
  697. var cubed = amount * squared;
  698. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  699. var part2 = (-2.0 * cubed) + (3.0 * squared);
  700. var part3 = (cubed - (2.0 * squared)) + amount;
  701. var part4 = cubed - squared;
  702. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  703. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  704. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  705. return new Vector3(x, y, z);
  706. };
  707. Vector3.Lerp = function (start, end, amount) {
  708. var x = start.x + ((end.x - start.x) * amount);
  709. var y = start.y + ((end.y - start.y) * amount);
  710. var z = start.z + ((end.z - start.z) * amount);
  711. return new Vector3(x, y, z);
  712. };
  713. Vector3.Dot = function (left, right) {
  714. return (left.x * right.x + left.y * right.y + left.z * right.z);
  715. };
  716. Vector3.Cross = function (left, right) {
  717. var result = Vector3.Zero();
  718. Vector3.CrossToRef(left, right, result);
  719. return result;
  720. };
  721. Vector3.CrossToRef = function (left, right, result) {
  722. result.x = left.y * right.z - left.z * right.y;
  723. result.y = left.z * right.x - left.x * right.z;
  724. result.z = left.x * right.y - left.y * right.x;
  725. };
  726. Vector3.Normalize = function (vector) {
  727. var result = Vector3.Zero();
  728. Vector3.NormalizeToRef(vector, result);
  729. return result;
  730. };
  731. Vector3.NormalizeToRef = function (vector, result) {
  732. result.copyFrom(vector);
  733. result.normalize();
  734. };
  735. Vector3.Project = function (vector, world, transform, viewport) {
  736. var cw = viewport.width;
  737. var ch = viewport.height;
  738. var cx = viewport.x;
  739. var cy = viewport.y;
  740. 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);
  741. var finalMatrix = world.multiply(transform).multiply(viewportMatrix);
  742. return Vector3.TransformCoordinates(vector, finalMatrix);
  743. };
  744. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  745. var matrix = world.multiply(transform);
  746. matrix.invert();
  747. source.x = source.x / viewportWidth * 2 - 1;
  748. source.y = -(source.y / viewportHeight * 2 - 1);
  749. var vector = Vector3.TransformCoordinates(source, matrix);
  750. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  751. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  752. vector = vector.scale(1.0 / num);
  753. }
  754. return vector;
  755. };
  756. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  757. var matrix = world.multiply(view).multiply(projection);
  758. matrix.invert();
  759. source.x = source.x / viewportWidth * 2 - 1;
  760. source.y = -(source.y / viewportHeight * 2 - 1);
  761. var vector = Vector3.TransformCoordinates(source, matrix);
  762. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  763. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  764. vector = vector.scale(1.0 / num);
  765. }
  766. return vector;
  767. };
  768. Vector3.Minimize = function (left, right) {
  769. var min = left.clone();
  770. min.MinimizeInPlace(right);
  771. return min;
  772. };
  773. Vector3.Maximize = function (left, right) {
  774. var max = left.clone();
  775. max.MaximizeInPlace(right);
  776. return max;
  777. };
  778. Vector3.Distance = function (value1, value2) {
  779. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  780. };
  781. Vector3.DistanceSquared = function (value1, value2) {
  782. var x = value1.x - value2.x;
  783. var y = value1.y - value2.y;
  784. var z = value1.z - value2.z;
  785. return (x * x) + (y * y) + (z * z);
  786. };
  787. Vector3.Center = function (value1, value2) {
  788. var center = value1.add(value2);
  789. center.scaleInPlace(0.5);
  790. return center;
  791. };
  792. return Vector3;
  793. })();
  794. BABYLON.Vector3 = Vector3;
  795. //Vector4 class created for EulerAngle class conversion to Quaternion
  796. var Vector4 = (function () {
  797. function Vector4(x, y, z, w) {
  798. this.x = x;
  799. this.y = y;
  800. this.z = z;
  801. this.w = w;
  802. }
  803. Vector4.prototype.toString = function () {
  804. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  805. };
  806. // Operators
  807. Vector4.prototype.asArray = function () {
  808. var result = [];
  809. this.toArray(result, 0);
  810. return result;
  811. };
  812. Vector4.prototype.toArray = function (array, index) {
  813. if (index === undefined) {
  814. index = 0;
  815. }
  816. array[index] = this.x;
  817. array[index + 1] = this.y;
  818. array[index + 2] = this.z;
  819. array[index + 3] = this.w;
  820. return this;
  821. };
  822. Vector4.prototype.addInPlace = function (otherVector) {
  823. this.x += otherVector.x;
  824. this.y += otherVector.y;
  825. this.z += otherVector.z;
  826. this.w += otherVector.w;
  827. return this;
  828. };
  829. Vector4.prototype.add = function (otherVector) {
  830. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  831. };
  832. Vector4.prototype.addToRef = function (otherVector, result) {
  833. result.x = this.x + otherVector.x;
  834. result.y = this.y + otherVector.y;
  835. result.z = this.z + otherVector.z;
  836. result.w = this.w + otherVector.w;
  837. return this;
  838. };
  839. Vector4.prototype.subtractInPlace = function (otherVector) {
  840. this.x -= otherVector.x;
  841. this.y -= otherVector.y;
  842. this.z -= otherVector.z;
  843. this.w -= otherVector.w;
  844. return this;
  845. };
  846. Vector4.prototype.subtract = function (otherVector) {
  847. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  848. };
  849. Vector4.prototype.subtractToRef = function (otherVector, result) {
  850. result.x = this.x - otherVector.x;
  851. result.y = this.y - otherVector.y;
  852. result.z = this.z - otherVector.z;
  853. result.w = this.w - otherVector.w;
  854. return this;
  855. };
  856. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  857. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  858. };
  859. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  860. result.x = this.x - x;
  861. result.y = this.y - y;
  862. result.z = this.z - z;
  863. result.w = this.w - w;
  864. return this;
  865. };
  866. Vector4.prototype.negate = function () {
  867. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  868. };
  869. Vector4.prototype.scaleInPlace = function (scale) {
  870. this.x *= scale;
  871. this.y *= scale;
  872. this.z *= scale;
  873. this.w *= scale;
  874. return this;
  875. };
  876. Vector4.prototype.scale = function (scale) {
  877. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  878. };
  879. Vector4.prototype.scaleToRef = function (scale, result) {
  880. result.x = this.x * scale;
  881. result.y = this.y * scale;
  882. result.z = this.z * scale;
  883. result.w = this.w * scale;
  884. };
  885. Vector4.prototype.equals = function (otherVector) {
  886. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  887. };
  888. Vector4.prototype.equalsWithEpsilon = function (otherVector) {
  889. 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;
  890. };
  891. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  892. return this.x === x && this.y === y && this.z === z && this.w === w;
  893. };
  894. Vector4.prototype.multiplyInPlace = function (otherVector) {
  895. this.x *= otherVector.x;
  896. this.y *= otherVector.y;
  897. this.z *= otherVector.z;
  898. this.w *= otherVector.w;
  899. return this;
  900. };
  901. Vector4.prototype.multiply = function (otherVector) {
  902. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  903. };
  904. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  905. result.x = this.x * otherVector.x;
  906. result.y = this.y * otherVector.y;
  907. result.z = this.z * otherVector.z;
  908. result.w = this.w * otherVector.w;
  909. return this;
  910. };
  911. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  912. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  913. };
  914. Vector4.prototype.divide = function (otherVector) {
  915. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  916. };
  917. Vector4.prototype.divideToRef = function (otherVector, result) {
  918. result.x = this.x / otherVector.x;
  919. result.y = this.y / otherVector.y;
  920. result.z = this.z / otherVector.z;
  921. result.w = this.w / otherVector.w;
  922. return this;
  923. };
  924. Vector4.prototype.MinimizeInPlace = function (other) {
  925. if (other.x < this.x)
  926. this.x = other.x;
  927. if (other.y < this.y)
  928. this.y = other.y;
  929. if (other.z < this.z)
  930. this.z = other.z;
  931. if (other.w < this.w)
  932. this.w = other.w;
  933. return this;
  934. };
  935. Vector4.prototype.MaximizeInPlace = function (other) {
  936. if (other.x > this.x)
  937. this.x = other.x;
  938. if (other.y > this.y)
  939. this.y = other.y;
  940. if (other.z > this.z)
  941. this.z = other.z;
  942. if (other.w > this.w)
  943. this.w = other.w;
  944. return this;
  945. };
  946. // Properties
  947. Vector4.prototype.length = function () {
  948. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  949. };
  950. Vector4.prototype.lengthSquared = function () {
  951. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  952. };
  953. // Methods
  954. Vector4.prototype.normalize = function () {
  955. var len = this.length();
  956. if (len === 0)
  957. return this;
  958. var num = 1.0 / len;
  959. this.x *= num;
  960. this.y *= num;
  961. this.z *= num;
  962. this.w *= num;
  963. return this;
  964. };
  965. Vector4.prototype.clone = function () {
  966. return new Vector4(this.x, this.y, this.z, this.w);
  967. };
  968. Vector4.prototype.copyFrom = function (source) {
  969. this.x = source.x;
  970. this.y = source.y;
  971. this.z = source.z;
  972. this.w = source.w;
  973. return this;
  974. };
  975. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  976. this.x = x;
  977. this.y = y;
  978. this.z = z;
  979. this.w = w;
  980. return this;
  981. };
  982. // Statics
  983. Vector4.FromArray = function (array, offset) {
  984. if (!offset) {
  985. offset = 0;
  986. }
  987. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  988. };
  989. Vector4.FromArrayToRef = function (array, offset, result) {
  990. result.x = array[offset];
  991. result.y = array[offset + 1];
  992. result.z = array[offset + 2];
  993. result.w = array[offset + 3];
  994. };
  995. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  996. result.x = array[offset];
  997. result.y = array[offset + 1];
  998. result.z = array[offset + 2];
  999. result.w = array[offset + 3];
  1000. };
  1001. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  1002. result.x = x;
  1003. result.y = y;
  1004. result.z = z;
  1005. result.w = w;
  1006. };
  1007. Vector4.Zero = function () {
  1008. return new Vector4(0, 0, 0, 0);
  1009. };
  1010. Vector4.Normalize = function (vector) {
  1011. var result = Vector4.Zero();
  1012. Vector4.NormalizeToRef(vector, result);
  1013. return result;
  1014. };
  1015. Vector4.NormalizeToRef = function (vector, result) {
  1016. result.copyFrom(vector);
  1017. result.normalize();
  1018. };
  1019. Vector4.Minimize = function (left, right) {
  1020. var min = left.clone();
  1021. min.MinimizeInPlace(right);
  1022. return min;
  1023. };
  1024. Vector4.Maximize = function (left, right) {
  1025. var max = left.clone();
  1026. max.MaximizeInPlace(right);
  1027. return max;
  1028. };
  1029. Vector4.Distance = function (value1, value2) {
  1030. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  1031. };
  1032. Vector4.DistanceSquared = function (value1, value2) {
  1033. var x = value1.x - value2.x;
  1034. var y = value1.y - value2.y;
  1035. var z = value1.z - value2.z;
  1036. var w = value1.w - value2.w;
  1037. return (x * x) + (y * y) + (z * z) + (w * w);
  1038. };
  1039. Vector4.Center = function (value1, value2) {
  1040. var center = value1.add(value2);
  1041. center.scaleInPlace(0.5);
  1042. return center;
  1043. };
  1044. return Vector4;
  1045. })();
  1046. BABYLON.Vector4 = Vector4;
  1047. var Quaternion = (function () {
  1048. function Quaternion(x, y, z, w) {
  1049. if (x === void 0) { x = 0; }
  1050. if (y === void 0) { y = 0; }
  1051. if (z === void 0) { z = 0; }
  1052. if (w === void 0) { w = 1; }
  1053. this.x = x;
  1054. this.y = y;
  1055. this.z = z;
  1056. this.w = w;
  1057. }
  1058. Quaternion.prototype.toString = function () {
  1059. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1060. };
  1061. Quaternion.prototype.asArray = function () {
  1062. return [this.x, this.y, this.z, this.w];
  1063. };
  1064. Quaternion.prototype.equals = function (otherQuaternion) {
  1065. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1066. };
  1067. Quaternion.prototype.clone = function () {
  1068. return new Quaternion(this.x, this.y, this.z, this.w);
  1069. };
  1070. Quaternion.prototype.copyFrom = function (other) {
  1071. this.x = other.x;
  1072. this.y = other.y;
  1073. this.z = other.z;
  1074. this.w = other.w;
  1075. return this;
  1076. };
  1077. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1078. this.x = x;
  1079. this.y = y;
  1080. this.z = z;
  1081. this.w = w;
  1082. return this;
  1083. };
  1084. Quaternion.prototype.add = function (other) {
  1085. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1086. };
  1087. Quaternion.prototype.subtract = function (other) {
  1088. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1089. };
  1090. Quaternion.prototype.scale = function (value) {
  1091. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1092. };
  1093. Quaternion.prototype.multiply = function (q1) {
  1094. var result = new Quaternion(0, 0, 0, 1.0);
  1095. this.multiplyToRef(q1, result);
  1096. return result;
  1097. };
  1098. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1099. result.x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1100. result.y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1101. result.z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1102. result.w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1103. return this;
  1104. };
  1105. Quaternion.prototype.length = function () {
  1106. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1107. };
  1108. Quaternion.prototype.normalize = function () {
  1109. var length = 1.0 / this.length();
  1110. this.x *= length;
  1111. this.y *= length;
  1112. this.z *= length;
  1113. this.w *= length;
  1114. return this;
  1115. };
  1116. Quaternion.prototype.toEulerAngles = function () {
  1117. var result = Vector3.Zero();
  1118. this.toEulerAnglesToRef(result);
  1119. return result;
  1120. };
  1121. Quaternion.prototype.toEulerAnglesToRef = function (result) {
  1122. //result is an EulerAngles in the in the z-x-z convention
  1123. var qx = this.x;
  1124. var qy = this.y;
  1125. var qz = this.z;
  1126. var qw = this.w;
  1127. var qxy = qx * qy;
  1128. var qxz = qx * qz;
  1129. var qwy = qw * qy;
  1130. var qwz = qw * qz;
  1131. var qwx = qw * qx;
  1132. var qyz = qy * qz;
  1133. var sqx = qx * qx;
  1134. var sqy = qy * qy;
  1135. var determinant = sqx + sqy;
  1136. if (determinant !== 0.000 && determinant !== 1.000) {
  1137. result.x = Math.atan2(qxz + qwy, qwx - qyz);
  1138. result.y = Math.acos(1 - 2 * determinant);
  1139. result.z = Math.atan2(qxz - qwy, qwx + qyz);
  1140. }
  1141. else {
  1142. if (determinant === 0.0) {
  1143. result.x = 0.0;
  1144. result.y = 0.0;
  1145. 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)
  1146. }
  1147. else {
  1148. 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)
  1149. result.y = Math.PI;
  1150. result.z = 0.0;
  1151. }
  1152. }
  1153. return this;
  1154. };
  1155. Quaternion.prototype.toRotationMatrix = function (result) {
  1156. var xx = this.x * this.x;
  1157. var yy = this.y * this.y;
  1158. var zz = this.z * this.z;
  1159. var xy = this.x * this.y;
  1160. var zw = this.z * this.w;
  1161. var zx = this.z * this.x;
  1162. var yw = this.y * this.w;
  1163. var yz = this.y * this.z;
  1164. var xw = this.x * this.w;
  1165. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1166. result.m[1] = 2.0 * (xy + zw);
  1167. result.m[2] = 2.0 * (zx - yw);
  1168. result.m[3] = 0;
  1169. result.m[4] = 2.0 * (xy - zw);
  1170. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1171. result.m[6] = 2.0 * (yz + xw);
  1172. result.m[7] = 0;
  1173. result.m[8] = 2.0 * (zx + yw);
  1174. result.m[9] = 2.0 * (yz - xw);
  1175. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1176. result.m[11] = 0;
  1177. result.m[12] = 0;
  1178. result.m[13] = 0;
  1179. result.m[14] = 0;
  1180. result.m[15] = 1.0;
  1181. return this;
  1182. };
  1183. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1184. Quaternion.FromRotationMatrixToRef(matrix, this);
  1185. return this;
  1186. };
  1187. // Statics
  1188. Quaternion.FromRotationMatrix = function (matrix) {
  1189. var result = new Quaternion();
  1190. Quaternion.FromRotationMatrixToRef(matrix, result);
  1191. return result;
  1192. };
  1193. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1194. var data = matrix.m;
  1195. var m11 = data[0], m12 = data[4], m13 = data[8];
  1196. var m21 = data[1], m22 = data[5], m23 = data[9];
  1197. var m31 = data[2], m32 = data[6], m33 = data[10];
  1198. var trace = m11 + m22 + m33;
  1199. var s;
  1200. if (trace > 0) {
  1201. s = 0.5 / Math.sqrt(trace + 1.0);
  1202. result.w = 0.25 / s;
  1203. result.x = (m32 - m23) * s;
  1204. result.y = (m13 - m31) * s;
  1205. result.z = (m21 - m12) * s;
  1206. }
  1207. else if (m11 > m22 && m11 > m33) {
  1208. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1209. result.w = (m32 - m23) / s;
  1210. result.x = 0.25 * s;
  1211. result.y = (m12 + m21) / s;
  1212. result.z = (m13 + m31) / s;
  1213. }
  1214. else if (m22 > m33) {
  1215. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1216. result.w = (m13 - m31) / s;
  1217. result.x = (m12 + m21) / s;
  1218. result.y = 0.25 * s;
  1219. result.z = (m23 + m32) / s;
  1220. }
  1221. else {
  1222. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1223. result.w = (m21 - m12) / s;
  1224. result.x = (m13 + m31) / s;
  1225. result.y = (m23 + m32) / s;
  1226. result.z = 0.25 * s;
  1227. }
  1228. };
  1229. Quaternion.Inverse = function (q) {
  1230. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1231. };
  1232. Quaternion.Identity = function () {
  1233. return new Quaternion(0, 0, 0, 1);
  1234. };
  1235. Quaternion.RotationAxis = function (axis, angle) {
  1236. var result = new Quaternion();
  1237. var sin = Math.sin(angle / 2);
  1238. result.w = Math.cos(angle / 2);
  1239. result.x = axis.x * sin;
  1240. result.y = axis.y * sin;
  1241. result.z = axis.z * sin;
  1242. return result;
  1243. };
  1244. Quaternion.FromArray = function (array, offset) {
  1245. if (!offset) {
  1246. offset = 0;
  1247. }
  1248. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1249. };
  1250. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1251. var result = new Quaternion();
  1252. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1253. return result;
  1254. };
  1255. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1256. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1257. var halfRoll = roll * 0.5;
  1258. var halfPitch = pitch * 0.5;
  1259. var halfYaw = yaw * 0.5;
  1260. var sinRoll = Math.sin(halfRoll);
  1261. var cosRoll = Math.cos(halfRoll);
  1262. var sinPitch = Math.sin(halfPitch);
  1263. var cosPitch = Math.cos(halfPitch);
  1264. var sinYaw = Math.sin(halfYaw);
  1265. var cosYaw = Math.cos(halfYaw);
  1266. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1267. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1268. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1269. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1270. };
  1271. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1272. var result = new Quaternion();
  1273. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1274. return result;
  1275. };
  1276. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1277. // Produces a quaternion from Euler angles in the z-x-z orientation
  1278. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1279. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1280. var halfBeta = beta * 0.5;
  1281. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1282. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1283. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1284. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1285. };
  1286. Quaternion.Slerp = function (left, right, amount) {
  1287. var num2;
  1288. var num3;
  1289. var num = amount;
  1290. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1291. var flag = false;
  1292. if (num4 < 0) {
  1293. flag = true;
  1294. num4 = -num4;
  1295. }
  1296. if (num4 > 0.999999) {
  1297. num3 = 1 - num;
  1298. num2 = flag ? -num : num;
  1299. }
  1300. else {
  1301. var num5 = Math.acos(num4);
  1302. var num6 = (1.0 / Math.sin(num5));
  1303. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1304. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1305. }
  1306. 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));
  1307. };
  1308. return Quaternion;
  1309. })();
  1310. BABYLON.Quaternion = Quaternion;
  1311. var Matrix = (function () {
  1312. function Matrix() {
  1313. this.m = new Float32Array(16);
  1314. }
  1315. // Properties
  1316. Matrix.prototype.isIdentity = function () {
  1317. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1318. return false;
  1319. 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)
  1320. return false;
  1321. return true;
  1322. };
  1323. Matrix.prototype.determinant = function () {
  1324. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1325. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1326. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1327. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1328. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1329. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1330. 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))));
  1331. };
  1332. // Methods
  1333. Matrix.prototype.toArray = function () {
  1334. return this.m;
  1335. };
  1336. Matrix.prototype.asArray = function () {
  1337. return this.toArray();
  1338. };
  1339. Matrix.prototype.invert = function () {
  1340. this.invertToRef(this);
  1341. return this;
  1342. };
  1343. Matrix.prototype.invertToRef = function (other) {
  1344. var l1 = this.m[0];
  1345. var l2 = this.m[1];
  1346. var l3 = this.m[2];
  1347. var l4 = this.m[3];
  1348. var l5 = this.m[4];
  1349. var l6 = this.m[5];
  1350. var l7 = this.m[6];
  1351. var l8 = this.m[7];
  1352. var l9 = this.m[8];
  1353. var l10 = this.m[9];
  1354. var l11 = this.m[10];
  1355. var l12 = this.m[11];
  1356. var l13 = this.m[12];
  1357. var l14 = this.m[13];
  1358. var l15 = this.m[14];
  1359. var l16 = this.m[15];
  1360. var l17 = (l11 * l16) - (l12 * l15);
  1361. var l18 = (l10 * l16) - (l12 * l14);
  1362. var l19 = (l10 * l15) - (l11 * l14);
  1363. var l20 = (l9 * l16) - (l12 * l13);
  1364. var l21 = (l9 * l15) - (l11 * l13);
  1365. var l22 = (l9 * l14) - (l10 * l13);
  1366. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1367. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1368. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1369. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1370. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1371. var l28 = (l7 * l16) - (l8 * l15);
  1372. var l29 = (l6 * l16) - (l8 * l14);
  1373. var l30 = (l6 * l15) - (l7 * l14);
  1374. var l31 = (l5 * l16) - (l8 * l13);
  1375. var l32 = (l5 * l15) - (l7 * l13);
  1376. var l33 = (l5 * l14) - (l6 * l13);
  1377. var l34 = (l7 * l12) - (l8 * l11);
  1378. var l35 = (l6 * l12) - (l8 * l10);
  1379. var l36 = (l6 * l11) - (l7 * l10);
  1380. var l37 = (l5 * l12) - (l8 * l9);
  1381. var l38 = (l5 * l11) - (l7 * l9);
  1382. var l39 = (l5 * l10) - (l6 * l9);
  1383. other.m[0] = l23 * l27;
  1384. other.m[4] = l24 * l27;
  1385. other.m[8] = l25 * l27;
  1386. other.m[12] = l26 * l27;
  1387. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1388. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1389. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1390. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1391. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1392. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1393. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1394. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1395. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1396. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1397. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1398. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1399. return this;
  1400. };
  1401. Matrix.prototype.invertToRefSIMD = function (other) {
  1402. var src = this.m;
  1403. var dest = other.m;
  1404. var row0, row1, row2, row3;
  1405. var tmp1;
  1406. var minor0, minor1, minor2, minor3;
  1407. var det;
  1408. // Load the 4 rows
  1409. var src0 = SIMD.float32x4.load(src, 0);
  1410. var src1 = SIMD.float32x4.load(src, 4);
  1411. var src2 = SIMD.float32x4.load(src, 8);
  1412. var src3 = SIMD.float32x4.load(src, 12);
  1413. // Transpose the source matrix. Sort of. Not a true transpose operation
  1414. tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  1415. row1 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  1416. row0 = SIMD.float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  1417. row1 = SIMD.float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  1418. tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  1419. row3 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  1420. row2 = SIMD.float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  1421. row3 = SIMD.float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  1422. // This is a true transposition, but it will lead to an incorrect result
  1423. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  1424. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  1425. //row0 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  1426. //row1 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  1427. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  1428. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  1429. //row2 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  1430. //row3 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  1431. // ----
  1432. tmp1 = SIMD.float32x4.mul(row2, row3);
  1433. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1434. minor0 = SIMD.float32x4.mul(row1, tmp1);
  1435. minor1 = SIMD.float32x4.mul(row0, tmp1);
  1436. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1437. minor0 = SIMD.float32x4.sub(SIMD.float32x4.mul(row1, tmp1), minor0);
  1438. minor1 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor1);
  1439. minor1 = SIMD.float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  1440. // ----
  1441. tmp1 = SIMD.float32x4.mul(row1, row2);
  1442. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1443. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor0);
  1444. minor3 = SIMD.float32x4.mul(row0, tmp1);
  1445. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1446. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row3, tmp1));
  1447. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor3);
  1448. minor3 = SIMD.float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  1449. // ----
  1450. tmp1 = SIMD.float32x4.mul(SIMD.float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  1451. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1452. row2 = SIMD.float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  1453. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor0);
  1454. minor2 = SIMD.float32x4.mul(row0, tmp1);
  1455. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1456. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row2, tmp1));
  1457. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor2);
  1458. minor2 = SIMD.float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  1459. // ----
  1460. tmp1 = SIMD.float32x4.mul(row0, row1);
  1461. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1462. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor2);
  1463. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row2, tmp1), minor3);
  1464. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1465. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row3, tmp1), minor2);
  1466. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row2, tmp1));
  1467. // ----
  1468. tmp1 = SIMD.float32x4.mul(row0, row3);
  1469. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1470. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row2, tmp1));
  1471. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor2);
  1472. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1473. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor1);
  1474. minor2 = SIMD.float32x4.sub(minor2, SIMD.float32x4.mul(row1, tmp1));
  1475. // ----
  1476. tmp1 = SIMD.float32x4.mul(row0, row2);
  1477. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1478. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor1);
  1479. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row1, tmp1));
  1480. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1481. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row3, tmp1));
  1482. minor3 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor3);
  1483. // Compute determinant
  1484. det = SIMD.float32x4.mul(row0, minor0);
  1485. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  1486. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  1487. tmp1 = SIMD.float32x4.reciprocal(det);
  1488. det = SIMD.float32x4.sub(SIMD.float32x4.add(tmp1, tmp1), SIMD.float32x4.mul(det, SIMD.float32x4.mul(tmp1, tmp1)));
  1489. det = SIMD.float32x4.swizzle(det, 0, 0, 0, 0);
  1490. // These shuffles aren't necessary if the faulty transposition is done
  1491. // up at the top of this function.
  1492. //minor0 = SIMD.float32x4.swizzle(minor0, 2, 1, 0, 3);
  1493. //minor1 = SIMD.float32x4.swizzle(minor1, 2, 1, 0, 3);
  1494. //minor2 = SIMD.float32x4.swizzle(minor2, 2, 1, 0, 3);
  1495. //minor3 = SIMD.float32x4.swizzle(minor3, 2, 1, 0, 3);
  1496. // Compute final values by multiplying with 1/det
  1497. minor0 = SIMD.float32x4.mul(det, minor0);
  1498. minor1 = SIMD.float32x4.mul(det, minor1);
  1499. minor2 = SIMD.float32x4.mul(det, minor2);
  1500. minor3 = SIMD.float32x4.mul(det, minor3);
  1501. SIMD.float32x4.store(dest, 0, minor0);
  1502. SIMD.float32x4.store(dest, 4, minor1);
  1503. SIMD.float32x4.store(dest, 8, minor2);
  1504. SIMD.float32x4.store(dest, 12, minor3);
  1505. return this;
  1506. };
  1507. Matrix.prototype.setTranslation = function (vector3) {
  1508. this.m[12] = vector3.x;
  1509. this.m[13] = vector3.y;
  1510. this.m[14] = vector3.z;
  1511. return this;
  1512. };
  1513. Matrix.prototype.multiply = function (other) {
  1514. var result = new Matrix();
  1515. this.multiplyToRef(other, result);
  1516. return result;
  1517. };
  1518. Matrix.prototype.copyFrom = function (other) {
  1519. for (var index = 0; index < 16; index++) {
  1520. this.m[index] = other.m[index];
  1521. }
  1522. return this;
  1523. };
  1524. Matrix.prototype.copyToArray = function (array, offset) {
  1525. if (offset === void 0) { offset = 0; }
  1526. for (var index = 0; index < 16; index++) {
  1527. array[offset + index] = this.m[index];
  1528. }
  1529. return this;
  1530. };
  1531. Matrix.prototype.multiplyToRef = function (other, result) {
  1532. this.multiplyToArray(other, result.m, 0);
  1533. return this;
  1534. };
  1535. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1536. var tm0 = this.m[0];
  1537. var tm1 = this.m[1];
  1538. var tm2 = this.m[2];
  1539. var tm3 = this.m[3];
  1540. var tm4 = this.m[4];
  1541. var tm5 = this.m[5];
  1542. var tm6 = this.m[6];
  1543. var tm7 = this.m[7];
  1544. var tm8 = this.m[8];
  1545. var tm9 = this.m[9];
  1546. var tm10 = this.m[10];
  1547. var tm11 = this.m[11];
  1548. var tm12 = this.m[12];
  1549. var tm13 = this.m[13];
  1550. var tm14 = this.m[14];
  1551. var tm15 = this.m[15];
  1552. var om0 = other.m[0];
  1553. var om1 = other.m[1];
  1554. var om2 = other.m[2];
  1555. var om3 = other.m[3];
  1556. var om4 = other.m[4];
  1557. var om5 = other.m[5];
  1558. var om6 = other.m[6];
  1559. var om7 = other.m[7];
  1560. var om8 = other.m[8];
  1561. var om9 = other.m[9];
  1562. var om10 = other.m[10];
  1563. var om11 = other.m[11];
  1564. var om12 = other.m[12];
  1565. var om13 = other.m[13];
  1566. var om14 = other.m[14];
  1567. var om15 = other.m[15];
  1568. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1569. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1570. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1571. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1572. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1573. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1574. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1575. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1576. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1577. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1578. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1579. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1580. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1581. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1582. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1583. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1584. return this;
  1585. };
  1586. Matrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  1587. if (offset === void 0) { offset = 0; }
  1588. var tm = this.m;
  1589. var om = other.m;
  1590. var om0 = SIMD.float32x4.load(om, 0);
  1591. var om1 = SIMD.float32x4.load(om, 4);
  1592. var om2 = SIMD.float32x4.load(om, 8);
  1593. var om3 = SIMD.float32x4.load(om, 12);
  1594. var tm0 = SIMD.float32x4.load(tm, 0);
  1595. SIMD.float32x4.store(result, offset + 0, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 3, 3, 3, 3), om3)))));
  1596. var tm1 = SIMD.float32x4.load(tm, 4);
  1597. SIMD.float32x4.store(result, offset + 4, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 3, 3, 3, 3), om3)))));
  1598. var tm2 = SIMD.float32x4.load(tm, 8);
  1599. SIMD.float32x4.store(result, offset + 8, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 3, 3, 3, 3), om3)))));
  1600. var tm3 = SIMD.float32x4.load(tm, 12);
  1601. SIMD.float32x4.store(result, offset + 12, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 3, 3, 3, 3), om3)))));
  1602. };
  1603. Matrix.prototype.equals = function (value) {
  1604. 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]);
  1605. };
  1606. Matrix.prototype.clone = function () {
  1607. 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]);
  1608. };
  1609. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1610. translation.x = this.m[12];
  1611. translation.y = this.m[13];
  1612. translation.z = this.m[14];
  1613. var xs = BABYLON.Tools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1614. var ys = BABYLON.Tools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1615. var zs = BABYLON.Tools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1616. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1617. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1618. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1619. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1620. rotation.x = 0;
  1621. rotation.y = 0;
  1622. rotation.z = 0;
  1623. rotation.w = 1;
  1624. return false;
  1625. }
  1626. 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);
  1627. Quaternion.FromRotationMatrixToRef(rotationMatrix, rotation);
  1628. return true;
  1629. };
  1630. // Statics
  1631. Matrix.FromArray = function (array, offset) {
  1632. var result = new Matrix();
  1633. if (!offset) {
  1634. offset = 0;
  1635. }
  1636. Matrix.FromArrayToRef(array, offset, result);
  1637. return result;
  1638. };
  1639. Matrix.FromArrayToRef = function (array, offset, result) {
  1640. for (var index = 0; index < 16; index++) {
  1641. result.m[index] = array[index + offset];
  1642. }
  1643. };
  1644. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1645. result.m[0] = initialM11;
  1646. result.m[1] = initialM12;
  1647. result.m[2] = initialM13;
  1648. result.m[3] = initialM14;
  1649. result.m[4] = initialM21;
  1650. result.m[5] = initialM22;
  1651. result.m[6] = initialM23;
  1652. result.m[7] = initialM24;
  1653. result.m[8] = initialM31;
  1654. result.m[9] = initialM32;
  1655. result.m[10] = initialM33;
  1656. result.m[11] = initialM34;
  1657. result.m[12] = initialM41;
  1658. result.m[13] = initialM42;
  1659. result.m[14] = initialM43;
  1660. result.m[15] = initialM44;
  1661. };
  1662. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1663. var result = new Matrix();
  1664. result.m[0] = initialM11;
  1665. result.m[1] = initialM12;
  1666. result.m[2] = initialM13;
  1667. result.m[3] = initialM14;
  1668. result.m[4] = initialM21;
  1669. result.m[5] = initialM22;
  1670. result.m[6] = initialM23;
  1671. result.m[7] = initialM24;
  1672. result.m[8] = initialM31;
  1673. result.m[9] = initialM32;
  1674. result.m[10] = initialM33;
  1675. result.m[11] = initialM34;
  1676. result.m[12] = initialM41;
  1677. result.m[13] = initialM42;
  1678. result.m[14] = initialM43;
  1679. result.m[15] = initialM44;
  1680. return result;
  1681. };
  1682. Matrix.Compose = function (scale, rotation, translation) {
  1683. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  1684. var rotationMatrix = Matrix.Identity();
  1685. rotation.toRotationMatrix(rotationMatrix);
  1686. result = result.multiply(rotationMatrix);
  1687. result.setTranslation(translation);
  1688. return result;
  1689. };
  1690. Matrix.Identity = function () {
  1691. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1692. };
  1693. Matrix.IdentityToRef = function (result) {
  1694. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1695. };
  1696. Matrix.Zero = function () {
  1697. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1698. };
  1699. Matrix.RotationX = function (angle) {
  1700. var result = new Matrix();
  1701. Matrix.RotationXToRef(angle, result);
  1702. return result;
  1703. };
  1704. Matrix.Invert = function (source) {
  1705. var result = new Matrix();
  1706. source.invertToRef(result);
  1707. return result;
  1708. };
  1709. Matrix.RotationXToRef = function (angle, result) {
  1710. var s = Math.sin(angle);
  1711. var c = Math.cos(angle);
  1712. result.m[0] = 1.0;
  1713. result.m[15] = 1.0;
  1714. result.m[5] = c;
  1715. result.m[10] = c;
  1716. result.m[9] = -s;
  1717. result.m[6] = s;
  1718. result.m[1] = 0;
  1719. result.m[2] = 0;
  1720. result.m[3] = 0;
  1721. result.m[4] = 0;
  1722. result.m[7] = 0;
  1723. result.m[8] = 0;
  1724. result.m[11] = 0;
  1725. result.m[12] = 0;
  1726. result.m[13] = 0;
  1727. result.m[14] = 0;
  1728. };
  1729. Matrix.RotationY = function (angle) {
  1730. var result = new Matrix();
  1731. Matrix.RotationYToRef(angle, result);
  1732. return result;
  1733. };
  1734. Matrix.RotationYToRef = function (angle, result) {
  1735. var s = Math.sin(angle);
  1736. var c = Math.cos(angle);
  1737. result.m[5] = 1.0;
  1738. result.m[15] = 1.0;
  1739. result.m[0] = c;
  1740. result.m[2] = -s;
  1741. result.m[8] = s;
  1742. result.m[10] = c;
  1743. result.m[1] = 0;
  1744. result.m[3] = 0;
  1745. result.m[4] = 0;
  1746. result.m[6] = 0;
  1747. result.m[7] = 0;
  1748. result.m[9] = 0;
  1749. result.m[11] = 0;
  1750. result.m[12] = 0;
  1751. result.m[13] = 0;
  1752. result.m[14] = 0;
  1753. };
  1754. Matrix.RotationZ = function (angle) {
  1755. var result = new Matrix();
  1756. Matrix.RotationZToRef(angle, result);
  1757. return result;
  1758. };
  1759. Matrix.RotationZToRef = function (angle, result) {
  1760. var s = Math.sin(angle);
  1761. var c = Math.cos(angle);
  1762. result.m[10] = 1.0;
  1763. result.m[15] = 1.0;
  1764. result.m[0] = c;
  1765. result.m[1] = s;
  1766. result.m[4] = -s;
  1767. result.m[5] = c;
  1768. result.m[2] = 0;
  1769. result.m[3] = 0;
  1770. result.m[6] = 0;
  1771. result.m[7] = 0;
  1772. result.m[8] = 0;
  1773. result.m[9] = 0;
  1774. result.m[11] = 0;
  1775. result.m[12] = 0;
  1776. result.m[13] = 0;
  1777. result.m[14] = 0;
  1778. };
  1779. Matrix.RotationAxis = function (axis, angle) {
  1780. var s = Math.sin(-angle);
  1781. var c = Math.cos(-angle);
  1782. var c1 = 1 - c;
  1783. axis.normalize();
  1784. var result = Matrix.Zero();
  1785. result.m[0] = (axis.x * axis.x) * c1 + c;
  1786. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1787. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1788. result.m[3] = 0.0;
  1789. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1790. result.m[5] = (axis.y * axis.y) * c1 + c;
  1791. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  1792. result.m[7] = 0.0;
  1793. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  1794. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  1795. result.m[10] = (axis.z * axis.z) * c1 + c;
  1796. result.m[11] = 0.0;
  1797. result.m[15] = 1.0;
  1798. return result;
  1799. };
  1800. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1801. var result = new Matrix();
  1802. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1803. return result;
  1804. };
  1805. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1806. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  1807. this._tempQuaternion.toRotationMatrix(result);
  1808. };
  1809. Matrix.Scaling = function (x, y, z) {
  1810. var result = Matrix.Zero();
  1811. Matrix.ScalingToRef(x, y, z, result);
  1812. return result;
  1813. };
  1814. Matrix.ScalingToRef = function (x, y, z, result) {
  1815. result.m[0] = x;
  1816. result.m[1] = 0;
  1817. result.m[2] = 0;
  1818. result.m[3] = 0;
  1819. result.m[4] = 0;
  1820. result.m[5] = y;
  1821. result.m[6] = 0;
  1822. result.m[7] = 0;
  1823. result.m[8] = 0;
  1824. result.m[9] = 0;
  1825. result.m[10] = z;
  1826. result.m[11] = 0;
  1827. result.m[12] = 0;
  1828. result.m[13] = 0;
  1829. result.m[14] = 0;
  1830. result.m[15] = 1.0;
  1831. };
  1832. Matrix.Translation = function (x, y, z) {
  1833. var result = Matrix.Identity();
  1834. Matrix.TranslationToRef(x, y, z, result);
  1835. return result;
  1836. };
  1837. Matrix.TranslationToRef = function (x, y, z, result) {
  1838. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  1839. };
  1840. Matrix.LookAtLH = function (eye, target, up) {
  1841. var result = Matrix.Zero();
  1842. Matrix.LookAtLHToRef(eye, target, up, result);
  1843. return result;
  1844. };
  1845. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  1846. // Z axis
  1847. target.subtractToRef(eye, this._zAxis);
  1848. this._zAxis.normalize();
  1849. // X axis
  1850. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  1851. this._xAxis.normalize();
  1852. // Y axis
  1853. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  1854. this._yAxis.normalize();
  1855. // Eye angles
  1856. var ex = -Vector3.Dot(this._xAxis, eye);
  1857. var ey = -Vector3.Dot(this._yAxis, eye);
  1858. var ez = -Vector3.Dot(this._zAxis, eye);
  1859. 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);
  1860. };
  1861. Matrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  1862. var out = result.m;
  1863. var center = SIMD.float32x4(targetRef.x, targetRef.y, targetRef.z, 0);
  1864. var eye = SIMD.float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0);
  1865. var up = SIMD.float32x4(upRef.x, upRef.y, upRef.z, 0);
  1866. // cc.kmVec3Subtract(f, pCenter, pEye);
  1867. var f = SIMD.float32x4.sub(center, eye);
  1868. // cc.kmVec3Normalize(f, f);
  1869. var tmp = SIMD.float32x4.mul(f, f);
  1870. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  1871. f = SIMD.float32x4.mul(f, SIMD.float32x4.reciprocalSqrt(tmp));
  1872. // cc.kmVec3Assign(up, pUp);
  1873. // cc.kmVec3Normalize(up, up);
  1874. tmp = SIMD.float32x4.mul(up, up);
  1875. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  1876. up = SIMD.float32x4.mul(up, SIMD.float32x4.reciprocalSqrt(tmp));
  1877. // cc.kmVec3Cross(s, f, up);
  1878. var s = SIMD.float32x4.sub(SIMD.float32x4.mul(SIMD.float32x4.swizzle(f, 1, 2, 0, 3), SIMD.float32x4.swizzle(up, 2, 0, 1, 3)), SIMD.float32x4.mul(SIMD.float32x4.swizzle(f, 2, 0, 1, 3), SIMD.float32x4.swizzle(up, 1, 2, 0, 3)));
  1879. // cc.kmVec3Normalize(s, s);
  1880. tmp = SIMD.float32x4.mul(s, s);
  1881. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  1882. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrt(tmp));
  1883. // cc.kmVec3Cross(u, s, f);
  1884. var u = SIMD.float32x4.sub(SIMD.float32x4.mul(SIMD.float32x4.swizzle(s, 1, 2, 0, 3), SIMD.float32x4.swizzle(f, 2, 0, 1, 3)), SIMD.float32x4.mul(SIMD.float32x4.swizzle(s, 2, 0, 1, 3), SIMD.float32x4.swizzle(f, 1, 2, 0, 3)));
  1885. // cc.kmVec3Normalize(s, s);
  1886. tmp = SIMD.float32x4.mul(s, s);
  1887. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  1888. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrt(tmp));
  1889. //cc.kmMat4Identity(pOut);
  1890. //pOut.mat[0] = s.x;
  1891. //pOut.mat[4] = s.y;
  1892. //pOut.mat[8] = s.z;
  1893. //pOut.mat[1] = u.x;
  1894. //pOut.mat[5] = u.y;
  1895. //pOut.mat[9] = u.z;
  1896. //pOut.mat[2] = -f.x;
  1897. //pOut.mat[6] = -f.y;
  1898. //pOut.mat[10] = -f.z;
  1899. var zero = SIMD.float32x4.splat(0.0);
  1900. s = SIMD.float32x4.neg(s);
  1901. var tmp01 = SIMD.float32x4.shuffle(s, u, 0, 1, 4, 5);
  1902. var tmp23 = SIMD.float32x4.shuffle(f, zero, 0, 1, 4, 5);
  1903. var a0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  1904. var a1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  1905. tmp01 = SIMD.float32x4.shuffle(s, u, 2, 3, 6, 7);
  1906. tmp23 = SIMD.float32x4.shuffle(f, zero, 2, 3, 6, 7);
  1907. var a2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  1908. var a3 = SIMD.float32x4(0.0, 0.0, 0.0, 1.0);
  1909. // cc.kmMat4Translation(translate, -pEye.x, -pEye.y, -pEye.z);
  1910. var b0 = SIMD.float32x4(1.0, 0.0, 0.0, 0.0);
  1911. var b1 = SIMD.float32x4(0.0, 1.0, 0.0, 0.0);
  1912. var b2 = SIMD.float32x4(0.0, 0.0, 1.0, 0.0);
  1913. var b3 = SIMD.float32x4.neg(eye);
  1914. b3 = SIMD.float32x4.withW(b3, 1.0);
  1915. // cc.kmMat4Multiply(pOut, pOut, translate);
  1916. SIMD.float32x4.store(out, 0, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 3, 3, 3, 3), a3)))));
  1917. SIMD.float32x4.store(out, 4, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 3, 3, 3, 3), a3)))));
  1918. SIMD.float32x4.store(out, 8, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 3, 3, 3, 3), a3)))));
  1919. SIMD.float32x4.store(out, 12, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 3, 3, 3, 3), a3)))));
  1920. };
  1921. Matrix.OrthoLH = function (width, height, znear, zfar) {
  1922. var matrix = Matrix.Zero();
  1923. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  1924. return matrix;
  1925. };
  1926. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  1927. var hw = 2.0 / width;
  1928. var hh = 2.0 / height;
  1929. var id = 1.0 / (zfar - znear);
  1930. var nid = znear / (znear - zfar);
  1931. Matrix.FromValuesToRef(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1, result);
  1932. };
  1933. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  1934. var matrix = Matrix.Zero();
  1935. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  1936. return matrix;
  1937. };
  1938. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  1939. result.m[0] = 2.0 / (right - left);
  1940. result.m[1] = result.m[2] = result.m[3] = 0;
  1941. result.m[5] = 2.0 / (top - bottom);
  1942. result.m[4] = result.m[6] = result.m[7] = 0;
  1943. result.m[10] = -1.0 / (znear - zfar);
  1944. result.m[8] = result.m[9] = result.m[11] = 0;
  1945. result.m[12] = (left + right) / (left - right);
  1946. result.m[13] = (top + bottom) / (bottom - top);
  1947. result.m[14] = znear / (znear - zfar);
  1948. result.m[15] = 1.0;
  1949. };
  1950. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  1951. var matrix = Matrix.Zero();
  1952. matrix.m[0] = (2.0 * znear) / width;
  1953. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  1954. matrix.m[5] = (2.0 * znear) / height;
  1955. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  1956. matrix.m[10] = -zfar / (znear - zfar);
  1957. matrix.m[8] = matrix.m[9] = 0.0;
  1958. matrix.m[11] = 1.0;
  1959. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  1960. matrix.m[14] = (znear * zfar) / (znear - zfar);
  1961. return matrix;
  1962. };
  1963. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  1964. var matrix = Matrix.Zero();
  1965. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  1966. return matrix;
  1967. };
  1968. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, fovMode) {
  1969. if (fovMode === void 0) { fovMode = BABYLON.Camera.FOVMODE_VERTICAL_FIXED; }
  1970. var tan = 1.0 / (Math.tan(fov * 0.5));
  1971. var v_fixed = (fovMode === BABYLON.Camera.FOVMODE_VERTICAL_FIXED);
  1972. if (v_fixed) {
  1973. result.m[0] = tan / aspect;
  1974. }
  1975. else {
  1976. result.m[0] = tan;
  1977. }
  1978. result.m[1] = result.m[2] = result.m[3] = 0.0;
  1979. if (v_fixed) {
  1980. result.m[5] = tan;
  1981. }
  1982. else {
  1983. result.m[5] = tan * aspect;
  1984. }
  1985. result.m[4] = result.m[6] = result.m[7] = 0.0;
  1986. result.m[8] = result.m[9] = 0.0;
  1987. result.m[10] = -zfar / (znear - zfar);
  1988. result.m[11] = 1.0;
  1989. result.m[12] = result.m[13] = result.m[15] = 0.0;
  1990. result.m[14] = (znear * zfar) / (znear - zfar);
  1991. };
  1992. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  1993. var cw = viewport.width;
  1994. var ch = viewport.height;
  1995. var cx = viewport.x;
  1996. var cy = viewport.y;
  1997. 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);
  1998. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  1999. };
  2000. Matrix.Transpose = function (matrix) {
  2001. var result = new Matrix();
  2002. result.m[0] = matrix.m[0];
  2003. result.m[1] = matrix.m[4];
  2004. result.m[2] = matrix.m[8];
  2005. result.m[3] = matrix.m[12];
  2006. result.m[4] = matrix.m[1];
  2007. result.m[5] = matrix.m[5];
  2008. result.m[6] = matrix.m[9];
  2009. result.m[7] = matrix.m[13];
  2010. result.m[8] = matrix.m[2];
  2011. result.m[9] = matrix.m[6];
  2012. result.m[10] = matrix.m[10];
  2013. result.m[11] = matrix.m[14];
  2014. result.m[12] = matrix.m[3];
  2015. result.m[13] = matrix.m[7];
  2016. result.m[14] = matrix.m[11];
  2017. result.m[15] = matrix.m[15];
  2018. return result;
  2019. };
  2020. Matrix.Reflection = function (plane) {
  2021. var matrix = new Matrix();
  2022. Matrix.ReflectionToRef(plane, matrix);
  2023. return matrix;
  2024. };
  2025. Matrix.ReflectionToRef = function (plane, result) {
  2026. plane.normalize();
  2027. var x = plane.normal.x;
  2028. var y = plane.normal.y;
  2029. var z = plane.normal.z;
  2030. var temp = -2 * x;
  2031. var temp2 = -2 * y;
  2032. var temp3 = -2 * z;
  2033. result.m[0] = (temp * x) + 1;
  2034. result.m[1] = temp2 * x;
  2035. result.m[2] = temp3 * x;
  2036. result.m[3] = 0.0;
  2037. result.m[4] = temp * y;
  2038. result.m[5] = (temp2 * y) + 1;
  2039. result.m[6] = temp3 * y;
  2040. result.m[7] = 0.0;
  2041. result.m[8] = temp * z;
  2042. result.m[9] = temp2 * z;
  2043. result.m[10] = (temp3 * z) + 1;
  2044. result.m[11] = 0.0;
  2045. result.m[12] = temp * plane.d;
  2046. result.m[13] = temp2 * plane.d;
  2047. result.m[14] = temp3 * plane.d;
  2048. result.m[15] = 1.0;
  2049. };
  2050. Matrix._tempQuaternion = new Quaternion();
  2051. Matrix._xAxis = Vector3.Zero();
  2052. Matrix._yAxis = Vector3.Zero();
  2053. Matrix._zAxis = Vector3.Zero();
  2054. return Matrix;
  2055. })();
  2056. BABYLON.Matrix = Matrix;
  2057. var Plane = (function () {
  2058. function Plane(a, b, c, d) {
  2059. this.normal = new Vector3(a, b, c);
  2060. this.d = d;
  2061. }
  2062. Plane.prototype.asArray = function () {
  2063. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  2064. };
  2065. // Methods
  2066. Plane.prototype.clone = function () {
  2067. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  2068. };
  2069. Plane.prototype.normalize = function () {
  2070. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  2071. var magnitude = 0;
  2072. if (norm !== 0) {
  2073. magnitude = 1.0 / norm;
  2074. }
  2075. this.normal.x *= magnitude;
  2076. this.normal.y *= magnitude;
  2077. this.normal.z *= magnitude;
  2078. this.d *= magnitude;
  2079. return this;
  2080. };
  2081. Plane.prototype.transform = function (transformation) {
  2082. var transposedMatrix = Matrix.Transpose(transformation);
  2083. var x = this.normal.x;
  2084. var y = this.normal.y;
  2085. var z = this.normal.z;
  2086. var d = this.d;
  2087. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  2088. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  2089. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  2090. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  2091. return new Plane(normalX, normalY, normalZ, finalD);
  2092. };
  2093. Plane.prototype.dotCoordinate = function (point) {
  2094. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  2095. };
  2096. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  2097. var x1 = point2.x - point1.x;
  2098. var y1 = point2.y - point1.y;
  2099. var z1 = point2.z - point1.z;
  2100. var x2 = point3.x - point1.x;
  2101. var y2 = point3.y - point1.y;
  2102. var z2 = point3.z - point1.z;
  2103. var yz = (y1 * z2) - (z1 * y2);
  2104. var xz = (z1 * x2) - (x1 * z2);
  2105. var xy = (x1 * y2) - (y1 * x2);
  2106. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  2107. var invPyth;
  2108. if (pyth !== 0) {
  2109. invPyth = 1.0 / pyth;
  2110. }
  2111. else {
  2112. invPyth = 0;
  2113. }
  2114. this.normal.x = yz * invPyth;
  2115. this.normal.y = xz * invPyth;
  2116. this.normal.z = xy * invPyth;
  2117. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  2118. return this;
  2119. };
  2120. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  2121. var dot = Vector3.Dot(this.normal, direction);
  2122. return (dot <= epsilon);
  2123. };
  2124. Plane.prototype.signedDistanceTo = function (point) {
  2125. return Vector3.Dot(point, this.normal) + this.d;
  2126. };
  2127. // Statics
  2128. Plane.FromArray = function (array) {
  2129. return new Plane(array[0], array[1], array[2], array[3]);
  2130. };
  2131. Plane.FromPoints = function (point1, point2, point3) {
  2132. var result = new Plane(0, 0, 0, 0);
  2133. result.copyFromPoints(point1, point2, point3);
  2134. return result;
  2135. };
  2136. Plane.FromPositionAndNormal = function (origin, normal) {
  2137. var result = new Plane(0, 0, 0, 0);
  2138. normal.normalize();
  2139. result.normal = normal;
  2140. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2141. return result;
  2142. };
  2143. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  2144. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2145. return Vector3.Dot(point, normal) + d;
  2146. };
  2147. return Plane;
  2148. })();
  2149. BABYLON.Plane = Plane;
  2150. var Viewport = (function () {
  2151. function Viewport(x, y, width, height) {
  2152. this.x = x;
  2153. this.y = y;
  2154. this.width = width;
  2155. this.height = height;
  2156. }
  2157. Viewport.prototype.toGlobal = function (engine) {
  2158. var width = engine.getRenderWidth();
  2159. var height = engine.getRenderHeight();
  2160. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  2161. };
  2162. return Viewport;
  2163. })();
  2164. BABYLON.Viewport = Viewport;
  2165. var Frustum = (function () {
  2166. function Frustum() {
  2167. }
  2168. Frustum.GetPlanes = function (transform) {
  2169. var frustumPlanes = [];
  2170. for (var index = 0; index < 6; index++) {
  2171. frustumPlanes.push(new Plane(0, 0, 0, 0));
  2172. }
  2173. Frustum.GetPlanesToRef(transform, frustumPlanes);
  2174. return frustumPlanes;
  2175. };
  2176. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  2177. // Near
  2178. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  2179. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  2180. frustumPlanes[0].normal.z = transform.m[10] + transform.m[10];
  2181. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  2182. frustumPlanes[0].normalize();
  2183. // Far
  2184. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  2185. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  2186. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  2187. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  2188. frustumPlanes[1].normalize();
  2189. // Left
  2190. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  2191. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  2192. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  2193. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  2194. frustumPlanes[2].normalize();
  2195. // Right
  2196. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  2197. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  2198. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  2199. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  2200. frustumPlanes[3].normalize();
  2201. // Top
  2202. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  2203. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  2204. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2205. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2206. frustumPlanes[4].normalize();
  2207. // Bottom
  2208. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2209. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2210. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2211. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2212. frustumPlanes[5].normalize();
  2213. };
  2214. return Frustum;
  2215. })();
  2216. BABYLON.Frustum = Frustum;
  2217. var Ray = (function () {
  2218. function Ray(origin, direction, length) {
  2219. if (length === void 0) { length = Number.MAX_VALUE; }
  2220. this.origin = origin;
  2221. this.direction = direction;
  2222. this.length = length;
  2223. }
  2224. // Methods
  2225. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  2226. var d = 0.0;
  2227. var maxValue = Number.MAX_VALUE;
  2228. if (Math.abs(this.direction.x) < 0.0000001) {
  2229. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  2230. return false;
  2231. }
  2232. }
  2233. else {
  2234. var inv = 1.0 / this.direction.x;
  2235. var min = (minimum.x - this.origin.x) * inv;
  2236. var max = (maximum.x - this.origin.x) * inv;
  2237. if (max === -Infinity) {
  2238. max = Infinity;
  2239. }
  2240. if (min > max) {
  2241. var temp = min;
  2242. min = max;
  2243. max = temp;
  2244. }
  2245. d = Math.max(min, d);
  2246. maxValue = Math.min(max, maxValue);
  2247. if (d > maxValue) {
  2248. return false;
  2249. }
  2250. }
  2251. if (Math.abs(this.direction.y) < 0.0000001) {
  2252. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  2253. return false;
  2254. }
  2255. }
  2256. else {
  2257. inv = 1.0 / this.direction.y;
  2258. min = (minimum.y - this.origin.y) * inv;
  2259. max = (maximum.y - this.origin.y) * inv;
  2260. if (max === -Infinity) {
  2261. max = Infinity;
  2262. }
  2263. if (min > max) {
  2264. temp = min;
  2265. min = max;
  2266. max = temp;
  2267. }
  2268. d = Math.max(min, d);
  2269. maxValue = Math.min(max, maxValue);
  2270. if (d > maxValue) {
  2271. return false;
  2272. }
  2273. }
  2274. if (Math.abs(this.direction.z) < 0.0000001) {
  2275. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  2276. return false;
  2277. }
  2278. }
  2279. else {
  2280. inv = 1.0 / this.direction.z;
  2281. min = (minimum.z - this.origin.z) * inv;
  2282. max = (maximum.z - this.origin.z) * inv;
  2283. if (max === -Infinity) {
  2284. max = Infinity;
  2285. }
  2286. if (min > max) {
  2287. temp = min;
  2288. min = max;
  2289. max = temp;
  2290. }
  2291. d = Math.max(min, d);
  2292. maxValue = Math.min(max, maxValue);
  2293. if (d > maxValue) {
  2294. return false;
  2295. }
  2296. }
  2297. return true;
  2298. };
  2299. Ray.prototype.intersectsBox = function (box) {
  2300. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  2301. };
  2302. Ray.prototype.intersectsSphere = function (sphere) {
  2303. var x = sphere.center.x - this.origin.x;
  2304. var y = sphere.center.y - this.origin.y;
  2305. var z = sphere.center.z - this.origin.z;
  2306. var pyth = (x * x) + (y * y) + (z * z);
  2307. var rr = sphere.radius * sphere.radius;
  2308. if (pyth <= rr) {
  2309. return true;
  2310. }
  2311. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  2312. if (dot < 0.0) {
  2313. return false;
  2314. }
  2315. var temp = pyth - (dot * dot);
  2316. return temp <= rr;
  2317. };
  2318. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  2319. if (!this._edge1) {
  2320. this._edge1 = Vector3.Zero();
  2321. this._edge2 = Vector3.Zero();
  2322. this._pvec = Vector3.Zero();
  2323. this._tvec = Vector3.Zero();
  2324. this._qvec = Vector3.Zero();
  2325. }
  2326. vertex1.subtractToRef(vertex0, this._edge1);
  2327. vertex2.subtractToRef(vertex0, this._edge2);
  2328. Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  2329. var det = Vector3.Dot(this._edge1, this._pvec);
  2330. if (det === 0) {
  2331. return null;
  2332. }
  2333. var invdet = 1 / det;
  2334. this.origin.subtractToRef(vertex0, this._tvec);
  2335. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  2336. if (bu < 0 || bu > 1.0) {
  2337. return null;
  2338. }
  2339. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  2340. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  2341. if (bv < 0 || bu + bv > 1.0) {
  2342. return null;
  2343. }
  2344. //check if the distance is longer than the predefined length.
  2345. var distance = Vector3.Dot(this._edge2, this._qvec) * invdet;
  2346. if (distance > this.length) {
  2347. return null;
  2348. }
  2349. return new BABYLON.IntersectionInfo(bu, bv, distance);
  2350. };
  2351. // Statics
  2352. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  2353. var start = Vector3.Unproject(new Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  2354. var end = Vector3.Unproject(new Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  2355. var direction = end.subtract(start);
  2356. direction.normalize();
  2357. return new Ray(start, direction);
  2358. };
  2359. /**
  2360. * 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
  2361. * transformed to the given world matrix.
  2362. * @param origin The origin point
  2363. * @param end The end point
  2364. * @param world a matrix to transform the ray to. Default is the identity matrix.
  2365. */
  2366. Ray.CreateNewFromTo = function (origin, end, world) {
  2367. if (world === void 0) { world = Matrix.Identity(); }
  2368. var direction = end.subtract(origin);
  2369. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  2370. direction.normalize();
  2371. return Ray.Transform(new Ray(origin, direction, length), world);
  2372. };
  2373. Ray.Transform = function (ray, matrix) {
  2374. var newOrigin = Vector3.TransformCoordinates(ray.origin, matrix);
  2375. var newDirection = Vector3.TransformNormal(ray.direction, matrix);
  2376. return new Ray(newOrigin, newDirection, ray.length);
  2377. };
  2378. return Ray;
  2379. })();
  2380. BABYLON.Ray = Ray;
  2381. (function (Space) {
  2382. Space[Space["LOCAL"] = 0] = "LOCAL";
  2383. Space[Space["WORLD"] = 1] = "WORLD";
  2384. })(BABYLON.Space || (BABYLON.Space = {}));
  2385. var Space = BABYLON.Space;
  2386. var Axis = (function () {
  2387. function Axis() {
  2388. }
  2389. Axis.X = new Vector3(1, 0, 0);
  2390. Axis.Y = new Vector3(0, 1, 0);
  2391. Axis.Z = new Vector3(0, 0, 1);
  2392. return Axis;
  2393. })();
  2394. BABYLON.Axis = Axis;
  2395. ;
  2396. var BezierCurve = (function () {
  2397. function BezierCurve() {
  2398. }
  2399. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2400. // Extract X (which is equal to time here)
  2401. var f0 = 1 - 3 * x2 + 3 * x1;
  2402. var f1 = 3 * x2 - 6 * x1;
  2403. var f2 = 3 * x1;
  2404. var refinedT = t;
  2405. for (var i = 0; i < 5; i++) {
  2406. var refinedT2 = refinedT * refinedT;
  2407. var refinedT3 = refinedT2 * refinedT;
  2408. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2409. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2410. refinedT -= (x - t) * slope;
  2411. refinedT = Math.min(1, Math.max(0, refinedT));
  2412. }
  2413. // Resolve cubic bezier for the given x
  2414. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 + 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 + Math.pow(refinedT, 3);
  2415. };
  2416. return BezierCurve;
  2417. })();
  2418. BABYLON.BezierCurve = BezierCurve;
  2419. (function (Orientation) {
  2420. Orientation[Orientation["CW"] = 0] = "CW";
  2421. Orientation[Orientation["CCW"] = 1] = "CCW";
  2422. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2423. var Orientation = BABYLON.Orientation;
  2424. var Angle = (function () {
  2425. function Angle(radians) {
  2426. var _this = this;
  2427. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2428. this.radians = function () { return _this._radians; };
  2429. this._radians = radians;
  2430. if (this._radians < 0)
  2431. this._radians += (2 * Math.PI);
  2432. }
  2433. Angle.BetweenTwoPoints = function (a, b) {
  2434. var delta = b.subtract(a);
  2435. var theta = Math.atan2(delta.y, delta.x);
  2436. return new Angle(theta);
  2437. };
  2438. Angle.FromRadians = function (radians) {
  2439. return new Angle(radians);
  2440. };
  2441. Angle.FromDegrees = function (degrees) {
  2442. return new Angle(degrees * Math.PI / 180);
  2443. };
  2444. return Angle;
  2445. })();
  2446. BABYLON.Angle = Angle;
  2447. var Arc2 = (function () {
  2448. function Arc2(startPoint, midPoint, endPoint) {
  2449. this.startPoint = startPoint;
  2450. this.midPoint = midPoint;
  2451. this.endPoint = endPoint;
  2452. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2453. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2454. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2455. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2456. 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);
  2457. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2458. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2459. var a1 = this.startAngle.degrees();
  2460. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2461. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2462. // angles correction
  2463. if (a2 - a1 > +180.0)
  2464. a2 -= 360.0;
  2465. if (a2 - a1 < -180.0)
  2466. a2 += 360.0;
  2467. if (a3 - a2 > +180.0)
  2468. a3 -= 360.0;
  2469. if (a3 - a2 < -180.0)
  2470. a3 += 360.0;
  2471. this.orientation = (a2 - a1) < 0 ? 0 /* CW */ : 1 /* CCW */;
  2472. this.angle = Angle.FromDegrees(this.orientation === 0 /* CW */ ? a1 - a3 : a3 - a1);
  2473. }
  2474. return Arc2;
  2475. })();
  2476. BABYLON.Arc2 = Arc2;
  2477. var PathCursor = (function () {
  2478. function PathCursor(path) {
  2479. this.path = path;
  2480. this._onchange = new Array();
  2481. this.value = 0;
  2482. this.animations = new Array();
  2483. }
  2484. PathCursor.prototype.getPoint = function () {
  2485. var point = this.path.getPointAtLengthPosition(this.value);
  2486. return new Vector3(point.x, 0, point.y);
  2487. };
  2488. PathCursor.prototype.moveAhead = function (step) {
  2489. if (step === void 0) { step = 0.002; }
  2490. this.move(step);
  2491. return this;
  2492. };
  2493. PathCursor.prototype.moveBack = function (step) {
  2494. if (step === void 0) { step = 0.002; }
  2495. this.move(-step);
  2496. return this;
  2497. };
  2498. PathCursor.prototype.move = function (step) {
  2499. if (Math.abs(step) > 1) {
  2500. throw "step size should be less than 1.";
  2501. }
  2502. this.value += step;
  2503. this.ensureLimits();
  2504. this.raiseOnChange();
  2505. return this;
  2506. };
  2507. PathCursor.prototype.ensureLimits = function () {
  2508. while (this.value > 1) {
  2509. this.value -= 1;
  2510. }
  2511. while (this.value < 0) {
  2512. this.value += 1;
  2513. }
  2514. return this;
  2515. };
  2516. // used by animation engine
  2517. PathCursor.prototype.markAsDirty = function (propertyName) {
  2518. this.ensureLimits();
  2519. this.raiseOnChange();
  2520. return this;
  2521. };
  2522. PathCursor.prototype.raiseOnChange = function () {
  2523. var _this = this;
  2524. this._onchange.forEach(function (f) { return f(_this); });
  2525. return this;
  2526. };
  2527. PathCursor.prototype.onchange = function (f) {
  2528. this._onchange.push(f);
  2529. return this;
  2530. };
  2531. return PathCursor;
  2532. })();
  2533. BABYLON.PathCursor = PathCursor;
  2534. var Path2 = (function () {
  2535. function Path2(x, y) {
  2536. this._points = new Array();
  2537. this._length = 0;
  2538. this.closed = false;
  2539. this._points.push(new Vector2(x, y));
  2540. }
  2541. Path2.prototype.addLineTo = function (x, y) {
  2542. if (closed) {
  2543. BABYLON.Tools.Error("cannot add lines to closed paths");
  2544. return this;
  2545. }
  2546. var newPoint = new Vector2(x, y);
  2547. var previousPoint = this._points[this._points.length - 1];
  2548. this._points.push(newPoint);
  2549. this._length += newPoint.subtract(previousPoint).length();
  2550. return this;
  2551. };
  2552. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2553. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2554. if (closed) {
  2555. BABYLON.Tools.Error("cannot add arcs to closed paths");
  2556. return this;
  2557. }
  2558. var startPoint = this._points[this._points.length - 1];
  2559. var midPoint = new Vector2(midX, midY);
  2560. var endPoint = new Vector2(endX, endY);
  2561. var arc = new Arc2(startPoint, midPoint, endPoint);
  2562. var increment = arc.angle.radians() / numberOfSegments;
  2563. if (arc.orientation === 0 /* CW */)
  2564. increment *= -1;
  2565. var currentAngle = arc.startAngle.radians() + increment;
  2566. for (var i = 0; i < numberOfSegments; i++) {
  2567. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2568. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2569. this.addLineTo(x, y);
  2570. currentAngle += increment;
  2571. }
  2572. return this;
  2573. };
  2574. Path2.prototype.close = function () {
  2575. this.closed = true;
  2576. return this;
  2577. };
  2578. Path2.prototype.length = function () {
  2579. var result = this._length;
  2580. if (!this.closed) {
  2581. var lastPoint = this._points[this._points.length - 1];
  2582. var firstPoint = this._points[0];
  2583. result += (firstPoint.subtract(lastPoint).length());
  2584. }
  2585. return result;
  2586. };
  2587. Path2.prototype.getPoints = function () {
  2588. return this._points;
  2589. };
  2590. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2591. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2592. BABYLON.Tools.Error("normalized length position should be between 0 and 1.");
  2593. return Vector2.Zero();
  2594. }
  2595. var lengthPosition = normalizedLengthPosition * this.length();
  2596. var previousOffset = 0;
  2597. for (var i = 0; i < this._points.length; i++) {
  2598. var j = (i + 1) % this._points.length;
  2599. var a = this._points[i];
  2600. var b = this._points[j];
  2601. var bToA = b.subtract(a);
  2602. var nextOffset = (bToA.length() + previousOffset);
  2603. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2604. var dir = bToA.normalize();
  2605. var localOffset = lengthPosition - previousOffset;
  2606. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2607. }
  2608. previousOffset = nextOffset;
  2609. }
  2610. BABYLON.Tools.Error("internal error");
  2611. return Vector2.Zero();
  2612. };
  2613. Path2.StartingAt = function (x, y) {
  2614. return new Path2(x, y);
  2615. };
  2616. return Path2;
  2617. })();
  2618. BABYLON.Path2 = Path2;
  2619. var Path3D = (function () {
  2620. function Path3D(path) {
  2621. this.path = path;
  2622. this._curve = new Array();
  2623. this._distances = new Array();
  2624. this._tangents = new Array();
  2625. this._normals = new Array();
  2626. this._binormals = new Array();
  2627. this._curve = path.slice(); // copy array
  2628. var l = this._curve.length;
  2629. // first and last tangents
  2630. this._tangents[0] = this._curve[1].subtract(this._curve[0]);
  2631. this._tangents[0].normalize();
  2632. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2633. this._tangents[l - 1].normalize();
  2634. // normals and binormals at first point : arbitrary vector with _normalVector()
  2635. var tg0 = this._tangents[0];
  2636. var pp0 = this._normalVector(this._curve[0], tg0);
  2637. this._normals[0] = pp0;
  2638. this._normals[0].normalize();
  2639. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2640. this._normals[0].normalize();
  2641. this._distances[0] = 0;
  2642. // normals and binormals : next points
  2643. var prev; // previous vector (segment)
  2644. var cur; // current vector (segment)
  2645. var curTang; // current tangent
  2646. var prevNorm; // previous normal
  2647. var prevBinor; // previous binormal
  2648. for (var i = 1; i < l; i++) {
  2649. // tangents
  2650. prev = this._curve[i].subtract(this._curve[i - 1]);
  2651. if (i < l - 1) {
  2652. cur = this._curve[i + 1].subtract(this._curve[i]);
  2653. this._tangents[i] = prev.add(cur);
  2654. this._tangents[i].normalize();
  2655. }
  2656. this._distances[i] = this._distances[i - 1] + prev.length();
  2657. // normals and binormals
  2658. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  2659. curTang = this._tangents[i];
  2660. prevNorm = this._normals[i - 1];
  2661. prevBinor = this._binormals[i - 1];
  2662. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  2663. this._normals[i].normalize();
  2664. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  2665. this._binormals[i].normalize();
  2666. }
  2667. }
  2668. Path3D.prototype.getCurve = function () {
  2669. return this._curve;
  2670. };
  2671. Path3D.prototype.getTangents = function () {
  2672. return this._tangents;
  2673. };
  2674. Path3D.prototype.getNormals = function () {
  2675. return this._normals;
  2676. };
  2677. Path3D.prototype.getBinormals = function () {
  2678. return this._binormals;
  2679. };
  2680. Path3D.prototype.getDistances = function () {
  2681. return this._distances;
  2682. };
  2683. // private function normalVector(v0, vt) :
  2684. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  2685. Path3D.prototype._normalVector = function (v0, vt) {
  2686. var point;
  2687. if (vt.x !== 1) {
  2688. point = new Vector3(1, 0, 0);
  2689. }
  2690. else if (vt.y !== 1) {
  2691. point = new Vector3(0, 1, 0);
  2692. }
  2693. else if (vt.z !== 1) {
  2694. point = new Vector3(0, 0, 1);
  2695. }
  2696. var normal0 = Vector3.Cross(vt, point);
  2697. normal0.normalize();
  2698. return normal0;
  2699. };
  2700. return Path3D;
  2701. })();
  2702. BABYLON.Path3D = Path3D;
  2703. var Curve3 = (function () {
  2704. function Curve3(points) {
  2705. this._points = points;
  2706. }
  2707. // QuadraticBezier(origin_V3, control_V3, destination_V3 )
  2708. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  2709. nbPoints = nbPoints > 2 ? nbPoints : 3;
  2710. var bez = new Array();
  2711. var step = 1 / nbPoints;
  2712. var equation = function (t, val0, val1, val2) {
  2713. var res = (1 - t) * (1 - t) * val0 + 2 * t * (1 - t) * val1 + t * t * val2;
  2714. return res;
  2715. };
  2716. for (var i = 0; i <= 1; i += step) {
  2717. bez.push(new Vector3(equation(i, v0.x, v1.x, v2.x), equation(i, v0.y, v1.y, v2.y), equation(i, v0.z, v1.z, v2.z)));
  2718. }
  2719. return new Curve3(bez);
  2720. };
  2721. // CubicBezier(origin_V3, control1_V3, control2_V3, destination_V3)
  2722. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  2723. nbPoints = nbPoints > 3 ? nbPoints : 4;
  2724. var bez = new Array();
  2725. var step = 1 / nbPoints;
  2726. var equation = function (t, val0, val1, val2, val3) {
  2727. var res = (1 - t) * (1 - t) * (1 - t) * val0 + 3 * t * (1 - t) * (1 - t) * val1 + 3 * t * t * (1 - t) * val2 + t * t * t * val3;
  2728. return res;
  2729. };
  2730. for (var i = 0; i <= 1; i += step) {
  2731. bez.push(new Vector3(equation(i, v0.x, v1.x, v2.x, v3.x), equation(i, v0.y, v1.y, v2.y, v3.y), equation(i, v0.z, v1.z, v2.z, v3.z)));
  2732. }
  2733. return new Curve3(bez);
  2734. };
  2735. Curve3.prototype.getPoints = function () {
  2736. return this._points;
  2737. };
  2738. Curve3.prototype.continue = function (curve) {
  2739. var lastPoint = this._points[this._points.length - 1];
  2740. var continuedPoints = this._points.slice();
  2741. var curvePoints = curve.getPoints();
  2742. for (var i = 1; i < curvePoints.length; i++) {
  2743. continuedPoints.push(curvePoints[i].add(lastPoint));
  2744. }
  2745. return new Curve3(continuedPoints);
  2746. };
  2747. return Curve3;
  2748. })();
  2749. BABYLON.Curve3 = Curve3;
  2750. // SIMD
  2751. if (window.SIMD !== undefined) {
  2752. // Replace functions
  2753. Matrix.prototype.multiplyToArray = Matrix.prototype.multiplyToArraySIMD;
  2754. Matrix.prototype.invertToRef = Matrix.prototype.invertToRefSIMD;
  2755. Matrix.LookAtLHToRef = Matrix.LookAtLHToRefSIMD;
  2756. Vector3.TransformCoordinatesToRef = Vector3.TransformCoordinatesToRefSIMD;
  2757. Vector3.TransformCoordinatesFromFloatsToRef = Vector3.TransformCoordinatesFromFloatsToRefSIMD;
  2758. Object.defineProperty(BABYLON.Vector3.prototype, "x", {
  2759. get: function () {
  2760. return this._data[0];
  2761. },
  2762. set: function (value) {
  2763. if (!this._data) {
  2764. this._data = new Float32Array(3);
  2765. }
  2766. this._data[0] = value;
  2767. }
  2768. });
  2769. Object.defineProperty(BABYLON.Vector3.prototype, "y", {
  2770. get: function () {
  2771. return this._data[1];
  2772. },
  2773. set: function (value) {
  2774. this._data[1] = value;
  2775. }
  2776. });
  2777. Object.defineProperty(BABYLON.Vector3.prototype, "z", {
  2778. get: function () {
  2779. return this._data[2];
  2780. },
  2781. set: function (value) {
  2782. this._data[2] = value;
  2783. }
  2784. });
  2785. }
  2786. })(BABYLON || (BABYLON = {}));
  2787. //# sourceMappingURL=babylon.math.js.mapvar BABYLON;
  2788. (function (BABYLON) {
  2789. // Screenshots
  2790. var screenshotCanvas;
  2791. var cloneValue = function (source, destinationObject) {
  2792. if (!source)
  2793. return null;
  2794. if (source instanceof BABYLON.Mesh) {
  2795. return null;
  2796. }
  2797. if (source instanceof BABYLON.SubMesh) {
  2798. return source.clone(destinationObject);
  2799. }
  2800. else if (source.clone) {
  2801. return source.clone();
  2802. }
  2803. return null;
  2804. };
  2805. var Tools = (function () {
  2806. function Tools() {
  2807. }
  2808. Tools.GetFilename = function (path) {
  2809. var index = path.lastIndexOf("/");
  2810. if (index < 0)
  2811. return path;
  2812. return path.substring(index + 1);
  2813. };
  2814. Tools.GetDOMTextContent = function (element) {
  2815. var result = "";
  2816. var child = element.firstChild;
  2817. while (child) {
  2818. if (child.nodeType === 3) {
  2819. result += child.textContent;
  2820. }
  2821. child = child.nextSibling;
  2822. }
  2823. return result;
  2824. };
  2825. Tools.ToDegrees = function (angle) {
  2826. return angle * 180 / Math.PI;
  2827. };
  2828. Tools.ToRadians = function (angle) {
  2829. return angle * Math.PI / 180;
  2830. };
  2831. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  2832. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  2833. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  2834. for (var index = indexStart; index < indexStart + indexCount; index++) {
  2835. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  2836. minimum = BABYLON.Vector3.Minimize(current, minimum);
  2837. maximum = BABYLON.Vector3.Maximize(current, maximum);
  2838. }
  2839. return {
  2840. minimum: minimum,
  2841. maximum: maximum
  2842. };
  2843. };
  2844. Tools.ExtractMinAndMax = function (positions, start, count) {
  2845. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  2846. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  2847. for (var index = start; index < start + count; index++) {
  2848. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  2849. minimum = BABYLON.Vector3.Minimize(current, minimum);
  2850. maximum = BABYLON.Vector3.Maximize(current, maximum);
  2851. }
  2852. return {
  2853. minimum: minimum,
  2854. maximum: maximum
  2855. };
  2856. };
  2857. Tools.MakeArray = function (obj, allowsNullUndefined) {
  2858. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  2859. return undefined;
  2860. return Array.isArray(obj) ? obj : [obj];
  2861. };
  2862. // Misc.
  2863. Tools.GetPointerPrefix = function () {
  2864. var eventPrefix = "pointer";
  2865. // Check if hand.js is referenced or if the browser natively supports pointer events
  2866. if (!navigator.pointerEnabled) {
  2867. eventPrefix = "mouse";
  2868. }
  2869. return eventPrefix;
  2870. };
  2871. Tools.QueueNewFrame = function (func) {
  2872. if (window.requestAnimationFrame)
  2873. window.requestAnimationFrame(func);
  2874. else if (window.msRequestAnimationFrame)
  2875. window.msRequestAnimationFrame(func);
  2876. else if (window.webkitRequestAnimationFrame)
  2877. window.webkitRequestAnimationFrame(func);
  2878. else if (window.mozRequestAnimationFrame)
  2879. window.mozRequestAnimationFrame(func);
  2880. else if (window.oRequestAnimationFrame)
  2881. window.oRequestAnimationFrame(func);
  2882. else {
  2883. window.setTimeout(func, 16);
  2884. }
  2885. };
  2886. Tools.RequestFullscreen = function (element) {
  2887. if (element.requestFullscreen)
  2888. element.requestFullscreen();
  2889. else if (element.msRequestFullscreen)
  2890. element.msRequestFullscreen();
  2891. else if (element.webkitRequestFullscreen)
  2892. element.webkitRequestFullscreen();
  2893. else if (element.mozRequestFullScreen)
  2894. element.mozRequestFullScreen();
  2895. };
  2896. Tools.ExitFullscreen = function () {
  2897. if (document.exitFullscreen) {
  2898. document.exitFullscreen();
  2899. }
  2900. else if (document.mozCancelFullScreen) {
  2901. document.mozCancelFullScreen();
  2902. }
  2903. else if (document.webkitCancelFullScreen) {
  2904. document.webkitCancelFullScreen();
  2905. }
  2906. else if (document.msCancelFullScreen) {
  2907. document.msCancelFullScreen();
  2908. }
  2909. };
  2910. // External files
  2911. Tools.CleanUrl = function (url) {
  2912. url = url.replace(/#/mg, "%23");
  2913. return url;
  2914. };
  2915. Tools.LoadImage = function (url, onload, onerror, database) {
  2916. url = Tools.CleanUrl(url);
  2917. var img = new Image();
  2918. if (url.substr(0, 5) !== "data:")
  2919. img.crossOrigin = 'anonymous';
  2920. img.onload = function () {
  2921. onload(img);
  2922. };
  2923. img.onerror = function (err) {
  2924. onerror(img, err);
  2925. };
  2926. var noIndexedDB = function () {
  2927. img.src = url;
  2928. };
  2929. var loadFromIndexedDB = function () {
  2930. database.loadImageFromDB(url, img);
  2931. };
  2932. //ANY database to do!
  2933. if (database && database.enableTexturesOffline && BABYLON.Database.isUASupportingBlobStorage) {
  2934. database.openAsync(loadFromIndexedDB, noIndexedDB);
  2935. }
  2936. else {
  2937. if (url.indexOf("file:") === -1) {
  2938. noIndexedDB();
  2939. }
  2940. else {
  2941. try {
  2942. var textureName = url.substring(5);
  2943. var blobURL;
  2944. try {
  2945. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  2946. }
  2947. catch (ex) {
  2948. // Chrome doesn't support oneTimeOnly parameter
  2949. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  2950. }
  2951. img.src = blobURL;
  2952. }
  2953. catch (e) {
  2954. Tools.Log("Error while trying to load texture: " + textureName);
  2955. img.src = null;
  2956. }
  2957. }
  2958. }
  2959. return img;
  2960. };
  2961. //ANY
  2962. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  2963. url = Tools.CleanUrl(url);
  2964. var noIndexedDB = function () {
  2965. var request = new XMLHttpRequest();
  2966. var loadUrl = Tools.BaseUrl + url;
  2967. request.open('GET', loadUrl, true);
  2968. if (useArrayBuffer) {
  2969. request.responseType = "arraybuffer";
  2970. }
  2971. request.onprogress = progressCallBack;
  2972. request.onreadystatechange = function () {
  2973. if (request.readyState === 4) {
  2974. if (request.status === 200 || Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  2975. callback(!useArrayBuffer ? request.responseText : request.response);
  2976. }
  2977. else {
  2978. if (onError) {
  2979. onError();
  2980. }
  2981. else {
  2982. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  2983. }
  2984. }
  2985. }
  2986. };
  2987. request.send(null);
  2988. };
  2989. var loadFromIndexedDB = function () {
  2990. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  2991. };
  2992. if (url.indexOf("file:") !== -1) {
  2993. var fileName = url.substring(5);
  2994. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  2995. }
  2996. else {
  2997. // Caching all files
  2998. if (database && database.enableSceneOffline) {
  2999. database.openAsync(loadFromIndexedDB, noIndexedDB);
  3000. }
  3001. else {
  3002. noIndexedDB();
  3003. }
  3004. }
  3005. };
  3006. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  3007. var reader = new FileReader();
  3008. reader.onload = function (e) {
  3009. //target doesn't have result from ts 1.3
  3010. callback(e.target['result']);
  3011. };
  3012. reader.onprogress = progressCallback;
  3013. reader.readAsDataURL(fileToLoad);
  3014. };
  3015. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  3016. var reader = new FileReader();
  3017. reader.onerror = function (e) {
  3018. Tools.Log("Error while reading file: " + fileToLoad.name);
  3019. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.81, 0], meshes: [], cameras: [], lights: [] }));
  3020. };
  3021. reader.onload = function (e) {
  3022. //target doesn't have result from ts 1.3
  3023. callback(e.target['result']);
  3024. };
  3025. reader.onprogress = progressCallBack;
  3026. if (!useArrayBuffer) {
  3027. // Asynchronous read
  3028. reader.readAsText(fileToLoad);
  3029. }
  3030. else {
  3031. reader.readAsArrayBuffer(fileToLoad);
  3032. }
  3033. };
  3034. // Misc.
  3035. Tools.Clamp = function (value, min, max) {
  3036. if (min === void 0) { min = 0; }
  3037. if (max === void 0) { max = 1; }
  3038. return Math.min(max, Math.max(min, value));
  3039. };
  3040. // Returns -1 when value is a negative number and
  3041. // +1 when value is a positive number.
  3042. Tools.Sign = function (value) {
  3043. value = +value; // convert to a number
  3044. if (value === 0 || isNaN(value))
  3045. return value;
  3046. return value > 0 ? 1 : -1;
  3047. };
  3048. Tools.Format = function (value, decimals) {
  3049. if (decimals === void 0) { decimals = 2; }
  3050. return value.toFixed(decimals);
  3051. };
  3052. Tools.CheckExtends = function (v, min, max) {
  3053. if (v.x < min.x)
  3054. min.x = v.x;
  3055. if (v.y < min.y)
  3056. min.y = v.y;
  3057. if (v.z < min.z)
  3058. min.z = v.z;
  3059. if (v.x > max.x)
  3060. max.x = v.x;
  3061. if (v.y > max.y)
  3062. max.y = v.y;
  3063. if (v.z > max.z)
  3064. max.z = v.z;
  3065. };
  3066. Tools.WithinEpsilon = function (a, b, epsilon) {
  3067. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  3068. var num = a - b;
  3069. return -epsilon <= num && num <= epsilon;
  3070. };
  3071. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  3072. for (var prop in source) {
  3073. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  3074. continue;
  3075. }
  3076. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  3077. continue;
  3078. }
  3079. var sourceValue = source[prop];
  3080. var typeOfSourceValue = typeof sourceValue;
  3081. if (typeOfSourceValue === "function") {
  3082. continue;
  3083. }
  3084. if (typeOfSourceValue === "object") {
  3085. if (sourceValue instanceof Array) {
  3086. destination[prop] = [];
  3087. if (sourceValue.length > 0) {
  3088. if (typeof sourceValue[0] == "object") {
  3089. for (var index = 0; index < sourceValue.length; index++) {
  3090. var clonedValue = cloneValue(sourceValue[index], destination);
  3091. if (destination[prop].indexOf(clonedValue) === -1) {
  3092. destination[prop].push(clonedValue);
  3093. }
  3094. }
  3095. }
  3096. else {
  3097. destination[prop] = sourceValue.slice(0);
  3098. }
  3099. }
  3100. }
  3101. else {
  3102. destination[prop] = cloneValue(sourceValue, destination);
  3103. }
  3104. }
  3105. else {
  3106. destination[prop] = sourceValue;
  3107. }
  3108. }
  3109. };
  3110. Tools.IsEmpty = function (obj) {
  3111. for (var i in obj) {
  3112. return false;
  3113. }
  3114. return true;
  3115. };
  3116. Tools.RegisterTopRootEvents = function (events) {
  3117. for (var index = 0; index < events.length; index++) {
  3118. var event = events[index];
  3119. window.addEventListener(event.name, event.handler, false);
  3120. try {
  3121. if (window.parent) {
  3122. window.parent.addEventListener(event.name, event.handler, false);
  3123. }
  3124. }
  3125. catch (e) {
  3126. }
  3127. }
  3128. };
  3129. Tools.UnregisterTopRootEvents = function (events) {
  3130. for (var index = 0; index < events.length; index++) {
  3131. var event = events[index];
  3132. window.removeEventListener(event.name, event.handler);
  3133. try {
  3134. if (window.parent) {
  3135. window.parent.removeEventListener(event.name, event.handler);
  3136. }
  3137. }
  3138. catch (e) {
  3139. }
  3140. }
  3141. };
  3142. Tools.DumpFramebuffer = function (width, height, engine) {
  3143. // Read the contents of the framebuffer
  3144. var numberOfChannelsByLine = width * 4;
  3145. var halfHeight = height / 2;
  3146. //Reading datas from WebGL
  3147. var data = engine.readPixels(0, 0, width, height);
  3148. for (var i = 0; i < halfHeight; i++) {
  3149. for (var j = 0; j < numberOfChannelsByLine; j++) {
  3150. var currentCell = j + i * numberOfChannelsByLine;
  3151. var targetLine = height - i - 1;
  3152. var targetCell = j + targetLine * numberOfChannelsByLine;
  3153. var temp = data[currentCell];
  3154. data[currentCell] = data[targetCell];
  3155. data[targetCell] = temp;
  3156. }
  3157. }
  3158. // Create a 2D canvas to store the result
  3159. if (!screenshotCanvas) {
  3160. screenshotCanvas = document.createElement('canvas');
  3161. }
  3162. screenshotCanvas.width = width;
  3163. screenshotCanvas.height = height;
  3164. var context = screenshotCanvas.getContext('2d');
  3165. // Copy the pixels to a 2D canvas
  3166. var imageData = context.createImageData(width, height);
  3167. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  3168. var castData = imageData.data;
  3169. castData.set(data);
  3170. context.putImageData(imageData, 0, 0);
  3171. var base64Image = screenshotCanvas.toDataURL();
  3172. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  3173. if (("download" in document.createElement("a"))) {
  3174. var a = window.document.createElement("a");
  3175. a.href = base64Image;
  3176. var date = new Date();
  3177. var stringDate = date.getFullYear() + "/" + date.getMonth() + "/" + date.getDate() + "-" + date.getHours() + ":" + date.getMinutes();
  3178. a.setAttribute("download", "screenshot-" + stringDate + ".png");
  3179. window.document.body.appendChild(a);
  3180. a.addEventListener("click", function () {
  3181. a.parentElement.removeChild(a);
  3182. });
  3183. a.click();
  3184. }
  3185. else {
  3186. var newWindow = window.open("");
  3187. var img = newWindow.document.createElement("img");
  3188. img.src = base64Image;
  3189. newWindow.document.body.appendChild(img);
  3190. }
  3191. };
  3192. Tools.CreateScreenshot = function (engine, camera, size) {
  3193. var width;
  3194. var height;
  3195. var scene = camera.getScene();
  3196. var previousCamera = null;
  3197. if (scene.activeCamera !== camera) {
  3198. previousCamera = scene.activeCamera;
  3199. scene.activeCamera = camera;
  3200. }
  3201. //If a precision value is specified
  3202. if (size.precision) {
  3203. width = Math.round(engine.getRenderWidth() * size.precision);
  3204. height = Math.round(width / engine.getAspectRatio(camera));
  3205. size = { width: width, height: height };
  3206. }
  3207. else if (size.width && size.height) {
  3208. width = size.width;
  3209. height = size.height;
  3210. }
  3211. else if (size.width && !size.height) {
  3212. width = size.width;
  3213. height = Math.round(width / engine.getAspectRatio(camera));
  3214. size = { width: width, height: height };
  3215. }
  3216. else if (size.height && !size.width) {
  3217. height = size.height;
  3218. width = Math.round(height * engine.getAspectRatio(camera));
  3219. size = { width: width, height: height };
  3220. }
  3221. else if (!isNaN(size)) {
  3222. height = size;
  3223. width = size;
  3224. }
  3225. else {
  3226. Tools.Error("Invalid 'size' parameter !");
  3227. return;
  3228. }
  3229. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  3230. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  3231. texture.renderList = scene.meshes;
  3232. texture.onAfterRender = function () {
  3233. Tools.DumpFramebuffer(width, height, engine);
  3234. };
  3235. scene.incrementRenderId();
  3236. texture.render(true);
  3237. texture.dispose();
  3238. if (previousCamera) {
  3239. scene.activeCamera = previousCamera;
  3240. }
  3241. };
  3242. // XHR response validator for local file scenario
  3243. Tools.ValidateXHRData = function (xhr, dataType) {
  3244. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  3245. if (dataType === void 0) { dataType = 7; }
  3246. try {
  3247. if (dataType & 1) {
  3248. if (xhr.responseText && xhr.responseText.length > 0) {
  3249. return true;
  3250. }
  3251. else if (dataType === 1) {
  3252. return false;
  3253. }
  3254. }
  3255. if (dataType & 2) {
  3256. // Check header width and height since there is no "TGA" magic number
  3257. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  3258. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  3259. return true;
  3260. }
  3261. else if (dataType === 2) {
  3262. return false;
  3263. }
  3264. }
  3265. if (dataType & 4) {
  3266. // Check for the "DDS" magic number
  3267. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  3268. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  3269. return true;
  3270. }
  3271. else {
  3272. return false;
  3273. }
  3274. }
  3275. }
  3276. catch (e) {
  3277. }
  3278. return false;
  3279. };
  3280. Object.defineProperty(Tools, "NoneLogLevel", {
  3281. get: function () {
  3282. return Tools._NoneLogLevel;
  3283. },
  3284. enumerable: true,
  3285. configurable: true
  3286. });
  3287. Object.defineProperty(Tools, "MessageLogLevel", {
  3288. get: function () {
  3289. return Tools._MessageLogLevel;
  3290. },
  3291. enumerable: true,
  3292. configurable: true
  3293. });
  3294. Object.defineProperty(Tools, "WarningLogLevel", {
  3295. get: function () {
  3296. return Tools._WarningLogLevel;
  3297. },
  3298. enumerable: true,
  3299. configurable: true
  3300. });
  3301. Object.defineProperty(Tools, "ErrorLogLevel", {
  3302. get: function () {
  3303. return Tools._ErrorLogLevel;
  3304. },
  3305. enumerable: true,
  3306. configurable: true
  3307. });
  3308. Object.defineProperty(Tools, "AllLogLevel", {
  3309. get: function () {
  3310. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  3311. },
  3312. enumerable: true,
  3313. configurable: true
  3314. });
  3315. Tools._AddLogEntry = function (entry) {
  3316. Tools._LogCache = entry + Tools._LogCache;
  3317. if (Tools.OnNewCacheEntry) {
  3318. Tools.OnNewCacheEntry(entry);
  3319. }
  3320. };
  3321. Tools._FormatMessage = function (message) {
  3322. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  3323. var date = new Date();
  3324. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  3325. };
  3326. Tools._LogDisabled = function (message) {
  3327. // nothing to do
  3328. };
  3329. Tools._LogEnabled = function (message) {
  3330. var formattedMessage = Tools._FormatMessage(message);
  3331. console.log("BJS - " + formattedMessage);
  3332. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  3333. Tools._AddLogEntry(entry);
  3334. };
  3335. Tools._WarnDisabled = function (message) {
  3336. // nothing to do
  3337. };
  3338. Tools._WarnEnabled = function (message) {
  3339. var formattedMessage = Tools._FormatMessage(message);
  3340. console.warn("BJS - " + formattedMessage);
  3341. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  3342. Tools._AddLogEntry(entry);
  3343. };
  3344. Tools._ErrorDisabled = function (message) {
  3345. // nothing to do
  3346. };
  3347. Tools._ErrorEnabled = function (message) {
  3348. var formattedMessage = Tools._FormatMessage(message);
  3349. console.error("BJS - " + formattedMessage);
  3350. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  3351. Tools._AddLogEntry(entry);
  3352. };
  3353. Object.defineProperty(Tools, "LogCache", {
  3354. get: function () {
  3355. return Tools._LogCache;
  3356. },
  3357. enumerable: true,
  3358. configurable: true
  3359. });
  3360. Object.defineProperty(Tools, "LogLevels", {
  3361. set: function (level) {
  3362. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  3363. Tools.Log = Tools._LogEnabled;
  3364. }
  3365. else {
  3366. Tools.Log = Tools._LogDisabled;
  3367. }
  3368. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  3369. Tools.Warn = Tools._WarnEnabled;
  3370. }
  3371. else {
  3372. Tools.Warn = Tools._WarnDisabled;
  3373. }
  3374. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  3375. Tools.Error = Tools._ErrorEnabled;
  3376. }
  3377. else {
  3378. Tools.Error = Tools._ErrorDisabled;
  3379. }
  3380. },
  3381. enumerable: true,
  3382. configurable: true
  3383. });
  3384. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  3385. get: function () {
  3386. return Tools._PerformanceNoneLogLevel;
  3387. },
  3388. enumerable: true,
  3389. configurable: true
  3390. });
  3391. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  3392. get: function () {
  3393. return Tools._PerformanceUserMarkLogLevel;
  3394. },
  3395. enumerable: true,
  3396. configurable: true
  3397. });
  3398. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  3399. get: function () {
  3400. return Tools._PerformanceConsoleLogLevel;
  3401. },
  3402. enumerable: true,
  3403. configurable: true
  3404. });
  3405. Object.defineProperty(Tools, "PerformanceLogLevel", {
  3406. set: function (level) {
  3407. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  3408. Tools.StartPerformanceCounter = Tools._StartUserMark;
  3409. Tools.EndPerformanceCounter = Tools._EndUserMark;
  3410. return;
  3411. }
  3412. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  3413. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  3414. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  3415. return;
  3416. }
  3417. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  3418. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  3419. },
  3420. enumerable: true,
  3421. configurable: true
  3422. });
  3423. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  3424. };
  3425. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  3426. };
  3427. Tools._StartUserMark = function (counterName, condition) {
  3428. if (condition === void 0) { condition = true; }
  3429. if (!condition || !Tools._performance.mark) {
  3430. return;
  3431. }
  3432. Tools._performance.mark(counterName + "-Begin");
  3433. };
  3434. Tools._EndUserMark = function (counterName, condition) {
  3435. if (condition === void 0) { condition = true; }
  3436. if (!condition || !Tools._performance.mark) {
  3437. return;
  3438. }
  3439. Tools._performance.mark(counterName + "-End");
  3440. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  3441. };
  3442. Tools._StartPerformanceConsole = function (counterName, condition) {
  3443. if (condition === void 0) { condition = true; }
  3444. if (!condition) {
  3445. return;
  3446. }
  3447. Tools._StartUserMark(counterName, condition);
  3448. if (console.time) {
  3449. console.time(counterName);
  3450. }
  3451. };
  3452. Tools._EndPerformanceConsole = function (counterName, condition) {
  3453. if (condition === void 0) { condition = true; }
  3454. if (!condition) {
  3455. return;
  3456. }
  3457. Tools._EndUserMark(counterName, condition);
  3458. if (console.time) {
  3459. console.timeEnd(counterName);
  3460. }
  3461. };
  3462. Object.defineProperty(Tools, "Now", {
  3463. get: function () {
  3464. if (window.performance && window.performance.now) {
  3465. return window.performance.now();
  3466. }
  3467. return new Date().getTime();
  3468. },
  3469. enumerable: true,
  3470. configurable: true
  3471. });
  3472. // Deprecated
  3473. Tools.GetFps = function () {
  3474. Tools.Warn("Tools.GetFps() is deprecated. Please use engine.getFps() instead");
  3475. return 0;
  3476. };
  3477. Tools.BaseUrl = "";
  3478. Tools.GetExponantOfTwo = function (value, max) {
  3479. var count = 1;
  3480. do {
  3481. count *= 2;
  3482. } while (count < value);
  3483. if (count > max)
  3484. count = max;
  3485. return count;
  3486. };
  3487. // Logs
  3488. Tools._NoneLogLevel = 0;
  3489. Tools._MessageLogLevel = 1;
  3490. Tools._WarningLogLevel = 2;
  3491. Tools._ErrorLogLevel = 4;
  3492. Tools._LogCache = "";
  3493. Tools.Log = Tools._LogEnabled;
  3494. Tools.Warn = Tools._WarnEnabled;
  3495. Tools.Error = Tools._ErrorEnabled;
  3496. // Performances
  3497. Tools._PerformanceNoneLogLevel = 0;
  3498. Tools._PerformanceUserMarkLogLevel = 1;
  3499. Tools._PerformanceConsoleLogLevel = 2;
  3500. Tools._performance = window.performance;
  3501. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  3502. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  3503. return Tools;
  3504. })();
  3505. BABYLON.Tools = Tools;
  3506. /**
  3507. * An implementation of a loop for asynchronous functions.
  3508. */
  3509. var AsyncLoop = (function () {
  3510. /**
  3511. * Constroctor.
  3512. * @param iterations the number of iterations.
  3513. * @param _fn the function to run each iteration
  3514. * @param _successCallback the callback that will be called upon succesful execution
  3515. * @param offset starting offset.
  3516. */
  3517. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  3518. if (offset === void 0) { offset = 0; }
  3519. this.iterations = iterations;
  3520. this._fn = _fn;
  3521. this._successCallback = _successCallback;
  3522. this.index = offset - 1;
  3523. this._done = false;
  3524. }
  3525. /**
  3526. * Execute the next iteration. Must be called after the last iteration was finished.
  3527. */
  3528. AsyncLoop.prototype.executeNext = function () {
  3529. if (!this._done) {
  3530. if (this.index + 1 < this.iterations) {
  3531. ++this.index;
  3532. this._fn(this);
  3533. }
  3534. else {
  3535. this.breakLoop();
  3536. }
  3537. }
  3538. };
  3539. /**
  3540. * Break the loop and run the success callback.
  3541. */
  3542. AsyncLoop.prototype.breakLoop = function () {
  3543. this._done = true;
  3544. this._successCallback();
  3545. };
  3546. /**
  3547. * Helper function
  3548. */
  3549. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  3550. if (offset === void 0) { offset = 0; }
  3551. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  3552. loop.executeNext();
  3553. return loop;
  3554. };
  3555. /**
  3556. * A for-loop that will run a given number of iterations synchronous and the rest async.
  3557. * @param iterations total number of iterations
  3558. * @param syncedIterations number of synchronous iterations in each async iteration.
  3559. * @param fn the function to call each iteration.
  3560. * @param callback a success call back that will be called when iterating stops.
  3561. * @param breakFunction a break condition (optional)
  3562. * @param timeout timeout settings for the setTimeout function. default - 0.
  3563. * @constructor
  3564. */
  3565. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  3566. if (timeout === void 0) { timeout = 0; }
  3567. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  3568. if (breakFunction && breakFunction())
  3569. loop.breakLoop();
  3570. else {
  3571. setTimeout(function () {
  3572. for (var i = 0; i < syncedIterations; ++i) {
  3573. var iteration = (loop.index * syncedIterations) + i;
  3574. if (iteration >= iterations)
  3575. break;
  3576. fn(iteration);
  3577. if (breakFunction && breakFunction()) {
  3578. loop.breakLoop();
  3579. break;
  3580. }
  3581. }
  3582. loop.executeNext();
  3583. }, timeout);
  3584. }
  3585. }, callback);
  3586. };
  3587. return AsyncLoop;
  3588. })();
  3589. BABYLON.AsyncLoop = AsyncLoop;
  3590. })(BABYLON || (BABYLON = {}));
  3591. //# sourceMappingURL=babylon.tools.js.mapvar BABYLON;
  3592. (function (BABYLON) {
  3593. var _DepthCullingState = (function () {
  3594. function _DepthCullingState() {
  3595. this._isDepthTestDirty = false;
  3596. this._isDepthMaskDirty = false;
  3597. this._isDepthFuncDirty = false;
  3598. this._isCullFaceDirty = false;
  3599. this._isCullDirty = false;
  3600. }
  3601. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  3602. get: function () {
  3603. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty;
  3604. },
  3605. enumerable: true,
  3606. configurable: true
  3607. });
  3608. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  3609. get: function () {
  3610. return this._cullFace;
  3611. },
  3612. set: function (value) {
  3613. if (this._cullFace === value) {
  3614. return;
  3615. }
  3616. this._cullFace = value;
  3617. this._isCullFaceDirty = true;
  3618. },
  3619. enumerable: true,
  3620. configurable: true
  3621. });
  3622. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  3623. get: function () {
  3624. return this._cull;
  3625. },
  3626. set: function (value) {
  3627. if (this._cull === value) {
  3628. return;
  3629. }
  3630. this._cull = value;
  3631. this._isCullDirty = true;
  3632. },
  3633. enumerable: true,
  3634. configurable: true
  3635. });
  3636. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  3637. get: function () {
  3638. return this._depthFunc;
  3639. },
  3640. set: function (value) {
  3641. if (this._depthFunc === value) {
  3642. return;
  3643. }
  3644. this._depthFunc = value;
  3645. this._isDepthFuncDirty = true;
  3646. },
  3647. enumerable: true,
  3648. configurable: true
  3649. });
  3650. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  3651. get: function () {
  3652. return this._depthMask;
  3653. },
  3654. set: function (value) {
  3655. if (this._depthMask === value) {
  3656. return;
  3657. }
  3658. this._depthMask = value;
  3659. this._isDepthMaskDirty = true;
  3660. },
  3661. enumerable: true,
  3662. configurable: true
  3663. });
  3664. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  3665. get: function () {
  3666. return this._depthTest;
  3667. },
  3668. set: function (value) {
  3669. if (this._depthTest === value) {
  3670. return;
  3671. }
  3672. this._depthTest = value;
  3673. this._isDepthTestDirty = true;
  3674. },
  3675. enumerable: true,
  3676. configurable: true
  3677. });
  3678. _DepthCullingState.prototype.reset = function () {
  3679. this._depthMask = true;
  3680. this._depthTest = true;
  3681. this._depthFunc = null;
  3682. this._cull = null;
  3683. this._cullFace = null;
  3684. this._isDepthTestDirty = true;
  3685. this._isDepthMaskDirty = true;
  3686. this._isDepthFuncDirty = false;
  3687. this._isCullFaceDirty = false;
  3688. this._isCullDirty = false;
  3689. };
  3690. _DepthCullingState.prototype.apply = function (gl) {
  3691. if (!this.isDirty) {
  3692. return;
  3693. }
  3694. // Cull
  3695. if (this._isCullDirty) {
  3696. if (this.cull) {
  3697. gl.enable(gl.CULL_FACE);
  3698. }
  3699. else {
  3700. gl.disable(gl.CULL_FACE);
  3701. }
  3702. this._isCullDirty = false;
  3703. }
  3704. // Cull face
  3705. if (this._isCullFaceDirty) {
  3706. gl.cullFace(this.cullFace);
  3707. this._isCullFaceDirty = false;
  3708. }
  3709. // Depth mask
  3710. if (this._isDepthMaskDirty) {
  3711. gl.depthMask(this.depthMask);
  3712. this._isDepthMaskDirty = false;
  3713. }
  3714. // Depth test
  3715. if (this._isDepthTestDirty) {
  3716. if (this.depthTest) {
  3717. gl.enable(gl.DEPTH_TEST);
  3718. }
  3719. else {
  3720. gl.disable(gl.DEPTH_TEST);
  3721. }
  3722. this._isDepthTestDirty = false;
  3723. }
  3724. // Depth func
  3725. if (this._isDepthFuncDirty) {
  3726. gl.depthFunc(this.depthFunc);
  3727. this._isDepthFuncDirty = false;
  3728. }
  3729. };
  3730. return _DepthCullingState;
  3731. })();
  3732. BABYLON._DepthCullingState = _DepthCullingState;
  3733. var _AlphaState = (function () {
  3734. function _AlphaState() {
  3735. this._isAlphaBlendDirty = false;
  3736. this._isBlendFunctionParametersDirty = false;
  3737. this._alphaBlend = false;
  3738. this._blendFunctionParameters = new Array(4);
  3739. }
  3740. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  3741. get: function () {
  3742. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  3743. },
  3744. enumerable: true,
  3745. configurable: true
  3746. });
  3747. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  3748. get: function () {
  3749. return this._alphaBlend;
  3750. },
  3751. set: function (value) {
  3752. if (this._alphaBlend === value) {
  3753. return;
  3754. }
  3755. this._alphaBlend = value;
  3756. this._isAlphaBlendDirty = true;
  3757. },
  3758. enumerable: true,
  3759. configurable: true
  3760. });
  3761. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  3762. if (this._blendFunctionParameters[0] === value0 && this._blendFunctionParameters[1] === value1 && this._blendFunctionParameters[2] === value2 && this._blendFunctionParameters[3] === value3) {
  3763. return;
  3764. }
  3765. this._blendFunctionParameters[0] = value0;
  3766. this._blendFunctionParameters[1] = value1;
  3767. this._blendFunctionParameters[2] = value2;
  3768. this._blendFunctionParameters[3] = value3;
  3769. this._isBlendFunctionParametersDirty = true;
  3770. };
  3771. _AlphaState.prototype.reset = function () {
  3772. this._alphaBlend = false;
  3773. this._blendFunctionParameters[0] = null;
  3774. this._blendFunctionParameters[1] = null;
  3775. this._blendFunctionParameters[2] = null;
  3776. this._blendFunctionParameters[3] = null;
  3777. this._isAlphaBlendDirty = true;
  3778. this._isBlendFunctionParametersDirty = false;
  3779. };
  3780. _AlphaState.prototype.apply = function (gl) {
  3781. if (!this.isDirty) {
  3782. return;
  3783. }
  3784. // Alpha blend
  3785. if (this._isAlphaBlendDirty) {
  3786. if (this._alphaBlend) {
  3787. gl.enable(gl.BLEND);
  3788. }
  3789. else {
  3790. gl.disable(gl.BLEND);
  3791. }
  3792. this._isAlphaBlendDirty = false;
  3793. }
  3794. // Alpha function
  3795. if (this._isBlendFunctionParametersDirty) {
  3796. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  3797. this._isBlendFunctionParametersDirty = false;
  3798. }
  3799. };
  3800. return _AlphaState;
  3801. })();
  3802. BABYLON._AlphaState = _AlphaState;
  3803. var compileShader = function (gl, source, type, defines) {
  3804. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  3805. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  3806. gl.compileShader(shader);
  3807. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  3808. throw new Error(gl.getShaderInfoLog(shader));
  3809. }
  3810. return shader;
  3811. };
  3812. var getWebGLTextureType = function (gl, type) {
  3813. var textureType = gl.UNSIGNED_BYTE;
  3814. if (type === Engine.TEXTURETYPE_FLOAT)
  3815. textureType = gl.FLOAT;
  3816. return textureType;
  3817. };
  3818. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  3819. var magFilter = gl.NEAREST;
  3820. var minFilter = gl.NEAREST;
  3821. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  3822. magFilter = gl.LINEAR;
  3823. if (generateMipMaps) {
  3824. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  3825. }
  3826. else {
  3827. minFilter = gl.LINEAR;
  3828. }
  3829. }
  3830. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  3831. magFilter = gl.LINEAR;
  3832. if (generateMipMaps) {
  3833. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  3834. }
  3835. else {
  3836. minFilter = gl.LINEAR;
  3837. }
  3838. }
  3839. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  3840. magFilter = gl.NEAREST;
  3841. if (generateMipMaps) {
  3842. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  3843. }
  3844. else {
  3845. minFilter = gl.NEAREST;
  3846. }
  3847. }
  3848. return {
  3849. min: minFilter,
  3850. mag: magFilter
  3851. };
  3852. };
  3853. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  3854. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  3855. var engine = scene.getEngine();
  3856. var potWidth = BABYLON.Tools.GetExponantOfTwo(width, engine.getCaps().maxTextureSize);
  3857. var potHeight = BABYLON.Tools.GetExponantOfTwo(height, engine.getCaps().maxTextureSize);
  3858. gl.bindTexture(gl.TEXTURE_2D, texture);
  3859. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  3860. processFunction(potWidth, potHeight);
  3861. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  3862. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  3863. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  3864. if (!noMipmap && !isCompressed) {
  3865. gl.generateMipmap(gl.TEXTURE_2D);
  3866. }
  3867. gl.bindTexture(gl.TEXTURE_2D, null);
  3868. engine._activeTexturesCache = [];
  3869. texture._baseWidth = width;
  3870. texture._baseHeight = height;
  3871. texture._width = potWidth;
  3872. texture._height = potHeight;
  3873. texture.isReady = true;
  3874. texture.samplingMode = samplingMode;
  3875. scene._removePendingData(texture);
  3876. };
  3877. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  3878. var onload = function () {
  3879. loadedImages[index] = img;
  3880. loadedImages._internalCount++;
  3881. scene._removePendingData(img);
  3882. if (loadedImages._internalCount === 6) {
  3883. onfinish(loadedImages);
  3884. }
  3885. };
  3886. var onerror = function () {
  3887. scene._removePendingData(img);
  3888. };
  3889. var img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  3890. scene._addPendingData(img);
  3891. };
  3892. var cascadeLoad = function (rootUrl, scene, onfinish, extensions) {
  3893. var loadedImages = [];
  3894. loadedImages._internalCount = 0;
  3895. for (var index = 0; index < 6; index++) {
  3896. partialLoad(rootUrl + extensions[index], index, loadedImages, scene, onfinish);
  3897. }
  3898. };
  3899. var EngineCapabilities = (function () {
  3900. function EngineCapabilities() {
  3901. }
  3902. return EngineCapabilities;
  3903. })();
  3904. BABYLON.EngineCapabilities = EngineCapabilities;
  3905. /**
  3906. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  3907. */
  3908. var Engine = (function () {
  3909. /**
  3910. * @constructor
  3911. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  3912. * @param {boolean} [antialias] - enable antialias
  3913. * @param options - further options to be sent to the getContext function
  3914. */
  3915. function Engine(canvas, antialias, options) {
  3916. var _this = this;
  3917. // Public members
  3918. this.isFullscreen = false;
  3919. this.isPointerLock = false;
  3920. this.cullBackFaces = true;
  3921. this.renderEvenInBackground = true;
  3922. this.scenes = new Array();
  3923. this._windowIsBackground = false;
  3924. this._loadingDivBackgroundColor = "black";
  3925. this._drawCalls = 0;
  3926. this._renderingQueueLaunched = false;
  3927. this._activeRenderLoops = [];
  3928. // FPS
  3929. this.fpsRange = 60;
  3930. this.previousFramesDuration = [];
  3931. this.fps = 60;
  3932. this.deltaTime = 0;
  3933. // States
  3934. this._depthCullingState = new _DepthCullingState();
  3935. this._alphaState = new _AlphaState();
  3936. this._alphaMode = Engine.ALPHA_DISABLE;
  3937. // Cache
  3938. this._loadedTexturesCache = new Array();
  3939. this._activeTexturesCache = new Array();
  3940. this._compiledEffects = {};
  3941. this._uintIndicesCurrentlySet = false;
  3942. this._renderingCanvas = canvas;
  3943. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  3944. options = options || {};
  3945. options.antialias = antialias;
  3946. try {
  3947. this._gl = canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options);
  3948. }
  3949. catch (e) {
  3950. throw new Error("WebGL not supported");
  3951. }
  3952. if (!this._gl) {
  3953. throw new Error("WebGL not supported");
  3954. }
  3955. this._onBlur = function () {
  3956. _this._windowIsBackground = true;
  3957. };
  3958. this._onFocus = function () {
  3959. _this._windowIsBackground = false;
  3960. };
  3961. window.addEventListener("blur", this._onBlur);
  3962. window.addEventListener("focus", this._onFocus);
  3963. // Textures
  3964. this._workingCanvas = document.createElement("canvas");
  3965. this._workingContext = this._workingCanvas.getContext("2d");
  3966. // Viewport
  3967. this._hardwareScalingLevel = 1.0 / (window.devicePixelRatio || 1.0);
  3968. this.resize();
  3969. // Caps
  3970. this._caps = new EngineCapabilities();
  3971. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  3972. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  3973. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  3974. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  3975. // Infos
  3976. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  3977. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  3978. if (rendererInfo != null) {
  3979. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  3980. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  3981. }
  3982. if (!this._glVendor) {
  3983. this._glVendor = "Unknown vendor";
  3984. }
  3985. if (!this._glRenderer) {
  3986. this._glRenderer = "Unknown renderer";
  3987. }
  3988. // Extensions
  3989. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  3990. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  3991. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  3992. 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');
  3993. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  3994. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  3995. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  3996. // Depth buffer
  3997. this.setDepthBuffer(true);
  3998. this.setDepthFunctionToLessOrEqual();
  3999. this.setDepthWrite(true);
  4000. // Fullscreen
  4001. this._onFullscreenChange = function () {
  4002. if (document.fullscreen !== undefined) {
  4003. _this.isFullscreen = document.fullscreen;
  4004. }
  4005. else if (document.mozFullScreen !== undefined) {
  4006. _this.isFullscreen = document.mozFullScreen;
  4007. }
  4008. else if (document.webkitIsFullScreen !== undefined) {
  4009. _this.isFullscreen = document.webkitIsFullScreen;
  4010. }
  4011. else if (document.msIsFullScreen !== undefined) {
  4012. _this.isFullscreen = document.msIsFullScreen;
  4013. }
  4014. // Pointer lock
  4015. if (_this.isFullscreen && _this._pointerLockRequested) {
  4016. canvas.requestPointerLock = canvas.requestPointerLock || canvas.msRequestPointerLock || canvas.mozRequestPointerLock || canvas.webkitRequestPointerLock;
  4017. if (canvas.requestPointerLock) {
  4018. canvas.requestPointerLock();
  4019. }
  4020. }
  4021. };
  4022. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  4023. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  4024. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  4025. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  4026. // Pointer lock
  4027. this._onPointerLockChange = function () {
  4028. _this.isPointerLock = (document.mozPointerLockElement === canvas || document.webkitPointerLockElement === canvas || document.msPointerLockElement === canvas || document.pointerLockElement === canvas);
  4029. };
  4030. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  4031. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  4032. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  4033. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  4034. if (!Engine.audioEngine) {
  4035. Engine.audioEngine = new BABYLON.AudioEngine();
  4036. }
  4037. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  4038. }
  4039. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  4040. get: function () {
  4041. return Engine._ALPHA_DISABLE;
  4042. },
  4043. enumerable: true,
  4044. configurable: true
  4045. });
  4046. Object.defineProperty(Engine, "ALPHA_ADD", {
  4047. get: function () {
  4048. return Engine._ALPHA_ADD;
  4049. },
  4050. enumerable: true,
  4051. configurable: true
  4052. });
  4053. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  4054. get: function () {
  4055. return Engine._ALPHA_COMBINE;
  4056. },
  4057. enumerable: true,
  4058. configurable: true
  4059. });
  4060. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  4061. get: function () {
  4062. return Engine._DELAYLOADSTATE_NONE;
  4063. },
  4064. enumerable: true,
  4065. configurable: true
  4066. });
  4067. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  4068. get: function () {
  4069. return Engine._DELAYLOADSTATE_LOADED;
  4070. },
  4071. enumerable: true,
  4072. configurable: true
  4073. });
  4074. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  4075. get: function () {
  4076. return Engine._DELAYLOADSTATE_LOADING;
  4077. },
  4078. enumerable: true,
  4079. configurable: true
  4080. });
  4081. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  4082. get: function () {
  4083. return Engine._DELAYLOADSTATE_NOTLOADED;
  4084. },
  4085. enumerable: true,
  4086. configurable: true
  4087. });
  4088. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  4089. get: function () {
  4090. return Engine._TEXTUREFORMAT_ALPHA;
  4091. },
  4092. enumerable: true,
  4093. configurable: true
  4094. });
  4095. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  4096. get: function () {
  4097. return Engine._TEXTUREFORMAT_LUMINANCE;
  4098. },
  4099. enumerable: true,
  4100. configurable: true
  4101. });
  4102. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  4103. get: function () {
  4104. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  4105. },
  4106. enumerable: true,
  4107. configurable: true
  4108. });
  4109. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  4110. get: function () {
  4111. return Engine._TEXTUREFORMAT_RGB;
  4112. },
  4113. enumerable: true,
  4114. configurable: true
  4115. });
  4116. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  4117. get: function () {
  4118. return Engine._TEXTUREFORMAT_RGBA;
  4119. },
  4120. enumerable: true,
  4121. configurable: true
  4122. });
  4123. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  4124. get: function () {
  4125. return Engine._TEXTURETYPE_UNSIGNED_INT;
  4126. },
  4127. enumerable: true,
  4128. configurable: true
  4129. });
  4130. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  4131. get: function () {
  4132. return Engine._TEXTURETYPE_FLOAT;
  4133. },
  4134. enumerable: true,
  4135. configurable: true
  4136. });
  4137. Object.defineProperty(Engine, "Version", {
  4138. get: function () {
  4139. return "2.1.0 alpha";
  4140. },
  4141. enumerable: true,
  4142. configurable: true
  4143. });
  4144. Engine.prototype.getGlInfo = function () {
  4145. return {
  4146. vendor: this._glVendor,
  4147. renderer: this._glRenderer,
  4148. version: this._glVersion
  4149. };
  4150. };
  4151. Engine.prototype.getAspectRatio = function (camera) {
  4152. var viewport = camera.viewport;
  4153. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  4154. };
  4155. Engine.prototype.getRenderWidth = function () {
  4156. if (this._currentRenderTarget) {
  4157. return this._currentRenderTarget._width;
  4158. }
  4159. return this._renderingCanvas.width;
  4160. };
  4161. Engine.prototype.getRenderHeight = function () {
  4162. if (this._currentRenderTarget) {
  4163. return this._currentRenderTarget._height;
  4164. }
  4165. return this._renderingCanvas.height;
  4166. };
  4167. Engine.prototype.getRenderingCanvas = function () {
  4168. return this._renderingCanvas;
  4169. };
  4170. Engine.prototype.getRenderingCanvasClientRect = function () {
  4171. return this._renderingCanvas.getBoundingClientRect();
  4172. };
  4173. Engine.prototype.setHardwareScalingLevel = function (level) {
  4174. this._hardwareScalingLevel = level;
  4175. this.resize();
  4176. };
  4177. Engine.prototype.getHardwareScalingLevel = function () {
  4178. return this._hardwareScalingLevel;
  4179. };
  4180. Engine.prototype.getLoadedTexturesCache = function () {
  4181. return this._loadedTexturesCache;
  4182. };
  4183. Engine.prototype.getCaps = function () {
  4184. return this._caps;
  4185. };
  4186. Object.defineProperty(Engine.prototype, "drawCalls", {
  4187. get: function () {
  4188. return this._drawCalls;
  4189. },
  4190. enumerable: true,
  4191. configurable: true
  4192. });
  4193. // Methods
  4194. Engine.prototype.resetDrawCalls = function () {
  4195. this._drawCalls = 0;
  4196. };
  4197. Engine.prototype.setDepthFunctionToGreater = function () {
  4198. this._depthCullingState.depthFunc = this._gl.GREATER;
  4199. };
  4200. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  4201. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  4202. };
  4203. Engine.prototype.setDepthFunctionToLess = function () {
  4204. this._depthCullingState.depthFunc = this._gl.LESS;
  4205. };
  4206. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  4207. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  4208. };
  4209. /**
  4210. * stop executing a render loop function and remove it from the execution array
  4211. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  4212. */
  4213. Engine.prototype.stopRenderLoop = function (renderFunction) {
  4214. if (!renderFunction) {
  4215. this._activeRenderLoops = [];
  4216. return;
  4217. }
  4218. var index = this._activeRenderLoops.indexOf(renderFunction);
  4219. if (index >= 0) {
  4220. this._activeRenderLoops.splice(index, 1);
  4221. }
  4222. };
  4223. Engine.prototype._renderLoop = function () {
  4224. var _this = this;
  4225. var shouldRender = true;
  4226. if (!this.renderEvenInBackground && this._windowIsBackground) {
  4227. shouldRender = false;
  4228. }
  4229. if (shouldRender) {
  4230. // Start new frame
  4231. this.beginFrame();
  4232. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  4233. var renderFunction = this._activeRenderLoops[index];
  4234. renderFunction();
  4235. }
  4236. // Present
  4237. this.endFrame();
  4238. }
  4239. if (this._activeRenderLoops.length > 0) {
  4240. // Register new frame
  4241. BABYLON.Tools.QueueNewFrame(function () {
  4242. _this._renderLoop();
  4243. });
  4244. }
  4245. else {
  4246. this._renderingQueueLaunched = false;
  4247. }
  4248. };
  4249. /**
  4250. * Register and execute a render loop. The engine can have more than one render function.
  4251. * @param {Function} renderFunction - the function to continuesly execute starting the next render loop.
  4252. * @example
  4253. * engine.runRenderLoop(function () {
  4254. * scene.render()
  4255. * })
  4256. */
  4257. Engine.prototype.runRenderLoop = function (renderFunction) {
  4258. var _this = this;
  4259. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  4260. return;
  4261. }
  4262. this._activeRenderLoops.push(renderFunction);
  4263. if (!this._renderingQueueLaunched) {
  4264. this._renderingQueueLaunched = true;
  4265. BABYLON.Tools.QueueNewFrame(function () {
  4266. _this._renderLoop();
  4267. });
  4268. }
  4269. };
  4270. /**
  4271. * Toggle full screen mode.
  4272. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  4273. */
  4274. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  4275. if (this.isFullscreen) {
  4276. BABYLON.Tools.ExitFullscreen();
  4277. }
  4278. else {
  4279. this._pointerLockRequested = requestPointerLock;
  4280. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  4281. }
  4282. };
  4283. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  4284. this.applyStates();
  4285. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  4286. if (this._depthCullingState.depthMask) {
  4287. this._gl.clearDepth(1.0);
  4288. }
  4289. var mode = 0;
  4290. if (backBuffer)
  4291. mode |= this._gl.COLOR_BUFFER_BIT;
  4292. if (depthStencil && this._depthCullingState.depthMask)
  4293. mode |= this._gl.DEPTH_BUFFER_BIT;
  4294. this._gl.clear(mode);
  4295. };
  4296. /**
  4297. * Set the WebGL's viewport
  4298. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  4299. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  4300. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  4301. */
  4302. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  4303. var width = requiredWidth || this._renderingCanvas.width;
  4304. var height = requiredHeight || this._renderingCanvas.height;
  4305. var x = viewport.x || 0;
  4306. var y = viewport.y || 0;
  4307. this._cachedViewport = viewport;
  4308. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  4309. };
  4310. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  4311. this._cachedViewport = null;
  4312. this._gl.viewport(x, y, width, height);
  4313. };
  4314. Engine.prototype.beginFrame = function () {
  4315. this._measureFps();
  4316. };
  4317. Engine.prototype.endFrame = function () {
  4318. //this.flushFramebuffer();
  4319. };
  4320. /**
  4321. * resize the view according to the canvas' size.
  4322. * @example
  4323. * window.addEventListener("resize", function () {
  4324. * engine.resize();
  4325. * });
  4326. */
  4327. Engine.prototype.resize = function () {
  4328. this.setSize(this._renderingCanvas.clientWidth / this._hardwareScalingLevel, this._renderingCanvas.clientHeight / this._hardwareScalingLevel);
  4329. };
  4330. /**
  4331. * force a specific size of the canvas
  4332. * @param {number} width - the new canvas' width
  4333. * @param {number} height - the new canvas' height
  4334. */
  4335. Engine.prototype.setSize = function (width, height) {
  4336. this._renderingCanvas.width = width;
  4337. this._renderingCanvas.height = height;
  4338. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  4339. };
  4340. Engine.prototype.bindFramebuffer = function (texture) {
  4341. this._currentRenderTarget = texture;
  4342. var gl = this._gl;
  4343. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  4344. this._gl.viewport(0, 0, texture._width, texture._height);
  4345. this.wipeCaches();
  4346. };
  4347. Engine.prototype.unBindFramebuffer = function (texture) {
  4348. this._currentRenderTarget = null;
  4349. if (texture.generateMipMaps) {
  4350. var gl = this._gl;
  4351. gl.bindTexture(gl.TEXTURE_2D, texture);
  4352. gl.generateMipmap(gl.TEXTURE_2D);
  4353. gl.bindTexture(gl.TEXTURE_2D, null);
  4354. }
  4355. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  4356. };
  4357. Engine.prototype.flushFramebuffer = function () {
  4358. this._gl.flush();
  4359. };
  4360. Engine.prototype.restoreDefaultFramebuffer = function () {
  4361. this._currentRenderTarget = null;
  4362. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  4363. this.setViewport(this._cachedViewport);
  4364. this.wipeCaches();
  4365. };
  4366. // VBOs
  4367. Engine.prototype._resetVertexBufferBinding = function () {
  4368. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  4369. this._cachedVertexBuffers = null;
  4370. };
  4371. Engine.prototype.createVertexBuffer = function (vertices) {
  4372. var vbo = this._gl.createBuffer();
  4373. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  4374. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  4375. this._resetVertexBufferBinding();
  4376. vbo.references = 1;
  4377. return vbo;
  4378. };
  4379. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  4380. var vbo = this._gl.createBuffer();
  4381. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  4382. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  4383. this._resetVertexBufferBinding();
  4384. vbo.references = 1;
  4385. return vbo;
  4386. };
  4387. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  4388. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  4389. if (offset === undefined) {
  4390. offset = 0;
  4391. }
  4392. if (vertices instanceof Float32Array) {
  4393. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  4394. }
  4395. else {
  4396. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  4397. }
  4398. this._resetVertexBufferBinding();
  4399. };
  4400. Engine.prototype._resetIndexBufferBinding = function () {
  4401. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  4402. this._cachedIndexBuffer = null;
  4403. };
  4404. Engine.prototype.createIndexBuffer = function (indices) {
  4405. var vbo = this._gl.createBuffer();
  4406. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  4407. // Check for 32 bits indices
  4408. var arrayBuffer;
  4409. var need32Bits = false;
  4410. if (this._caps.uintIndices) {
  4411. for (var index = 0; index < indices.length; index++) {
  4412. if (indices[index] > 65535) {
  4413. need32Bits = true;
  4414. break;
  4415. }
  4416. }
  4417. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  4418. }
  4419. else {
  4420. arrayBuffer = new Uint16Array(indices);
  4421. }
  4422. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  4423. this._resetIndexBufferBinding();
  4424. vbo.references = 1;
  4425. vbo.is32Bits = need32Bits;
  4426. return vbo;
  4427. };
  4428. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  4429. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  4430. this._cachedVertexBuffers = vertexBuffer;
  4431. this._cachedEffectForVertexBuffers = effect;
  4432. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  4433. var offset = 0;
  4434. for (var index = 0; index < vertexDeclaration.length; index++) {
  4435. var order = effect.getAttributeLocation(index);
  4436. if (order >= 0) {
  4437. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  4438. }
  4439. offset += vertexDeclaration[index] * 4;
  4440. }
  4441. }
  4442. if (this._cachedIndexBuffer !== indexBuffer) {
  4443. this._cachedIndexBuffer = indexBuffer;
  4444. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  4445. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  4446. }
  4447. };
  4448. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  4449. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  4450. this._cachedVertexBuffers = vertexBuffers;
  4451. this._cachedEffectForVertexBuffers = effect;
  4452. var attributes = effect.getAttributesNames();
  4453. for (var index = 0; index < attributes.length; index++) {
  4454. var order = effect.getAttributeLocation(index);
  4455. if (order >= 0) {
  4456. var vertexBuffer = vertexBuffers[attributes[index]];
  4457. if (!vertexBuffer) {
  4458. continue;
  4459. }
  4460. var stride = vertexBuffer.getStrideSize();
  4461. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  4462. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  4463. }
  4464. }
  4465. }
  4466. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  4467. this._cachedIndexBuffer = indexBuffer;
  4468. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  4469. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  4470. }
  4471. };
  4472. Engine.prototype._releaseBuffer = function (buffer) {
  4473. buffer.references--;
  4474. if (buffer.references === 0) {
  4475. this._gl.deleteBuffer(buffer);
  4476. return true;
  4477. }
  4478. return false;
  4479. };
  4480. Engine.prototype.createInstancesBuffer = function (capacity) {
  4481. var buffer = this._gl.createBuffer();
  4482. buffer.capacity = capacity;
  4483. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  4484. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  4485. return buffer;
  4486. };
  4487. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  4488. this._gl.deleteBuffer(buffer);
  4489. };
  4490. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  4491. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  4492. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  4493. for (var index = 0; index < 4; index++) {
  4494. var offsetLocation = offsetLocations[index];
  4495. this._gl.enableVertexAttribArray(offsetLocation);
  4496. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  4497. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  4498. }
  4499. };
  4500. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  4501. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  4502. for (var index = 0; index < 4; index++) {
  4503. var offsetLocation = offsetLocations[index];
  4504. this._gl.disableVertexAttribArray(offsetLocation);
  4505. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  4506. }
  4507. };
  4508. Engine.prototype.applyStates = function () {
  4509. this._depthCullingState.apply(this._gl);
  4510. this._alphaState.apply(this._gl);
  4511. };
  4512. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  4513. // Apply states
  4514. this.applyStates();
  4515. this._drawCalls++;
  4516. // Render
  4517. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  4518. if (instancesCount) {
  4519. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2, instancesCount);
  4520. return;
  4521. }
  4522. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2);
  4523. };
  4524. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  4525. // Apply states
  4526. this.applyStates();
  4527. this._drawCalls++;
  4528. if (instancesCount) {
  4529. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  4530. return;
  4531. }
  4532. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  4533. };
  4534. // Shaders
  4535. Engine.prototype._releaseEffect = function (effect) {
  4536. if (this._compiledEffects[effect._key]) {
  4537. delete this._compiledEffects[effect._key];
  4538. if (effect.getProgram()) {
  4539. this._gl.deleteProgram(effect.getProgram());
  4540. }
  4541. }
  4542. };
  4543. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  4544. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  4545. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  4546. var name = vertex + "+" + fragment + "@" + defines;
  4547. if (this._compiledEffects[name]) {
  4548. return this._compiledEffects[name];
  4549. }
  4550. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  4551. effect._key = name;
  4552. this._compiledEffects[name] = effect;
  4553. return effect;
  4554. };
  4555. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  4556. if (uniformsNames === void 0) { uniformsNames = []; }
  4557. if (samplers === void 0) { samplers = []; }
  4558. if (defines === void 0) { defines = ""; }
  4559. return this.createEffect({
  4560. vertex: "particles",
  4561. fragmentElement: fragmentName
  4562. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  4563. };
  4564. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  4565. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  4566. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  4567. var shaderProgram = this._gl.createProgram();
  4568. this._gl.attachShader(shaderProgram, vertexShader);
  4569. this._gl.attachShader(shaderProgram, fragmentShader);
  4570. this._gl.linkProgram(shaderProgram);
  4571. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  4572. if (!linked) {
  4573. var error = this._gl.getProgramInfoLog(shaderProgram);
  4574. if (error) {
  4575. throw new Error(error);
  4576. }
  4577. }
  4578. this._gl.deleteShader(vertexShader);
  4579. this._gl.deleteShader(fragmentShader);
  4580. return shaderProgram;
  4581. };
  4582. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  4583. var results = [];
  4584. for (var index = 0; index < uniformsNames.length; index++) {
  4585. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  4586. }
  4587. return results;
  4588. };
  4589. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  4590. var results = [];
  4591. for (var index = 0; index < attributesNames.length; index++) {
  4592. try {
  4593. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  4594. }
  4595. catch (e) {
  4596. results.push(-1);
  4597. }
  4598. }
  4599. return results;
  4600. };
  4601. Engine.prototype.enableEffect = function (effect) {
  4602. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  4603. if (effect && effect.onBind) {
  4604. effect.onBind(effect);
  4605. }
  4606. return;
  4607. }
  4608. this._vertexAttribArrays = this._vertexAttribArrays || [];
  4609. // Use program
  4610. this._gl.useProgram(effect.getProgram());
  4611. for (var i in this._vertexAttribArrays) {
  4612. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  4613. continue;
  4614. }
  4615. this._vertexAttribArrays[i] = false;
  4616. this._gl.disableVertexAttribArray(i);
  4617. }
  4618. var attributesCount = effect.getAttributesCount();
  4619. for (var index = 0; index < attributesCount; index++) {
  4620. // Attributes
  4621. var order = effect.getAttributeLocation(index);
  4622. if (order >= 0) {
  4623. this._vertexAttribArrays[order] = true;
  4624. this._gl.enableVertexAttribArray(order);
  4625. }
  4626. }
  4627. this._currentEffect = effect;
  4628. if (effect.onBind) {
  4629. effect.onBind(effect);
  4630. }
  4631. };
  4632. Engine.prototype.setArray = function (uniform, array) {
  4633. if (!uniform)
  4634. return;
  4635. this._gl.uniform1fv(uniform, array);
  4636. };
  4637. Engine.prototype.setArray2 = function (uniform, array) {
  4638. if (!uniform || array.length % 2 !== 0)
  4639. return;
  4640. this._gl.uniform2fv(uniform, array);
  4641. };
  4642. Engine.prototype.setArray3 = function (uniform, array) {
  4643. if (!uniform || array.length % 3 !== 0)
  4644. return;
  4645. this._gl.uniform3fv(uniform, array);
  4646. };
  4647. Engine.prototype.setArray4 = function (uniform, array) {
  4648. if (!uniform || array.length % 4 !== 0)
  4649. return;
  4650. this._gl.uniform4fv(uniform, array);
  4651. };
  4652. Engine.prototype.setMatrices = function (uniform, matrices) {
  4653. if (!uniform)
  4654. return;
  4655. this._gl.uniformMatrix4fv(uniform, false, matrices);
  4656. };
  4657. Engine.prototype.setMatrix = function (uniform, matrix) {
  4658. if (!uniform)
  4659. return;
  4660. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  4661. };
  4662. Engine.prototype.setFloat = function (uniform, value) {
  4663. if (!uniform)
  4664. return;
  4665. this._gl.uniform1f(uniform, value);
  4666. };
  4667. Engine.prototype.setFloat2 = function (uniform, x, y) {
  4668. if (!uniform)
  4669. return;
  4670. this._gl.uniform2f(uniform, x, y);
  4671. };
  4672. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  4673. if (!uniform)
  4674. return;
  4675. this._gl.uniform3f(uniform, x, y, z);
  4676. };
  4677. Engine.prototype.setBool = function (uniform, bool) {
  4678. if (!uniform)
  4679. return;
  4680. this._gl.uniform1i(uniform, bool);
  4681. };
  4682. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  4683. if (!uniform)
  4684. return;
  4685. this._gl.uniform4f(uniform, x, y, z, w);
  4686. };
  4687. Engine.prototype.setColor3 = function (uniform, color3) {
  4688. if (!uniform)
  4689. return;
  4690. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  4691. };
  4692. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  4693. if (!uniform)
  4694. return;
  4695. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  4696. };
  4697. // States
  4698. Engine.prototype.setState = function (culling, force) {
  4699. // Culling
  4700. if (this._depthCullingState.cull !== culling || force) {
  4701. if (culling) {
  4702. this._depthCullingState.cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  4703. this._depthCullingState.cull = true;
  4704. }
  4705. else {
  4706. this._depthCullingState.cull = false;
  4707. }
  4708. }
  4709. };
  4710. Engine.prototype.setDepthBuffer = function (enable) {
  4711. this._depthCullingState.depthTest = enable;
  4712. };
  4713. Engine.prototype.getDepthWrite = function () {
  4714. return this._depthCullingState.depthMask;
  4715. };
  4716. Engine.prototype.setDepthWrite = function (enable) {
  4717. this._depthCullingState.depthMask = enable;
  4718. };
  4719. Engine.prototype.setColorWrite = function (enable) {
  4720. this._gl.colorMask(enable, enable, enable, enable);
  4721. };
  4722. Engine.prototype.setAlphaMode = function (mode) {
  4723. switch (mode) {
  4724. case Engine.ALPHA_DISABLE:
  4725. this.setDepthWrite(true);
  4726. this._alphaState.alphaBlend = false;
  4727. break;
  4728. case Engine.ALPHA_COMBINE:
  4729. this.setDepthWrite(false);
  4730. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  4731. this._alphaState.alphaBlend = true;
  4732. break;
  4733. case Engine.ALPHA_ADD:
  4734. this.setDepthWrite(false);
  4735. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  4736. this._alphaState.alphaBlend = true;
  4737. break;
  4738. }
  4739. this._alphaMode = mode;
  4740. };
  4741. Engine.prototype.getAlphaMode = function () {
  4742. return this._alphaMode;
  4743. };
  4744. Engine.prototype.setAlphaTesting = function (enable) {
  4745. this._alphaTest = enable;
  4746. };
  4747. Engine.prototype.getAlphaTesting = function () {
  4748. return this._alphaTest;
  4749. };
  4750. // Textures
  4751. Engine.prototype.wipeCaches = function () {
  4752. this._activeTexturesCache = [];
  4753. this._currentEffect = null;
  4754. this._depthCullingState.reset();
  4755. this._alphaState.reset();
  4756. this._cachedVertexBuffers = null;
  4757. this._cachedIndexBuffer = null;
  4758. this._cachedEffectForVertexBuffers = null;
  4759. };
  4760. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  4761. var gl = this._gl;
  4762. gl.bindTexture(gl.TEXTURE_2D, texture);
  4763. var magFilter = gl.NEAREST;
  4764. var minFilter = gl.NEAREST;
  4765. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  4766. magFilter = gl.LINEAR;
  4767. minFilter = gl.LINEAR;
  4768. }
  4769. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  4770. magFilter = gl.LINEAR;
  4771. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  4772. }
  4773. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  4774. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  4775. gl.bindTexture(gl.TEXTURE_2D, null);
  4776. texture.samplingMode = samplingMode;
  4777. };
  4778. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  4779. var _this = this;
  4780. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  4781. if (onLoad === void 0) { onLoad = null; }
  4782. if (onError === void 0) { onError = null; }
  4783. if (buffer === void 0) { buffer = null; }
  4784. var texture = this._gl.createTexture();
  4785. var extension;
  4786. var fromData = false;
  4787. if (url.substr(0, 5) === "data:") {
  4788. fromData = true;
  4789. }
  4790. if (!fromData)
  4791. extension = url.substr(url.length - 4, 4).toLowerCase();
  4792. else {
  4793. var oldUrl = url;
  4794. fromData = oldUrl.split(':');
  4795. url = oldUrl;
  4796. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  4797. }
  4798. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  4799. var isTGA = (extension === ".tga");
  4800. scene._addPendingData(texture);
  4801. texture.url = url;
  4802. texture.noMipmap = noMipmap;
  4803. texture.references = 1;
  4804. this._loadedTexturesCache.push(texture);
  4805. var onerror = function () {
  4806. scene._removePendingData(texture);
  4807. if (onError) {
  4808. onError();
  4809. }
  4810. };
  4811. if (isTGA) {
  4812. var callback = function (arrayBuffer) {
  4813. var data = new Uint8Array(arrayBuffer);
  4814. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  4815. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  4816. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  4817. if (onLoad) {
  4818. onLoad();
  4819. }
  4820. }, samplingMode);
  4821. };
  4822. if (!(fromData instanceof Array))
  4823. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  4824. callback(arrayBuffer);
  4825. }, onerror, scene.database, true);
  4826. else
  4827. callback(buffer);
  4828. }
  4829. else if (isDDS) {
  4830. callback = function (data) {
  4831. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  4832. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  4833. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  4834. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  4835. if (onLoad) {
  4836. onLoad();
  4837. }
  4838. }, samplingMode);
  4839. };
  4840. if (!(fromData instanceof Array))
  4841. BABYLON.Tools.LoadFile(url, function (data) {
  4842. callback(data);
  4843. }, onerror, scene.database, true);
  4844. else
  4845. callback(buffer);
  4846. }
  4847. else {
  4848. var onload = function (img) {
  4849. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  4850. var isPot = (img.width === potWidth && img.height === potHeight);
  4851. if (!isPot) {
  4852. _this._workingCanvas.width = potWidth;
  4853. _this._workingCanvas.height = potHeight;
  4854. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  4855. _this._workingContext.imageSmoothingEnabled = false;
  4856. _this._workingContext.mozImageSmoothingEnabled = false;
  4857. _this._workingContext.oImageSmoothingEnabled = false;
  4858. _this._workingContext.webkitImageSmoothingEnabled = false;
  4859. _this._workingContext.msImageSmoothingEnabled = false;
  4860. }
  4861. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  4862. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  4863. _this._workingContext.imageSmoothingEnabled = true;
  4864. _this._workingContext.mozImageSmoothingEnabled = true;
  4865. _this._workingContext.oImageSmoothingEnabled = true;
  4866. _this._workingContext.webkitImageSmoothingEnabled = true;
  4867. _this._workingContext.msImageSmoothingEnabled = true;
  4868. }
  4869. }
  4870. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  4871. if (onLoad) {
  4872. onLoad();
  4873. }
  4874. }, samplingMode);
  4875. };
  4876. if (!(fromData instanceof Array))
  4877. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  4878. else
  4879. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  4880. }
  4881. return texture;
  4882. };
  4883. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode) {
  4884. var texture = this._gl.createTexture();
  4885. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4886. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  4887. // Format
  4888. var internalFormat = this._gl.RGBA;
  4889. switch (format) {
  4890. case Engine.TEXTUREFORMAT_ALPHA:
  4891. internalFormat = this._gl.ALPHA;
  4892. break;
  4893. case Engine.TEXTUREFORMAT_LUMINANCE:
  4894. internalFormat = this._gl.LUMINANCE;
  4895. break;
  4896. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  4897. internalFormat = this._gl.LUMINANCE_ALPHA;
  4898. break;
  4899. case Engine.TEXTUREFORMAT_RGB:
  4900. internalFormat = this._gl.RGB;
  4901. break;
  4902. case Engine.TEXTUREFORMAT_RGBA:
  4903. internalFormat = this._gl.RGBA;
  4904. break;
  4905. }
  4906. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, width, height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  4907. if (generateMipMaps) {
  4908. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4909. }
  4910. // Filters
  4911. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  4912. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  4913. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  4914. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4915. this._activeTexturesCache = [];
  4916. texture._baseWidth = width;
  4917. texture._baseHeight = height;
  4918. texture._width = width;
  4919. texture._height = height;
  4920. texture.isReady = true;
  4921. texture.references = 1;
  4922. texture.samplingMode = samplingMode;
  4923. this._loadedTexturesCache.push(texture);
  4924. return texture;
  4925. };
  4926. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  4927. var texture = this._gl.createTexture();
  4928. width = BABYLON.Tools.GetExponantOfTwo(width, this._caps.maxTextureSize);
  4929. height = BABYLON.Tools.GetExponantOfTwo(height, this._caps.maxTextureSize);
  4930. this._activeTexturesCache = [];
  4931. texture._baseWidth = width;
  4932. texture._baseHeight = height;
  4933. texture._width = width;
  4934. texture._height = height;
  4935. texture.isReady = false;
  4936. texture.generateMipMaps = generateMipMaps;
  4937. texture.references = 1;
  4938. texture.samplingMode = samplingMode;
  4939. this.updateTextureSamplingMode(samplingMode, texture);
  4940. this._loadedTexturesCache.push(texture);
  4941. return texture;
  4942. };
  4943. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  4944. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  4945. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4946. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  4947. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  4948. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4949. };
  4950. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  4951. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4952. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  4953. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  4954. if (texture.generateMipMaps) {
  4955. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4956. }
  4957. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4958. this._activeTexturesCache = [];
  4959. texture.isReady = true;
  4960. };
  4961. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  4962. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4963. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  4964. // Scale the video if it is a NPOT using the current working canvas
  4965. if (video.videoWidth !== texture._width || video.videoHeight !== texture._height) {
  4966. if (!texture._workingCanvas) {
  4967. texture._workingCanvas = document.createElement("canvas");
  4968. texture._workingContext = texture._workingCanvas.getContext("2d");
  4969. texture._workingCanvas.width = texture._width;
  4970. texture._workingCanvas.height = texture._height;
  4971. }
  4972. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  4973. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  4974. }
  4975. else {
  4976. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  4977. }
  4978. if (texture.generateMipMaps) {
  4979. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4980. }
  4981. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4982. this._activeTexturesCache = [];
  4983. texture.isReady = true;
  4984. };
  4985. Engine.prototype.createRenderTargetTexture = function (size, options) {
  4986. // old version had a "generateMipMaps" arg instead of options.
  4987. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  4988. // in the same way, generateDepthBuffer is defaulted to true
  4989. var generateMipMaps = false;
  4990. var generateDepthBuffer = true;
  4991. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  4992. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  4993. if (options !== undefined) {
  4994. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipmaps;
  4995. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  4996. type = options.type === undefined ? type : options.type;
  4997. if (options.samplingMode !== undefined) {
  4998. samplingMode = options.samplingMode;
  4999. }
  5000. if (type === Engine.TEXTURETYPE_FLOAT) {
  5001. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  5002. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  5003. }
  5004. }
  5005. var gl = this._gl;
  5006. var texture = gl.createTexture();
  5007. gl.bindTexture(gl.TEXTURE_2D, texture);
  5008. var width = size.width || size;
  5009. var height = size.height || size;
  5010. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  5011. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  5012. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  5013. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  5014. }
  5015. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  5016. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  5017. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  5018. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  5019. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  5020. var depthBuffer;
  5021. // Create the depth buffer
  5022. if (generateDepthBuffer) {
  5023. depthBuffer = gl.createRenderbuffer();
  5024. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  5025. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  5026. }
  5027. // Create the framebuffer
  5028. var framebuffer = gl.createFramebuffer();
  5029. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  5030. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  5031. if (generateDepthBuffer) {
  5032. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  5033. }
  5034. // Unbind
  5035. gl.bindTexture(gl.TEXTURE_2D, null);
  5036. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  5037. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  5038. texture._framebuffer = framebuffer;
  5039. if (generateDepthBuffer) {
  5040. texture._depthBuffer = depthBuffer;
  5041. }
  5042. texture._width = width;
  5043. texture._height = height;
  5044. texture.isReady = true;
  5045. texture.generateMipMaps = generateMipMaps;
  5046. texture.references = 1;
  5047. texture.samplingMode = samplingMode;
  5048. this._activeTexturesCache = [];
  5049. this._loadedTexturesCache.push(texture);
  5050. return texture;
  5051. };
  5052. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  5053. var _this = this;
  5054. var gl = this._gl;
  5055. var texture = gl.createTexture();
  5056. texture.isCube = true;
  5057. texture.url = rootUrl;
  5058. texture.references = 1;
  5059. this._loadedTexturesCache.push(texture);
  5060. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  5061. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  5062. if (isDDS) {
  5063. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  5064. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  5065. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  5066. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  5067. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  5068. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  5069. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  5070. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  5071. }
  5072. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  5073. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  5074. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  5075. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  5076. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  5077. _this._activeTexturesCache = [];
  5078. texture._width = info.width;
  5079. texture._height = info.height;
  5080. texture.isReady = true;
  5081. }, null, null, true);
  5082. }
  5083. else {
  5084. cascadeLoad(rootUrl, scene, function (imgs) {
  5085. var width = BABYLON.Tools.GetExponantOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  5086. var height = width;
  5087. _this._workingCanvas.width = width;
  5088. _this._workingCanvas.height = height;
  5089. var faces = [
  5090. gl.TEXTURE_CUBE_MAP_POSITIVE_X,
  5091. gl.TEXTURE_CUBE_MAP_POSITIVE_Y,
  5092. gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  5093. gl.TEXTURE_CUBE_MAP_NEGATIVE_X,
  5094. gl.TEXTURE_CUBE_MAP_NEGATIVE_Y,
  5095. gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  5096. ];
  5097. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  5098. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  5099. for (var index = 0; index < faces.length; index++) {
  5100. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  5101. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  5102. }
  5103. if (!noMipmap) {
  5104. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  5105. }
  5106. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  5107. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  5108. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  5109. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  5110. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  5111. _this._activeTexturesCache = [];
  5112. texture._width = width;
  5113. texture._height = height;
  5114. texture.isReady = true;
  5115. }, extensions);
  5116. }
  5117. return texture;
  5118. };
  5119. Engine.prototype._releaseTexture = function (texture) {
  5120. var gl = this._gl;
  5121. if (texture._framebuffer) {
  5122. gl.deleteFramebuffer(texture._framebuffer);
  5123. }
  5124. if (texture._depthBuffer) {
  5125. gl.deleteRenderbuffer(texture._depthBuffer);
  5126. }
  5127. gl.deleteTexture(texture);
  5128. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  5129. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  5130. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  5131. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  5132. this._activeTexturesCache[channel] = null;
  5133. }
  5134. var index = this._loadedTexturesCache.indexOf(texture);
  5135. if (index !== -1) {
  5136. this._loadedTexturesCache.splice(index, 1);
  5137. }
  5138. };
  5139. Engine.prototype.bindSamplers = function (effect) {
  5140. this._gl.useProgram(effect.getProgram());
  5141. var samplers = effect.getSamplers();
  5142. for (var index = 0; index < samplers.length; index++) {
  5143. var uniform = effect.getUniform(samplers[index]);
  5144. this._gl.uniform1i(uniform, index);
  5145. }
  5146. this._currentEffect = null;
  5147. };
  5148. Engine.prototype._bindTexture = function (channel, texture) {
  5149. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  5150. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  5151. this._activeTexturesCache[channel] = null;
  5152. };
  5153. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  5154. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  5155. };
  5156. Engine.prototype.setTexture = function (channel, texture) {
  5157. if (channel < 0) {
  5158. return;
  5159. }
  5160. // Not ready?
  5161. if (!texture || !texture.isReady()) {
  5162. if (this._activeTexturesCache[channel] != null) {
  5163. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  5164. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  5165. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  5166. this._activeTexturesCache[channel] = null;
  5167. }
  5168. return;
  5169. }
  5170. // Video
  5171. if (texture instanceof BABYLON.VideoTexture) {
  5172. if (texture.update()) {
  5173. this._activeTexturesCache[channel] = null;
  5174. }
  5175. }
  5176. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  5177. texture.delayLoad();
  5178. return;
  5179. }
  5180. if (this._activeTexturesCache[channel] === texture) {
  5181. return;
  5182. }
  5183. this._activeTexturesCache[channel] = texture;
  5184. var internalTexture = texture.getInternalTexture();
  5185. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  5186. if (internalTexture.isCube) {
  5187. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  5188. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  5189. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  5190. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  5191. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  5192. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  5193. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  5194. }
  5195. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  5196. }
  5197. else {
  5198. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  5199. if (internalTexture._cachedWrapU !== texture.wrapU) {
  5200. internalTexture._cachedWrapU = texture.wrapU;
  5201. switch (texture.wrapU) {
  5202. case BABYLON.Texture.WRAP_ADDRESSMODE:
  5203. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  5204. break;
  5205. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  5206. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  5207. break;
  5208. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  5209. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  5210. break;
  5211. }
  5212. }
  5213. if (internalTexture._cachedWrapV !== texture.wrapV) {
  5214. internalTexture._cachedWrapV = texture.wrapV;
  5215. switch (texture.wrapV) {
  5216. case BABYLON.Texture.WRAP_ADDRESSMODE:
  5217. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  5218. break;
  5219. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  5220. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  5221. break;
  5222. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  5223. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  5224. break;
  5225. }
  5226. }
  5227. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  5228. }
  5229. };
  5230. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  5231. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  5232. var value = texture.anisotropicFilteringLevel;
  5233. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  5234. value = 1;
  5235. }
  5236. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  5237. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  5238. texture._cachedAnisotropicFilteringLevel = value;
  5239. }
  5240. };
  5241. Engine.prototype.readPixels = function (x, y, width, height) {
  5242. var data = new Uint8Array(height * width * 4);
  5243. this._gl.readPixels(0, 0, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  5244. return data;
  5245. };
  5246. // Dispose
  5247. Engine.prototype.dispose = function () {
  5248. this.hideLoadingUI();
  5249. this.stopRenderLoop();
  5250. while (this.scenes.length) {
  5251. this.scenes[0].dispose();
  5252. }
  5253. // Release audio engine
  5254. Engine.audioEngine.dispose();
  5255. for (var name in this._compiledEffects) {
  5256. this._gl.deleteProgram(this._compiledEffects[name]._program);
  5257. }
  5258. for (var i in this._vertexAttribArrays) {
  5259. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  5260. continue;
  5261. }
  5262. this._gl.disableVertexAttribArray(i);
  5263. }
  5264. // Events
  5265. window.removeEventListener("blur", this._onBlur);
  5266. window.removeEventListener("focus", this._onFocus);
  5267. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  5268. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  5269. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  5270. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  5271. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  5272. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  5273. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  5274. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  5275. };
  5276. // Loading screen
  5277. Engine.prototype.displayLoadingUI = function () {
  5278. var _this = this;
  5279. this._loadingDiv = document.createElement("div");
  5280. this._loadingDiv.style.opacity = "0";
  5281. this._loadingDiv.style.transition = "opacity 1.5s ease";
  5282. // Loading text
  5283. this._loadingTextDiv = document.createElement("div");
  5284. this._loadingTextDiv.style.position = "absolute";
  5285. this._loadingTextDiv.style.left = "0";
  5286. this._loadingTextDiv.style.top = "50%";
  5287. this._loadingTextDiv.style.marginTop = "80px";
  5288. this._loadingTextDiv.style.width = "100%";
  5289. this._loadingTextDiv.style.height = "20px";
  5290. this._loadingTextDiv.style.fontFamily = "Arial";
  5291. this._loadingTextDiv.style.fontSize = "14px";
  5292. this._loadingTextDiv.style.color = "white";
  5293. this._loadingTextDiv.style.textAlign = "center";
  5294. this._loadingTextDiv.innerHTML = "Loading";
  5295. this._loadingDiv.appendChild(this._loadingTextDiv);
  5296. // Loading img
  5297. var imgBack = new Image();
  5298. 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==";
  5299. imgBack.style.position = "absolute";
  5300. imgBack.style.left = "50%";
  5301. imgBack.style.top = "50%";
  5302. imgBack.style.marginLeft = "-50px";
  5303. imgBack.style.marginTop = "-50px";
  5304. imgBack.style.transition = "transform 1.0s ease";
  5305. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  5306. var deg = 360;
  5307. var onTransitionEnd = function () {
  5308. deg += 360;
  5309. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  5310. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  5311. };
  5312. imgBack.addEventListener("transitionend", onTransitionEnd);
  5313. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  5314. this._loadingDiv.appendChild(imgBack);
  5315. // front image
  5316. var imgFront = new Image();
  5317. 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=";
  5318. imgFront.style.position = "absolute";
  5319. imgFront.style.left = "50%";
  5320. imgFront.style.top = "50%";
  5321. imgFront.style.marginLeft = "-50px";
  5322. imgFront.style.marginTop = "-50px";
  5323. this._loadingDiv.appendChild(imgFront);
  5324. // Resize
  5325. this._resizeLoadingUI = function () {
  5326. var canvasRect = _this.getRenderingCanvasClientRect();
  5327. _this._loadingDiv.style.position = "absolute";
  5328. _this._loadingDiv.style.left = canvasRect.left + "px";
  5329. _this._loadingDiv.style.top = canvasRect.top + "px";
  5330. _this._loadingDiv.style.width = canvasRect.width + "px";
  5331. _this._loadingDiv.style.height = canvasRect.height + "px";
  5332. };
  5333. this._resizeLoadingUI();
  5334. window.addEventListener("resize", this._resizeLoadingUI);
  5335. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  5336. document.body.appendChild(this._loadingDiv);
  5337. setTimeout(function () {
  5338. _this._loadingDiv.style.opacity = "1";
  5339. imgBack.style.transform = "rotateZ(360deg)";
  5340. imgBack.style.webkitTransform = "rotateZ(360deg)";
  5341. }, 0);
  5342. };
  5343. Object.defineProperty(Engine.prototype, "loadingUIText", {
  5344. set: function (text) {
  5345. if (!this._loadingDiv) {
  5346. return;
  5347. }
  5348. this._loadingTextDiv.innerHTML = text;
  5349. },
  5350. enumerable: true,
  5351. configurable: true
  5352. });
  5353. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  5354. get: function () {
  5355. return this._loadingDivBackgroundColor;
  5356. },
  5357. set: function (color) {
  5358. this._loadingDivBackgroundColor = color;
  5359. if (!this._loadingDiv) {
  5360. return;
  5361. }
  5362. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  5363. },
  5364. enumerable: true,
  5365. configurable: true
  5366. });
  5367. Engine.prototype.hideLoadingUI = function () {
  5368. var _this = this;
  5369. if (!this._loadingDiv) {
  5370. return;
  5371. }
  5372. var onTransitionEnd = function () {
  5373. if (!_this._loadingDiv) {
  5374. return;
  5375. }
  5376. document.body.removeChild(_this._loadingDiv);
  5377. window.removeEventListener("resize", _this._resizeLoadingUI);
  5378. _this._loadingDiv = null;
  5379. };
  5380. this._loadingDiv.style.opacity = "0";
  5381. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  5382. };
  5383. // FPS
  5384. Engine.prototype.getFps = function () {
  5385. return this.fps;
  5386. };
  5387. Engine.prototype.getDeltaTime = function () {
  5388. return this.deltaTime;
  5389. };
  5390. Engine.prototype._measureFps = function () {
  5391. this.previousFramesDuration.push(BABYLON.Tools.Now);
  5392. var length = this.previousFramesDuration.length;
  5393. if (length >= 2) {
  5394. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  5395. }
  5396. if (length >= this.fpsRange) {
  5397. if (length > this.fpsRange) {
  5398. this.previousFramesDuration.splice(0, 1);
  5399. length = this.previousFramesDuration.length;
  5400. }
  5401. var sum = 0;
  5402. for (var id = 0; id < length - 1; id++) {
  5403. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  5404. }
  5405. this.fps = 1000.0 / (sum / (length - 1));
  5406. }
  5407. };
  5408. // Statics
  5409. Engine.isSupported = function () {
  5410. try {
  5411. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  5412. if (navigator.isCocoonJS) {
  5413. return true;
  5414. }
  5415. var tempcanvas = document.createElement("canvas");
  5416. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  5417. return gl != null && !!window.WebGLRenderingContext;
  5418. }
  5419. catch (e) {
  5420. return false;
  5421. }
  5422. };
  5423. // Const statics
  5424. Engine._ALPHA_DISABLE = 0;
  5425. Engine._ALPHA_ADD = 1;
  5426. Engine._ALPHA_COMBINE = 2;
  5427. Engine._DELAYLOADSTATE_NONE = 0;
  5428. Engine._DELAYLOADSTATE_LOADED = 1;
  5429. Engine._DELAYLOADSTATE_LOADING = 2;
  5430. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  5431. Engine._TEXTUREFORMAT_ALPHA = 0;
  5432. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  5433. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  5434. Engine._TEXTUREFORMAT_RGB = 4;
  5435. Engine._TEXTUREFORMAT_RGBA = 4;
  5436. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  5437. Engine._TEXTURETYPE_FLOAT = 1;
  5438. // Updatable statics so stick with vars here
  5439. Engine.Epsilon = 0.001;
  5440. Engine.CollisionsEpsilon = 0.001;
  5441. Engine.ShadersRepository = "Babylon/Shaders/";
  5442. return Engine;
  5443. })();
  5444. BABYLON.Engine = Engine;
  5445. })(BABYLON || (BABYLON = {}));
  5446. //# sourceMappingURL=babylon.engine.js.mapvar BABYLON;
  5447. (function (BABYLON) {
  5448. /**
  5449. * Node is the basic class for all scene objects (Mesh, Light Camera).
  5450. */
  5451. var Node = (function () {
  5452. /**
  5453. * @constructor
  5454. * @param {string} name - the name and id to be given to this node
  5455. * @param {BABYLON.Scene} the scene this node will be added to
  5456. */
  5457. function Node(name, scene) {
  5458. this.state = "";
  5459. this.animations = new Array();
  5460. this._childrenFlag = -1;
  5461. this._isEnabled = true;
  5462. this._isReady = true;
  5463. this._currentRenderId = -1;
  5464. this._parentRenderId = -1;
  5465. this.name = name;
  5466. this.id = name;
  5467. this._scene = scene;
  5468. this._initCache();
  5469. }
  5470. Node.prototype.getScene = function () {
  5471. return this._scene;
  5472. };
  5473. Node.prototype.getEngine = function () {
  5474. return this._scene.getEngine();
  5475. };
  5476. // override it in derived class
  5477. Node.prototype.getWorldMatrix = function () {
  5478. return BABYLON.Matrix.Identity();
  5479. };
  5480. // override it in derived class if you add new variables to the cache
  5481. // and call the parent class method
  5482. Node.prototype._initCache = function () {
  5483. this._cache = {};
  5484. this._cache.parent = undefined;
  5485. };
  5486. Node.prototype.updateCache = function (force) {
  5487. if (!force && this.isSynchronized())
  5488. return;
  5489. this._cache.parent = this.parent;
  5490. this._updateCache();
  5491. };
  5492. // override it in derived class if you add new variables to the cache
  5493. // and call the parent class method if !ignoreParentClass
  5494. Node.prototype._updateCache = function (ignoreParentClass) {
  5495. };
  5496. // override it in derived class if you add new variables to the cache
  5497. Node.prototype._isSynchronized = function () {
  5498. return true;
  5499. };
  5500. Node.prototype.isSynchronizedWithParent = function () {
  5501. if (!this.parent) {
  5502. return true;
  5503. }
  5504. if (this._parentRenderId !== this.parent._currentRenderId) {
  5505. return false;
  5506. }
  5507. this._parentRenderId = this.parent._currentRenderId;
  5508. return this.parent._currentRenderId <= this._currentRenderId && this.parent.isSynchronized();
  5509. };
  5510. Node.prototype.isSynchronized = function (updateCache) {
  5511. var check = this.hasNewParent();
  5512. check = check || !this.isSynchronizedWithParent();
  5513. check = check || !this._isSynchronized();
  5514. if (updateCache)
  5515. this.updateCache(true);
  5516. return !check;
  5517. };
  5518. Node.prototype.hasNewParent = function (update) {
  5519. if (this._cache.parent === this.parent)
  5520. return false;
  5521. if (update)
  5522. this._cache.parent = this.parent;
  5523. return true;
  5524. };
  5525. /**
  5526. * Is this node ready to be used/rendered
  5527. * @return {boolean} is it ready
  5528. */
  5529. Node.prototype.isReady = function () {
  5530. return this._isReady;
  5531. };
  5532. /**
  5533. * Is this node enabled.
  5534. * If the node has a parent and is enabled, the parent will be inspected as well.
  5535. * @return {boolean} whether this node (and its parent) is enabled.
  5536. * @see setEnabled
  5537. */
  5538. Node.prototype.isEnabled = function () {
  5539. if (!this._isEnabled) {
  5540. return false;
  5541. }
  5542. if (this.parent) {
  5543. return this.parent.isEnabled();
  5544. }
  5545. return true;
  5546. };
  5547. /**
  5548. * Set the enabled state of this node.
  5549. * @param {boolean} value - the new enabled state
  5550. * @see isEnabled
  5551. */
  5552. Node.prototype.setEnabled = function (value) {
  5553. this._isEnabled = value;
  5554. };
  5555. /**
  5556. * Is this node a descendant of the given node.
  5557. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  5558. * @param {BABYLON.Node} ancestor - The parent node to inspect
  5559. * @see parent
  5560. */
  5561. Node.prototype.isDescendantOf = function (ancestor) {
  5562. if (this.parent) {
  5563. if (this.parent === ancestor) {
  5564. return true;
  5565. }
  5566. return this.parent.isDescendantOf(ancestor);
  5567. }
  5568. return false;
  5569. };
  5570. Node.prototype._getDescendants = function (list, results) {
  5571. for (var index = 0; index < list.length; index++) {
  5572. var item = list[index];
  5573. if (item.isDescendantOf(this)) {
  5574. results.push(item);
  5575. }
  5576. }
  5577. };
  5578. /**
  5579. * Will return all nodes that have this node as parent.
  5580. * @return {BABYLON.Node[]} all children nodes of all types.
  5581. */
  5582. Node.prototype.getDescendants = function () {
  5583. var results = [];
  5584. this._getDescendants(this._scene.meshes, results);
  5585. this._getDescendants(this._scene.lights, results);
  5586. this._getDescendants(this._scene.cameras, results);
  5587. return results;
  5588. };
  5589. Node.prototype._setReady = function (state) {
  5590. if (state == this._isReady) {
  5591. return;
  5592. }
  5593. if (!state) {
  5594. this._isReady = false;
  5595. return;
  5596. }
  5597. this._isReady = true;
  5598. if (this.onReady) {
  5599. this.onReady(this);
  5600. }
  5601. };
  5602. return Node;
  5603. })();
  5604. BABYLON.Node = Node;
  5605. })(BABYLON || (BABYLON = {}));
  5606. //# sourceMappingURL=babylon.node.js.mapvar BABYLON;
  5607. (function (BABYLON) {
  5608. var BoundingSphere = (function () {
  5609. function BoundingSphere(minimum, maximum) {
  5610. this.minimum = minimum;
  5611. this.maximum = maximum;
  5612. this._tempRadiusVector = BABYLON.Vector3.Zero();
  5613. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  5614. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  5615. this.radius = distance * 0.5;
  5616. this.centerWorld = BABYLON.Vector3.Zero();
  5617. this._update(BABYLON.Matrix.Identity());
  5618. }
  5619. // Methods
  5620. BoundingSphere.prototype._update = function (world) {
  5621. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  5622. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  5623. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  5624. };
  5625. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  5626. for (var i = 0; i < 6; i++) {
  5627. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  5628. return false;
  5629. }
  5630. return true;
  5631. };
  5632. BoundingSphere.prototype.intersectsPoint = function (point) {
  5633. var x = this.centerWorld.x - point.x;
  5634. var y = this.centerWorld.y - point.y;
  5635. var z = this.centerWorld.z - point.z;
  5636. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  5637. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  5638. return false;
  5639. return true;
  5640. };
  5641. // Statics
  5642. BoundingSphere.Intersects = function (sphere0, sphere1) {
  5643. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  5644. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  5645. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  5646. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  5647. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  5648. return false;
  5649. return true;
  5650. };
  5651. return BoundingSphere;
  5652. })();
  5653. BABYLON.BoundingSphere = BoundingSphere;
  5654. })(BABYLON || (BABYLON = {}));
  5655. //# sourceMappingURL=babylon.boundingSphere.js.mapvar BABYLON;
  5656. (function (BABYLON) {
  5657. var BoundingBox = (function () {
  5658. function BoundingBox(minimum, maximum) {
  5659. this.minimum = minimum;
  5660. this.maximum = maximum;
  5661. this.vectors = new Array();
  5662. this.vectorsWorld = new Array();
  5663. // Bounding vectors
  5664. this.vectors.push(this.minimum.clone());
  5665. this.vectors.push(this.maximum.clone());
  5666. this.vectors.push(this.minimum.clone());
  5667. this.vectors[2].x = this.maximum.x;
  5668. this.vectors.push(this.minimum.clone());
  5669. this.vectors[3].y = this.maximum.y;
  5670. this.vectors.push(this.minimum.clone());
  5671. this.vectors[4].z = this.maximum.z;
  5672. this.vectors.push(this.maximum.clone());
  5673. this.vectors[5].z = this.minimum.z;
  5674. this.vectors.push(this.maximum.clone());
  5675. this.vectors[6].x = this.minimum.x;
  5676. this.vectors.push(this.maximum.clone());
  5677. this.vectors[7].y = this.minimum.y;
  5678. // OBB
  5679. this.center = this.maximum.add(this.minimum).scale(0.5);
  5680. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  5681. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  5682. for (var index = 0; index < this.vectors.length; index++) {
  5683. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  5684. }
  5685. this.minimumWorld = BABYLON.Vector3.Zero();
  5686. this.maximumWorld = BABYLON.Vector3.Zero();
  5687. this._update(BABYLON.Matrix.Identity());
  5688. }
  5689. // Methods
  5690. BoundingBox.prototype.getWorldMatrix = function () {
  5691. return this._worldMatrix;
  5692. };
  5693. BoundingBox.prototype._update = function (world) {
  5694. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  5695. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  5696. for (var index = 0; index < this.vectors.length; index++) {
  5697. var v = this.vectorsWorld[index];
  5698. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  5699. if (v.x < this.minimumWorld.x)
  5700. this.minimumWorld.x = v.x;
  5701. if (v.y < this.minimumWorld.y)
  5702. this.minimumWorld.y = v.y;
  5703. if (v.z < this.minimumWorld.z)
  5704. this.minimumWorld.z = v.z;
  5705. if (v.x > this.maximumWorld.x)
  5706. this.maximumWorld.x = v.x;
  5707. if (v.y > this.maximumWorld.y)
  5708. this.maximumWorld.y = v.y;
  5709. if (v.z > this.maximumWorld.z)
  5710. this.maximumWorld.z = v.z;
  5711. }
  5712. // OBB
  5713. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  5714. this.center.scaleInPlace(0.5);
  5715. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  5716. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  5717. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  5718. this._worldMatrix = world;
  5719. };
  5720. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  5721. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  5722. };
  5723. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  5724. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  5725. };
  5726. BoundingBox.prototype.intersectsPoint = function (point) {
  5727. var delta = BABYLON.Engine.Epsilon;
  5728. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  5729. return false;
  5730. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  5731. return false;
  5732. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  5733. return false;
  5734. return true;
  5735. };
  5736. BoundingBox.prototype.intersectsSphere = function (sphere) {
  5737. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  5738. };
  5739. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  5740. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  5741. return false;
  5742. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  5743. return false;
  5744. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  5745. return false;
  5746. return true;
  5747. };
  5748. // Statics
  5749. BoundingBox.Intersects = function (box0, box1) {
  5750. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  5751. return false;
  5752. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  5753. return false;
  5754. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  5755. return false;
  5756. return true;
  5757. };
  5758. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  5759. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  5760. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  5761. return (num <= (sphereRadius * sphereRadius));
  5762. };
  5763. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  5764. for (var p = 0; p < 6; p++) {
  5765. for (var i = 0; i < 8; i++) {
  5766. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  5767. return false;
  5768. }
  5769. }
  5770. }
  5771. return true;
  5772. };
  5773. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  5774. for (var p = 0; p < 6; p++) {
  5775. var inCount = 8;
  5776. for (var i = 0; i < 8; i++) {
  5777. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  5778. --inCount;
  5779. }
  5780. else {
  5781. break;
  5782. }
  5783. }
  5784. if (inCount === 0)
  5785. return false;
  5786. }
  5787. return true;
  5788. };
  5789. return BoundingBox;
  5790. })();
  5791. BABYLON.BoundingBox = BoundingBox;
  5792. })(BABYLON || (BABYLON = {}));
  5793. //# sourceMappingURL=babylon.boundingBox.js.mapvar BABYLON;
  5794. (function (BABYLON) {
  5795. var computeBoxExtents = function (axis, box) {
  5796. var p = BABYLON.Vector3.Dot(box.center, axis);
  5797. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  5798. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  5799. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  5800. var r = r0 + r1 + r2;
  5801. return {
  5802. min: p - r,
  5803. max: p + r
  5804. };
  5805. };
  5806. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  5807. var axisOverlap = function (axis, box0, box1) {
  5808. var result0 = computeBoxExtents(axis, box0);
  5809. var result1 = computeBoxExtents(axis, box1);
  5810. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  5811. };
  5812. var BoundingInfo = (function () {
  5813. function BoundingInfo(minimum, maximum) {
  5814. this.minimum = minimum;
  5815. this.maximum = maximum;
  5816. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  5817. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  5818. }
  5819. // Methods
  5820. BoundingInfo.prototype._update = function (world) {
  5821. this.boundingBox._update(world);
  5822. this.boundingSphere._update(world);
  5823. };
  5824. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  5825. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  5826. return false;
  5827. return this.boundingBox.isInFrustum(frustumPlanes);
  5828. };
  5829. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  5830. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  5831. };
  5832. BoundingInfo.prototype._checkCollision = function (collider) {
  5833. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  5834. };
  5835. BoundingInfo.prototype.intersectsPoint = function (point) {
  5836. if (!this.boundingSphere.centerWorld) {
  5837. return false;
  5838. }
  5839. if (!this.boundingSphere.intersectsPoint(point)) {
  5840. return false;
  5841. }
  5842. if (!this.boundingBox.intersectsPoint(point)) {
  5843. return false;
  5844. }
  5845. return true;
  5846. };
  5847. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  5848. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  5849. return false;
  5850. }
  5851. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  5852. return false;
  5853. }
  5854. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  5855. return false;
  5856. }
  5857. if (!precise) {
  5858. return true;
  5859. }
  5860. var box0 = this.boundingBox;
  5861. var box1 = boundingInfo.boundingBox;
  5862. if (!axisOverlap(box0.directions[0], box0, box1))
  5863. return false;
  5864. if (!axisOverlap(box0.directions[1], box0, box1))
  5865. return false;
  5866. if (!axisOverlap(box0.directions[2], box0, box1))
  5867. return false;
  5868. if (!axisOverlap(box1.directions[0], box0, box1))
  5869. return false;
  5870. if (!axisOverlap(box1.directions[1], box0, box1))
  5871. return false;
  5872. if (!axisOverlap(box1.directions[2], box0, box1))
  5873. return false;
  5874. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  5875. return false;
  5876. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  5877. return false;
  5878. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  5879. return false;
  5880. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  5881. return false;
  5882. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  5883. return false;
  5884. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  5885. return false;
  5886. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  5887. return false;
  5888. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  5889. return false;
  5890. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  5891. return false;
  5892. return true;
  5893. };
  5894. return BoundingInfo;
  5895. })();
  5896. BABYLON.BoundingInfo = BoundingInfo;
  5897. })(BABYLON || (BABYLON = {}));
  5898. //# sourceMappingURL=babylon.boundingInfo.js.map
  5899. var BABYLON;
  5900. (function (BABYLON) {
  5901. var Light = (function (_super) {
  5902. __extends(Light, _super);
  5903. function Light(name, scene) {
  5904. _super.call(this, name, scene);
  5905. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  5906. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  5907. this.intensity = 1.0;
  5908. this.range = Number.MAX_VALUE;
  5909. this.includeOnlyWithLayerMask = 0;
  5910. this.includedOnlyMeshes = new Array();
  5911. this.excludedMeshes = new Array();
  5912. this._excludedMeshesIds = new Array();
  5913. this._includedOnlyMeshesIds = new Array();
  5914. scene.addLight(this);
  5915. }
  5916. Light.prototype.getShadowGenerator = function () {
  5917. return this._shadowGenerator;
  5918. };
  5919. Light.prototype.getAbsolutePosition = function () {
  5920. return BABYLON.Vector3.Zero();
  5921. };
  5922. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  5923. };
  5924. Light.prototype._getWorldMatrix = function () {
  5925. return BABYLON.Matrix.Identity();
  5926. };
  5927. Light.prototype.canAffectMesh = function (mesh) {
  5928. if (!mesh) {
  5929. return true;
  5930. }
  5931. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  5932. return false;
  5933. }
  5934. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  5935. return false;
  5936. }
  5937. if (this.includeOnlyWithLayerMask !== 0 && this.includeOnlyWithLayerMask !== mesh.layerMask) {
  5938. return false;
  5939. }
  5940. return true;
  5941. };
  5942. Light.prototype.getWorldMatrix = function () {
  5943. this._currentRenderId = this.getScene().getRenderId();
  5944. var worldMatrix = this._getWorldMatrix();
  5945. if (this.parent && this.parent.getWorldMatrix) {
  5946. if (!this._parentedWorldMatrix) {
  5947. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  5948. }
  5949. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  5950. return this._parentedWorldMatrix;
  5951. }
  5952. return worldMatrix;
  5953. };
  5954. Light.prototype.dispose = function () {
  5955. if (this._shadowGenerator) {
  5956. this._shadowGenerator.dispose();
  5957. this._shadowGenerator = null;
  5958. }
  5959. // Remove from scene
  5960. this.getScene().removeLight(this);
  5961. };
  5962. return Light;
  5963. })(BABYLON.Node);
  5964. BABYLON.Light = Light;
  5965. })(BABYLON || (BABYLON = {}));
  5966. //# sourceMappingURL=babylon.light.js.map
  5967. var BABYLON;
  5968. (function (BABYLON) {
  5969. var PointLight = (function (_super) {
  5970. __extends(PointLight, _super);
  5971. function PointLight(name, position, scene) {
  5972. _super.call(this, name, scene);
  5973. this.position = position;
  5974. }
  5975. PointLight.prototype.getAbsolutePosition = function () {
  5976. return this._transformedPosition ? this._transformedPosition : this.position;
  5977. };
  5978. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  5979. if (this.parent && this.parent.getWorldMatrix) {
  5980. if (!this._transformedPosition) {
  5981. this._transformedPosition = BABYLON.Vector3.Zero();
  5982. }
  5983. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  5984. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, 0);
  5985. return;
  5986. }
  5987. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  5988. };
  5989. PointLight.prototype.getShadowGenerator = function () {
  5990. return null;
  5991. };
  5992. PointLight.prototype._getWorldMatrix = function () {
  5993. if (!this._worldMatrix) {
  5994. this._worldMatrix = BABYLON.Matrix.Identity();
  5995. }
  5996. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  5997. return this._worldMatrix;
  5998. };
  5999. return PointLight;
  6000. })(BABYLON.Light);
  6001. BABYLON.PointLight = PointLight;
  6002. })(BABYLON || (BABYLON = {}));
  6003. //# sourceMappingURL=babylon.pointLight.js.map
  6004. var BABYLON;
  6005. (function (BABYLON) {
  6006. var SpotLight = (function (_super) {
  6007. __extends(SpotLight, _super);
  6008. function SpotLight(name, position, direction, angle, exponent, scene) {
  6009. _super.call(this, name, scene);
  6010. this.position = position;
  6011. this.direction = direction;
  6012. this.angle = angle;
  6013. this.exponent = exponent;
  6014. }
  6015. SpotLight.prototype.getAbsolutePosition = function () {
  6016. return this.transformedPosition ? this.transformedPosition : this.position;
  6017. };
  6018. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  6019. var activeCamera = this.getScene().activeCamera;
  6020. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  6021. };
  6022. SpotLight.prototype.supportsVSM = function () {
  6023. return true;
  6024. };
  6025. SpotLight.prototype.needRefreshPerFrame = function () {
  6026. return false;
  6027. };
  6028. SpotLight.prototype.setDirectionToTarget = function (target) {
  6029. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  6030. return this.direction;
  6031. };
  6032. SpotLight.prototype.computeTransformedPosition = function () {
  6033. if (this.parent && this.parent.getWorldMatrix) {
  6034. if (!this.transformedPosition) {
  6035. this.transformedPosition = BABYLON.Vector3.Zero();
  6036. }
  6037. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  6038. return true;
  6039. }
  6040. return false;
  6041. };
  6042. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  6043. var normalizeDirection;
  6044. if (this.parent && this.parent.getWorldMatrix) {
  6045. if (!this._transformedDirection) {
  6046. this._transformedDirection = BABYLON.Vector3.Zero();
  6047. }
  6048. this.computeTransformedPosition();
  6049. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  6050. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  6051. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  6052. }
  6053. else {
  6054. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  6055. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  6056. }
  6057. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  6058. };
  6059. SpotLight.prototype._getWorldMatrix = function () {
  6060. if (!this._worldMatrix) {
  6061. this._worldMatrix = BABYLON.Matrix.Identity();
  6062. }
  6063. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  6064. return this._worldMatrix;
  6065. };
  6066. return SpotLight;
  6067. })(BABYLON.Light);
  6068. BABYLON.SpotLight = SpotLight;
  6069. })(BABYLON || (BABYLON = {}));
  6070. //# sourceMappingURL=babylon.spotLight.js.map
  6071. var BABYLON;
  6072. (function (BABYLON) {
  6073. var DirectionalLight = (function (_super) {
  6074. __extends(DirectionalLight, _super);
  6075. function DirectionalLight(name, direction, scene) {
  6076. _super.call(this, name, scene);
  6077. this.direction = direction;
  6078. this.shadowOrthoScale = 0.5;
  6079. this.position = direction.scale(-1);
  6080. }
  6081. DirectionalLight.prototype.getAbsolutePosition = function () {
  6082. return this.transformedPosition ? this.transformedPosition : this.position;
  6083. };
  6084. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  6085. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  6086. return this.direction;
  6087. };
  6088. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  6089. var orthoLeft = Number.MAX_VALUE;
  6090. var orthoRight = Number.MIN_VALUE;
  6091. var orthoTop = Number.MIN_VALUE;
  6092. var orthoBottom = Number.MAX_VALUE;
  6093. var tempVector3 = BABYLON.Vector3.Zero();
  6094. var activeCamera = this.getScene().activeCamera;
  6095. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  6096. var mesh = renderList[meshIndex];
  6097. if (!mesh) {
  6098. continue;
  6099. }
  6100. var boundingInfo = mesh.getBoundingInfo();
  6101. if (!boundingInfo) {
  6102. continue;
  6103. }
  6104. var boundingBox = boundingInfo.boundingBox;
  6105. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  6106. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  6107. if (tempVector3.x < orthoLeft)
  6108. orthoLeft = tempVector3.x;
  6109. if (tempVector3.y < orthoBottom)
  6110. orthoBottom = tempVector3.y;
  6111. if (tempVector3.x > orthoRight)
  6112. orthoRight = tempVector3.x;
  6113. if (tempVector3.y > orthoTop)
  6114. orthoTop = tempVector3.y;
  6115. }
  6116. }
  6117. var xOffset = orthoRight - orthoLeft;
  6118. var yOffset = orthoTop - orthoBottom;
  6119. BABYLON.Matrix.OrthoOffCenterLHToRef(orthoLeft - xOffset * this.shadowOrthoScale, orthoRight + xOffset * this.shadowOrthoScale, orthoBottom - yOffset * this.shadowOrthoScale, orthoTop + yOffset * this.shadowOrthoScale, -activeCamera.maxZ, activeCamera.maxZ, matrix);
  6120. };
  6121. DirectionalLight.prototype.supportsVSM = function () {
  6122. return true;
  6123. };
  6124. DirectionalLight.prototype.needRefreshPerFrame = function () {
  6125. return true;
  6126. };
  6127. DirectionalLight.prototype.computeTransformedPosition = function () {
  6128. if (this.parent && this.parent.getWorldMatrix) {
  6129. if (!this.transformedPosition) {
  6130. this.transformedPosition = BABYLON.Vector3.Zero();
  6131. }
  6132. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  6133. return true;
  6134. }
  6135. return false;
  6136. };
  6137. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  6138. if (this.parent && this.parent.getWorldMatrix) {
  6139. if (!this._transformedDirection) {
  6140. this._transformedDirection = BABYLON.Vector3.Zero();
  6141. }
  6142. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  6143. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  6144. return;
  6145. }
  6146. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  6147. };
  6148. DirectionalLight.prototype._getWorldMatrix = function () {
  6149. if (!this._worldMatrix) {
  6150. this._worldMatrix = BABYLON.Matrix.Identity();
  6151. }
  6152. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  6153. return this._worldMatrix;
  6154. };
  6155. return DirectionalLight;
  6156. })(BABYLON.Light);
  6157. BABYLON.DirectionalLight = DirectionalLight;
  6158. })(BABYLON || (BABYLON = {}));
  6159. //# sourceMappingURL=babylon.directionalLight.js.mapvar BABYLON;
  6160. (function (BABYLON) {
  6161. var ShadowGenerator = (function () {
  6162. function ShadowGenerator(mapSize, light) {
  6163. var _this = this;
  6164. // Members
  6165. this._filter = ShadowGenerator.FILTER_NONE;
  6166. this.blurScale = 2;
  6167. this._blurBoxOffset = 0;
  6168. this._bias = 0.00005;
  6169. this._darkness = 0;
  6170. this._transparencyShadow = false;
  6171. this._viewMatrix = BABYLON.Matrix.Zero();
  6172. this._projectionMatrix = BABYLON.Matrix.Zero();
  6173. this._transformMatrix = BABYLON.Matrix.Zero();
  6174. this._worldViewProjection = BABYLON.Matrix.Zero();
  6175. this._light = light;
  6176. this._scene = light.getScene();
  6177. this._mapSize = mapSize;
  6178. light._shadowGenerator = this;
  6179. // Render target
  6180. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false);
  6181. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  6182. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  6183. this._shadowMap.anisotropicFilteringLevel = 1;
  6184. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  6185. this._shadowMap.renderParticles = false;
  6186. this._shadowMap.onAfterUnbind = function () {
  6187. if (!_this.useBlurVarianceShadowMap) {
  6188. return;
  6189. }
  6190. if (!_this._shadowMap2) {
  6191. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false);
  6192. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  6193. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  6194. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  6195. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  6196. _this._downSamplePostprocess.onApply = function (effect) {
  6197. effect.setTexture("textureSampler", _this._shadowMap);
  6198. };
  6199. _this.blurBoxOffset = 1;
  6200. }
  6201. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  6202. };
  6203. // Custom render function
  6204. var renderSubMesh = function (subMesh) {
  6205. var mesh = subMesh.getRenderingMesh();
  6206. var scene = _this._scene;
  6207. var engine = scene.getEngine();
  6208. // Culling
  6209. engine.setState(subMesh.getMaterial().backFaceCulling);
  6210. // Managing instances
  6211. var batch = mesh._getInstancesRenderList(subMesh._id);
  6212. if (batch.mustReturn) {
  6213. return;
  6214. }
  6215. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  6216. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  6217. engine.enableEffect(_this._effect);
  6218. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  6219. var material = subMesh.getMaterial();
  6220. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  6221. // Alpha test
  6222. if (material && material.needAlphaTesting()) {
  6223. var alphaTexture = material.getAlphaTestTexture();
  6224. _this._effect.setTexture("diffuseSampler", alphaTexture);
  6225. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  6226. }
  6227. // Bones
  6228. if (mesh.useBones) {
  6229. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  6230. }
  6231. // Draw
  6232. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  6233. }
  6234. else {
  6235. // Need to reset refresh rate of the shadowMap
  6236. _this._shadowMap.resetRefreshCounter();
  6237. }
  6238. };
  6239. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  6240. var index;
  6241. for (index = 0; index < opaqueSubMeshes.length; index++) {
  6242. renderSubMesh(opaqueSubMeshes.data[index]);
  6243. }
  6244. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  6245. renderSubMesh(alphaTestSubMeshes.data[index]);
  6246. }
  6247. if (_this._transparencyShadow) {
  6248. for (index = 0; index < transparentSubMeshes.length; index++) {
  6249. renderSubMesh(transparentSubMeshes.data[index]);
  6250. }
  6251. }
  6252. };
  6253. this._shadowMap.onClear = function (engine) {
  6254. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  6255. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
  6256. }
  6257. else {
  6258. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  6259. }
  6260. };
  6261. }
  6262. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  6263. // Static
  6264. get: function () {
  6265. return ShadowGenerator._FILTER_NONE;
  6266. },
  6267. enumerable: true,
  6268. configurable: true
  6269. });
  6270. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  6271. get: function () {
  6272. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  6273. },
  6274. enumerable: true,
  6275. configurable: true
  6276. });
  6277. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  6278. get: function () {
  6279. return ShadowGenerator._FILTER_POISSONSAMPLING;
  6280. },
  6281. enumerable: true,
  6282. configurable: true
  6283. });
  6284. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  6285. get: function () {
  6286. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  6287. },
  6288. enumerable: true,
  6289. configurable: true
  6290. });
  6291. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  6292. get: function () {
  6293. return this._bias;
  6294. },
  6295. set: function (bias) {
  6296. this._bias = bias;
  6297. },
  6298. enumerable: true,
  6299. configurable: true
  6300. });
  6301. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  6302. get: function () {
  6303. return this._blurBoxOffset;
  6304. },
  6305. set: function (value) {
  6306. var _this = this;
  6307. if (this._blurBoxOffset === value) {
  6308. return;
  6309. }
  6310. this._blurBoxOffset = value;
  6311. if (this._boxBlurPostprocess) {
  6312. this._boxBlurPostprocess.dispose();
  6313. }
  6314. this._boxBlurPostprocess = new BABYLON.PostProcess("DepthBoxBlur", "depthBoxBlur", ["screenSize", "boxOffset"], [], 1.0 / this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define OFFSET " + value);
  6315. this._boxBlurPostprocess.onApply = function (effect) {
  6316. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  6317. };
  6318. },
  6319. enumerable: true,
  6320. configurable: true
  6321. });
  6322. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  6323. get: function () {
  6324. return this._filter;
  6325. },
  6326. set: function (value) {
  6327. if (this._filter === value) {
  6328. return;
  6329. }
  6330. this._filter = value;
  6331. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  6332. this._shadowMap.anisotropicFilteringLevel = 16;
  6333. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  6334. }
  6335. else {
  6336. this._shadowMap.anisotropicFilteringLevel = 1;
  6337. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  6338. }
  6339. },
  6340. enumerable: true,
  6341. configurable: true
  6342. });
  6343. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  6344. get: function () {
  6345. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  6346. },
  6347. set: function (value) {
  6348. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  6349. },
  6350. enumerable: true,
  6351. configurable: true
  6352. });
  6353. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  6354. get: function () {
  6355. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING || (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP || this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  6356. },
  6357. set: function (value) {
  6358. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  6359. },
  6360. enumerable: true,
  6361. configurable: true
  6362. });
  6363. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  6364. get: function () {
  6365. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  6366. },
  6367. set: function (value) {
  6368. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  6369. },
  6370. enumerable: true,
  6371. configurable: true
  6372. });
  6373. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  6374. var defines = [];
  6375. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  6376. defines.push("#define VSM");
  6377. }
  6378. var attribs = [BABYLON.VertexBuffer.PositionKind];
  6379. var mesh = subMesh.getMesh();
  6380. var material = subMesh.getMaterial();
  6381. // Alpha test
  6382. if (material && material.needAlphaTesting()) {
  6383. defines.push("#define ALPHATEST");
  6384. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  6385. attribs.push(BABYLON.VertexBuffer.UVKind);
  6386. defines.push("#define UV1");
  6387. }
  6388. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  6389. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  6390. defines.push("#define UV2");
  6391. }
  6392. }
  6393. // Bones
  6394. if (mesh.useBones) {
  6395. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  6396. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  6397. defines.push("#define BONES");
  6398. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  6399. }
  6400. // Instances
  6401. if (useInstances) {
  6402. defines.push("#define INSTANCES");
  6403. attribs.push("world0");
  6404. attribs.push("world1");
  6405. attribs.push("world2");
  6406. attribs.push("world3");
  6407. }
  6408. // Get correct effect
  6409. var join = defines.join("\n");
  6410. if (this._cachedDefines !== join) {
  6411. this._cachedDefines = join;
  6412. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  6413. }
  6414. return this._effect.isReady();
  6415. };
  6416. ShadowGenerator.prototype.getShadowMap = function () {
  6417. return this._shadowMap;
  6418. };
  6419. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  6420. if (this._shadowMap2) {
  6421. return this._shadowMap2;
  6422. }
  6423. return this._shadowMap;
  6424. };
  6425. ShadowGenerator.prototype.getLight = function () {
  6426. return this._light;
  6427. };
  6428. // Methods
  6429. ShadowGenerator.prototype.getTransformMatrix = function () {
  6430. var scene = this._scene;
  6431. if (this._currentRenderID === scene.getRenderId()) {
  6432. return this._transformMatrix;
  6433. }
  6434. this._currentRenderID = scene.getRenderId();
  6435. var lightPosition = this._light.position;
  6436. var lightDirection = this._light.direction;
  6437. if (this._light.computeTransformedPosition()) {
  6438. lightPosition = this._light.transformedPosition;
  6439. }
  6440. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !lightDirection.equals(this._cachedDirection)) {
  6441. this._cachedPosition = lightPosition.clone();
  6442. this._cachedDirection = lightDirection.clone();
  6443. BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  6444. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  6445. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  6446. }
  6447. return this._transformMatrix;
  6448. };
  6449. ShadowGenerator.prototype.getDarkness = function () {
  6450. return this._darkness;
  6451. };
  6452. ShadowGenerator.prototype.setDarkness = function (darkness) {
  6453. if (darkness >= 1.0)
  6454. this._darkness = 1.0;
  6455. else if (darkness <= 0.0)
  6456. this._darkness = 0.0;
  6457. else
  6458. this._darkness = darkness;
  6459. };
  6460. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  6461. this._transparencyShadow = hasShadow;
  6462. };
  6463. ShadowGenerator.prototype._packHalf = function (depth) {
  6464. var scale = depth * 255.0;
  6465. var fract = scale - Math.floor(scale);
  6466. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  6467. };
  6468. ShadowGenerator.prototype.dispose = function () {
  6469. this._shadowMap.dispose();
  6470. if (this._shadowMap2) {
  6471. this._shadowMap2.dispose();
  6472. }
  6473. if (this._downSamplePostprocess) {
  6474. this._downSamplePostprocess.dispose();
  6475. }
  6476. if (this._boxBlurPostprocess) {
  6477. this._boxBlurPostprocess.dispose();
  6478. }
  6479. };
  6480. ShadowGenerator._FILTER_NONE = 0;
  6481. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  6482. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  6483. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  6484. return ShadowGenerator;
  6485. })();
  6486. BABYLON.ShadowGenerator = ShadowGenerator;
  6487. })(BABYLON || (BABYLON = {}));
  6488. //# sourceMappingURL=babylon.shadowGenerator.js.map
  6489. var BABYLON;
  6490. (function (BABYLON) {
  6491. var HemisphericLight = (function (_super) {
  6492. __extends(HemisphericLight, _super);
  6493. function HemisphericLight(name, direction, scene) {
  6494. _super.call(this, name, scene);
  6495. this.direction = direction;
  6496. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  6497. }
  6498. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  6499. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  6500. return this.direction;
  6501. };
  6502. HemisphericLight.prototype.getShadowGenerator = function () {
  6503. return null;
  6504. };
  6505. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  6506. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  6507. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  6508. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  6509. };
  6510. HemisphericLight.prototype._getWorldMatrix = function () {
  6511. if (!this._worldMatrix) {
  6512. this._worldMatrix = BABYLON.Matrix.Identity();
  6513. }
  6514. return this._worldMatrix;
  6515. };
  6516. return HemisphericLight;
  6517. })(BABYLON.Light);
  6518. BABYLON.HemisphericLight = HemisphericLight;
  6519. })(BABYLON || (BABYLON = {}));
  6520. //# sourceMappingURL=babylon.hemisphericLight.js.mapvar BABYLON;
  6521. (function (BABYLON) {
  6522. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  6523. if (boxMin.x > sphereCenter.x + sphereRadius)
  6524. return false;
  6525. if (sphereCenter.x - sphereRadius > boxMax.x)
  6526. return false;
  6527. if (boxMin.y > sphereCenter.y + sphereRadius)
  6528. return false;
  6529. if (sphereCenter.y - sphereRadius > boxMax.y)
  6530. return false;
  6531. if (boxMin.z > sphereCenter.z + sphereRadius)
  6532. return false;
  6533. if (sphereCenter.z - sphereRadius > boxMax.z)
  6534. return false;
  6535. return true;
  6536. };
  6537. var getLowestRoot = function (a, b, c, maxR) {
  6538. var determinant = b * b - 4.0 * a * c;
  6539. var result = { root: 0, found: false };
  6540. if (determinant < 0)
  6541. return result;
  6542. var sqrtD = Math.sqrt(determinant);
  6543. var r1 = (-b - sqrtD) / (2.0 * a);
  6544. var r2 = (-b + sqrtD) / (2.0 * a);
  6545. if (r1 > r2) {
  6546. var temp = r2;
  6547. r2 = r1;
  6548. r1 = temp;
  6549. }
  6550. if (r1 > 0 && r1 < maxR) {
  6551. result.root = r1;
  6552. result.found = true;
  6553. return result;
  6554. }
  6555. if (r2 > 0 && r2 < maxR) {
  6556. result.root = r2;
  6557. result.found = true;
  6558. return result;
  6559. }
  6560. return result;
  6561. };
  6562. var Collider = (function () {
  6563. function Collider() {
  6564. this.radius = new BABYLON.Vector3(1, 1, 1);
  6565. this.retry = 0;
  6566. this.basePointWorld = BABYLON.Vector3.Zero();
  6567. this.velocityWorld = BABYLON.Vector3.Zero();
  6568. this.normalizedVelocity = BABYLON.Vector3.Zero();
  6569. this._collisionPoint = BABYLON.Vector3.Zero();
  6570. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  6571. this._tempVector = BABYLON.Vector3.Zero();
  6572. this._tempVector2 = BABYLON.Vector3.Zero();
  6573. this._tempVector3 = BABYLON.Vector3.Zero();
  6574. this._tempVector4 = BABYLON.Vector3.Zero();
  6575. this._edge = BABYLON.Vector3.Zero();
  6576. this._baseToVertex = BABYLON.Vector3.Zero();
  6577. this._destinationPoint = BABYLON.Vector3.Zero();
  6578. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  6579. this._displacementVector = BABYLON.Vector3.Zero();
  6580. }
  6581. // Methods
  6582. Collider.prototype._initialize = function (source, dir, e) {
  6583. this.velocity = dir;
  6584. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  6585. this.basePoint = source;
  6586. source.multiplyToRef(this.radius, this.basePointWorld);
  6587. dir.multiplyToRef(this.radius, this.velocityWorld);
  6588. this.velocityWorldLength = this.velocityWorld.length();
  6589. this.epsilon = e;
  6590. this.collisionFound = false;
  6591. };
  6592. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  6593. pa.subtractToRef(point, this._tempVector);
  6594. pb.subtractToRef(point, this._tempVector2);
  6595. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  6596. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  6597. if (d < 0)
  6598. return false;
  6599. pc.subtractToRef(point, this._tempVector3);
  6600. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  6601. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  6602. if (d < 0)
  6603. return false;
  6604. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  6605. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  6606. return d >= 0;
  6607. };
  6608. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  6609. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  6610. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  6611. if (distance > this.velocityWorldLength + max + sphereRadius) {
  6612. return false;
  6613. }
  6614. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  6615. return false;
  6616. return true;
  6617. };
  6618. Collider.prototype._testTriangle = function (faceIndex, subMesh, p1, p2, p3) {
  6619. var t0;
  6620. var embeddedInPlane = false;
  6621. if (!subMesh._trianglePlanes) {
  6622. subMesh._trianglePlanes = [];
  6623. }
  6624. if (!subMesh._trianglePlanes[faceIndex]) {
  6625. subMesh._trianglePlanes[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  6626. subMesh._trianglePlanes[faceIndex].copyFromPoints(p1, p2, p3);
  6627. }
  6628. var trianglePlane = subMesh._trianglePlanes[faceIndex];
  6629. if ((!subMesh.getMaterial()) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  6630. return;
  6631. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  6632. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  6633. if (normalDotVelocity == 0) {
  6634. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  6635. return;
  6636. embeddedInPlane = true;
  6637. t0 = 0;
  6638. }
  6639. else {
  6640. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  6641. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  6642. if (t0 > t1) {
  6643. var temp = t1;
  6644. t1 = t0;
  6645. t0 = temp;
  6646. }
  6647. if (t0 > 1.0 || t1 < 0.0)
  6648. return;
  6649. if (t0 < 0)
  6650. t0 = 0;
  6651. if (t0 > 1.0)
  6652. t0 = 1.0;
  6653. }
  6654. this._collisionPoint.copyFromFloats(0, 0, 0);
  6655. var found = false;
  6656. var t = 1.0;
  6657. if (!embeddedInPlane) {
  6658. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  6659. this.velocity.scaleToRef(t0, this._tempVector);
  6660. this._planeIntersectionPoint.addInPlace(this._tempVector);
  6661. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  6662. found = true;
  6663. t = t0;
  6664. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  6665. }
  6666. }
  6667. if (!found) {
  6668. var velocitySquaredLength = this.velocity.lengthSquared();
  6669. var a = velocitySquaredLength;
  6670. this.basePoint.subtractToRef(p1, this._tempVector);
  6671. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  6672. var c = this._tempVector.lengthSquared() - 1.0;
  6673. var lowestRoot = getLowestRoot(a, b, c, t);
  6674. if (lowestRoot.found) {
  6675. t = lowestRoot.root;
  6676. found = true;
  6677. this._collisionPoint.copyFrom(p1);
  6678. }
  6679. this.basePoint.subtractToRef(p2, this._tempVector);
  6680. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  6681. c = this._tempVector.lengthSquared() - 1.0;
  6682. lowestRoot = getLowestRoot(a, b, c, t);
  6683. if (lowestRoot.found) {
  6684. t = lowestRoot.root;
  6685. found = true;
  6686. this._collisionPoint.copyFrom(p2);
  6687. }
  6688. this.basePoint.subtractToRef(p3, this._tempVector);
  6689. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  6690. c = this._tempVector.lengthSquared() - 1.0;
  6691. lowestRoot = getLowestRoot(a, b, c, t);
  6692. if (lowestRoot.found) {
  6693. t = lowestRoot.root;
  6694. found = true;
  6695. this._collisionPoint.copyFrom(p3);
  6696. }
  6697. p2.subtractToRef(p1, this._edge);
  6698. p1.subtractToRef(this.basePoint, this._baseToVertex);
  6699. var edgeSquaredLength = this._edge.lengthSquared();
  6700. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  6701. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  6702. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  6703. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  6704. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  6705. lowestRoot = getLowestRoot(a, b, c, t);
  6706. if (lowestRoot.found) {
  6707. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  6708. if (f >= 0.0 && f <= 1.0) {
  6709. t = lowestRoot.root;
  6710. found = true;
  6711. this._edge.scaleInPlace(f);
  6712. p1.addToRef(this._edge, this._collisionPoint);
  6713. }
  6714. }
  6715. p3.subtractToRef(p2, this._edge);
  6716. p2.subtractToRef(this.basePoint, this._baseToVertex);
  6717. edgeSquaredLength = this._edge.lengthSquared();
  6718. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  6719. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  6720. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  6721. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  6722. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  6723. lowestRoot = getLowestRoot(a, b, c, t);
  6724. if (lowestRoot.found) {
  6725. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  6726. if (f >= 0.0 && f <= 1.0) {
  6727. t = lowestRoot.root;
  6728. found = true;
  6729. this._edge.scaleInPlace(f);
  6730. p2.addToRef(this._edge, this._collisionPoint);
  6731. }
  6732. }
  6733. p1.subtractToRef(p3, this._edge);
  6734. p3.subtractToRef(this.basePoint, this._baseToVertex);
  6735. edgeSquaredLength = this._edge.lengthSquared();
  6736. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  6737. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  6738. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  6739. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  6740. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  6741. lowestRoot = getLowestRoot(a, b, c, t);
  6742. if (lowestRoot.found) {
  6743. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  6744. if (f >= 0.0 && f <= 1.0) {
  6745. t = lowestRoot.root;
  6746. found = true;
  6747. this._edge.scaleInPlace(f);
  6748. p3.addToRef(this._edge, this._collisionPoint);
  6749. }
  6750. }
  6751. }
  6752. if (found) {
  6753. var distToCollision = t * this.velocity.length();
  6754. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  6755. if (!this.intersectionPoint) {
  6756. this.intersectionPoint = this._collisionPoint.clone();
  6757. }
  6758. else {
  6759. this.intersectionPoint.copyFrom(this._collisionPoint);
  6760. }
  6761. this.nearestDistance = distToCollision;
  6762. this.collisionFound = true;
  6763. this.collidedMesh = subMesh.getMesh();
  6764. }
  6765. }
  6766. };
  6767. Collider.prototype._collide = function (subMesh, pts, indices, indexStart, indexEnd, decal) {
  6768. for (var i = indexStart; i < indexEnd; i += 3) {
  6769. var p1 = pts[indices[i] - decal];
  6770. var p2 = pts[indices[i + 1] - decal];
  6771. var p3 = pts[indices[i + 2] - decal];
  6772. this._testTriangle(i, subMesh, p3, p2, p1);
  6773. }
  6774. };
  6775. Collider.prototype._getResponse = function (pos, vel) {
  6776. pos.addToRef(vel, this._destinationPoint);
  6777. vel.scaleInPlace((this.nearestDistance / vel.length()));
  6778. this.basePoint.addToRef(vel, pos);
  6779. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  6780. this._slidePlaneNormal.normalize();
  6781. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  6782. pos.addInPlace(this._displacementVector);
  6783. this.intersectionPoint.addInPlace(this._displacementVector);
  6784. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  6785. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  6786. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  6787. };
  6788. return Collider;
  6789. })();
  6790. BABYLON.Collider = Collider;
  6791. })(BABYLON || (BABYLON = {}));
  6792. //# sourceMappingURL=babylon.collider.js.map
  6793. var BABYLON;
  6794. (function (BABYLON) {
  6795. var Camera = (function (_super) {
  6796. __extends(Camera, _super);
  6797. function Camera(name, position, scene) {
  6798. _super.call(this, name, scene);
  6799. this.position = position;
  6800. // Members
  6801. this.upVector = BABYLON.Vector3.Up();
  6802. this.orthoLeft = null;
  6803. this.orthoRight = null;
  6804. this.orthoBottom = null;
  6805. this.orthoTop = null;
  6806. this.fov = 0.8;
  6807. this.minZ = 1.0;
  6808. this.maxZ = 10000.0;
  6809. this.inertia = 0.9;
  6810. this.mode = Camera.PERSPECTIVE_CAMERA;
  6811. this.isIntermediate = false;
  6812. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  6813. this.subCameras = [];
  6814. this.layerMask = 0xFFFFFFFF;
  6815. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  6816. this._computedViewMatrix = BABYLON.Matrix.Identity();
  6817. this._projectionMatrix = new BABYLON.Matrix();
  6818. this._postProcesses = new Array();
  6819. this._postProcessesTakenIndices = [];
  6820. this._activeMeshes = new BABYLON.SmartArray(256);
  6821. this._globalPosition = BABYLON.Vector3.Zero();
  6822. scene.addCamera(this);
  6823. if (!scene.activeCamera) {
  6824. scene.activeCamera = this;
  6825. }
  6826. }
  6827. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  6828. get: function () {
  6829. return Camera._PERSPECTIVE_CAMERA;
  6830. },
  6831. enumerable: true,
  6832. configurable: true
  6833. });
  6834. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  6835. get: function () {
  6836. return Camera._ORTHOGRAPHIC_CAMERA;
  6837. },
  6838. enumerable: true,
  6839. configurable: true
  6840. });
  6841. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  6842. get: function () {
  6843. return Camera._FOVMODE_VERTICAL_FIXED;
  6844. },
  6845. enumerable: true,
  6846. configurable: true
  6847. });
  6848. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  6849. get: function () {
  6850. return Camera._FOVMODE_HORIZONTAL_FIXED;
  6851. },
  6852. enumerable: true,
  6853. configurable: true
  6854. });
  6855. Object.defineProperty(Camera.prototype, "globalPosition", {
  6856. get: function () {
  6857. return this._globalPosition;
  6858. },
  6859. enumerable: true,
  6860. configurable: true
  6861. });
  6862. Camera.prototype.getActiveMeshes = function () {
  6863. return this._activeMeshes;
  6864. };
  6865. Camera.prototype.isActiveMesh = function (mesh) {
  6866. return (this._activeMeshes.indexOf(mesh) !== -1);
  6867. };
  6868. //Cache
  6869. Camera.prototype._initCache = function () {
  6870. _super.prototype._initCache.call(this);
  6871. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6872. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6873. this._cache.mode = undefined;
  6874. this._cache.minZ = undefined;
  6875. this._cache.maxZ = undefined;
  6876. this._cache.fov = undefined;
  6877. this._cache.aspectRatio = undefined;
  6878. this._cache.orthoLeft = undefined;
  6879. this._cache.orthoRight = undefined;
  6880. this._cache.orthoBottom = undefined;
  6881. this._cache.orthoTop = undefined;
  6882. this._cache.renderWidth = undefined;
  6883. this._cache.renderHeight = undefined;
  6884. };
  6885. Camera.prototype._updateCache = function (ignoreParentClass) {
  6886. if (!ignoreParentClass) {
  6887. _super.prototype._updateCache.call(this);
  6888. }
  6889. var engine = this.getEngine();
  6890. this._cache.position.copyFrom(this.position);
  6891. this._cache.upVector.copyFrom(this.upVector);
  6892. this._cache.mode = this.mode;
  6893. this._cache.minZ = this.minZ;
  6894. this._cache.maxZ = this.maxZ;
  6895. this._cache.fov = this.fov;
  6896. this._cache.aspectRatio = engine.getAspectRatio(this);
  6897. this._cache.orthoLeft = this.orthoLeft;
  6898. this._cache.orthoRight = this.orthoRight;
  6899. this._cache.orthoBottom = this.orthoBottom;
  6900. this._cache.orthoTop = this.orthoTop;
  6901. this._cache.renderWidth = engine.getRenderWidth();
  6902. this._cache.renderHeight = engine.getRenderHeight();
  6903. };
  6904. Camera.prototype._updateFromScene = function () {
  6905. this.updateCache();
  6906. this._update();
  6907. };
  6908. // Synchronized
  6909. Camera.prototype._isSynchronized = function () {
  6910. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  6911. };
  6912. Camera.prototype._isSynchronizedViewMatrix = function () {
  6913. if (!_super.prototype._isSynchronized.call(this))
  6914. return false;
  6915. return this._cache.position.equals(this.position) && this._cache.upVector.equals(this.upVector) && this.isSynchronizedWithParent();
  6916. };
  6917. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  6918. var check = this._cache.mode === this.mode && this._cache.minZ === this.minZ && this._cache.maxZ === this.maxZ;
  6919. if (!check) {
  6920. return false;
  6921. }
  6922. var engine = this.getEngine();
  6923. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  6924. check = this._cache.fov === this.fov && this._cache.aspectRatio === engine.getAspectRatio(this);
  6925. }
  6926. else {
  6927. 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();
  6928. }
  6929. return check;
  6930. };
  6931. // Controls
  6932. Camera.prototype.attachControl = function (element) {
  6933. };
  6934. Camera.prototype.detachControl = function (element) {
  6935. };
  6936. Camera.prototype._update = function () {
  6937. };
  6938. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  6939. if (insertAt === void 0) { insertAt = null; }
  6940. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  6941. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  6942. return 0;
  6943. }
  6944. if (insertAt == null || insertAt < 0) {
  6945. this._postProcesses.push(postProcess);
  6946. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  6947. return this._postProcesses.length - 1;
  6948. }
  6949. var add = 0;
  6950. if (this._postProcesses[insertAt]) {
  6951. var start = this._postProcesses.length - 1;
  6952. for (var i = start; i >= insertAt + 1; --i) {
  6953. this._postProcesses[i + 1] = this._postProcesses[i];
  6954. }
  6955. add = 1;
  6956. }
  6957. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  6958. if (this._postProcessesTakenIndices[i] < insertAt) {
  6959. continue;
  6960. }
  6961. start = this._postProcessesTakenIndices.length - 1;
  6962. for (var j = start; j >= i; --j) {
  6963. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  6964. }
  6965. this._postProcessesTakenIndices[i] = insertAt;
  6966. break;
  6967. }
  6968. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) == -1) {
  6969. this._postProcessesTakenIndices.push(insertAt);
  6970. }
  6971. var result = insertAt + add;
  6972. this._postProcesses[result] = postProcess;
  6973. return result;
  6974. };
  6975. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  6976. if (atIndices === void 0) { atIndices = null; }
  6977. var result = [];
  6978. if (!atIndices) {
  6979. var length = this._postProcesses.length;
  6980. for (var i = 0; i < length; i++) {
  6981. if (this._postProcesses[i] !== postProcess) {
  6982. continue;
  6983. }
  6984. delete this._postProcesses[i];
  6985. var index = this._postProcessesTakenIndices.indexOf(i);
  6986. this._postProcessesTakenIndices.splice(index, 1);
  6987. }
  6988. }
  6989. else {
  6990. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  6991. for (i = 0; i < atIndices.length; i++) {
  6992. var foundPostProcess = this._postProcesses[atIndices[i]];
  6993. if (foundPostProcess !== postProcess) {
  6994. result.push(i);
  6995. continue;
  6996. }
  6997. delete this._postProcesses[atIndices[i]];
  6998. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  6999. this._postProcessesTakenIndices.splice(index, 1);
  7000. }
  7001. }
  7002. return result;
  7003. };
  7004. Camera.prototype.getWorldMatrix = function () {
  7005. if (!this._worldMatrix) {
  7006. this._worldMatrix = BABYLON.Matrix.Identity();
  7007. }
  7008. var viewMatrix = this.getViewMatrix();
  7009. viewMatrix.invertToRef(this._worldMatrix);
  7010. return this._worldMatrix;
  7011. };
  7012. Camera.prototype._getViewMatrix = function () {
  7013. return BABYLON.Matrix.Identity();
  7014. };
  7015. Camera.prototype.getViewMatrix = function () {
  7016. this._computedViewMatrix = this._computeViewMatrix();
  7017. if (!this.parent || !this.parent.getWorldMatrix || this.isSynchronized()) {
  7018. this._globalPosition.copyFrom(this.position);
  7019. return this._computedViewMatrix;
  7020. }
  7021. if (!this._worldMatrix) {
  7022. this._worldMatrix = BABYLON.Matrix.Identity();
  7023. }
  7024. this._computedViewMatrix.invertToRef(this._worldMatrix);
  7025. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  7026. this._computedViewMatrix.invert();
  7027. this._currentRenderId = this.getScene().getRenderId();
  7028. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  7029. return this._computedViewMatrix;
  7030. };
  7031. Camera.prototype._computeViewMatrix = function (force) {
  7032. if (!force && this._isSynchronizedViewMatrix()) {
  7033. return this._computedViewMatrix;
  7034. }
  7035. this._computedViewMatrix = this._getViewMatrix();
  7036. if (!this.parent || !this.parent.getWorldMatrix) {
  7037. this._currentRenderId = this.getScene().getRenderId();
  7038. }
  7039. return this._computedViewMatrix;
  7040. };
  7041. Camera.prototype.getProjectionMatrix = function (force) {
  7042. if (!force && this._isSynchronizedProjectionMatrix()) {
  7043. return this._projectionMatrix;
  7044. }
  7045. var engine = this.getEngine();
  7046. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  7047. if (this.minZ <= 0) {
  7048. this.minZ = 0.1;
  7049. }
  7050. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode);
  7051. return this._projectionMatrix;
  7052. }
  7053. var halfWidth = engine.getRenderWidth() / 2.0;
  7054. var halfHeight = engine.getRenderHeight() / 2.0;
  7055. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  7056. return this._projectionMatrix;
  7057. };
  7058. Camera.prototype.dispose = function () {
  7059. // Remove from scene
  7060. this.getScene().removeCamera(this);
  7061. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  7062. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  7063. }
  7064. };
  7065. // Statics
  7066. Camera._PERSPECTIVE_CAMERA = 0;
  7067. Camera._ORTHOGRAPHIC_CAMERA = 1;
  7068. Camera._FOVMODE_VERTICAL_FIXED = 0;
  7069. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  7070. return Camera;
  7071. })(BABYLON.Node);
  7072. BABYLON.Camera = Camera;
  7073. })(BABYLON || (BABYLON = {}));
  7074. //# sourceMappingURL=babylon.camera.js.map
  7075. var BABYLON;
  7076. (function (BABYLON) {
  7077. var TargetCamera = (function (_super) {
  7078. __extends(TargetCamera, _super);
  7079. function TargetCamera(name, position, scene) {
  7080. _super.call(this, name, position, scene);
  7081. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  7082. this.cameraRotation = new BABYLON.Vector2(0, 0);
  7083. this.rotation = new BABYLON.Vector3(0, 0, 0);
  7084. this.speed = 2.0;
  7085. this.noRotationConstraint = false;
  7086. this.lockedTarget = null;
  7087. this._currentTarget = BABYLON.Vector3.Zero();
  7088. this._viewMatrix = BABYLON.Matrix.Zero();
  7089. this._camMatrix = BABYLON.Matrix.Zero();
  7090. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  7091. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  7092. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  7093. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  7094. this._lookAtTemp = BABYLON.Matrix.Zero();
  7095. this._tempMatrix = BABYLON.Matrix.Zero();
  7096. }
  7097. TargetCamera.prototype._getLockedTargetPosition = function () {
  7098. if (!this.lockedTarget) {
  7099. return null;
  7100. }
  7101. return this.lockedTarget.position || this.lockedTarget;
  7102. };
  7103. // Cache
  7104. TargetCamera.prototype._initCache = function () {
  7105. _super.prototype._initCache.call(this);
  7106. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7107. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7108. };
  7109. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  7110. if (!ignoreParentClass) {
  7111. _super.prototype._updateCache.call(this);
  7112. }
  7113. var lockedTargetPosition = this._getLockedTargetPosition();
  7114. if (!lockedTargetPosition) {
  7115. this._cache.lockedTarget = null;
  7116. }
  7117. else {
  7118. if (!this._cache.lockedTarget) {
  7119. this._cache.lockedTarget = lockedTargetPosition.clone();
  7120. }
  7121. else {
  7122. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  7123. }
  7124. }
  7125. this._cache.rotation.copyFrom(this.rotation);
  7126. };
  7127. // Synchronized
  7128. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  7129. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  7130. return false;
  7131. }
  7132. var lockedTargetPosition = this._getLockedTargetPosition();
  7133. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition) && this._cache.rotation.equals(this.rotation);
  7134. };
  7135. // Methods
  7136. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  7137. var engine = this.getEngine();
  7138. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  7139. };
  7140. // Target
  7141. TargetCamera.prototype.setTarget = function (target) {
  7142. this.upVector.normalize();
  7143. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  7144. this._camMatrix.invert();
  7145. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  7146. var vDir = target.subtract(this.position);
  7147. if (vDir.x >= 0.0) {
  7148. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  7149. }
  7150. else {
  7151. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  7152. }
  7153. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  7154. if (isNaN(this.rotation.x)) {
  7155. this.rotation.x = 0;
  7156. }
  7157. if (isNaN(this.rotation.y)) {
  7158. this.rotation.y = 0;
  7159. }
  7160. if (isNaN(this.rotation.z)) {
  7161. this.rotation.z = 0;
  7162. }
  7163. };
  7164. TargetCamera.prototype.getTarget = function () {
  7165. return this._currentTarget;
  7166. };
  7167. TargetCamera.prototype._decideIfNeedsToMove = function () {
  7168. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  7169. };
  7170. TargetCamera.prototype._updatePosition = function () {
  7171. this.position.addInPlace(this.cameraDirection);
  7172. };
  7173. TargetCamera.prototype._update = function () {
  7174. var needToMove = this._decideIfNeedsToMove();
  7175. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  7176. // Move
  7177. if (needToMove) {
  7178. this._updatePosition();
  7179. }
  7180. // Rotate
  7181. if (needToRotate) {
  7182. this.rotation.x += this.cameraRotation.x;
  7183. this.rotation.y += this.cameraRotation.y;
  7184. if (!this.noRotationConstraint) {
  7185. var limit = (Math.PI / 2) * 0.95;
  7186. if (this.rotation.x > limit)
  7187. this.rotation.x = limit;
  7188. if (this.rotation.x < -limit)
  7189. this.rotation.x = -limit;
  7190. }
  7191. }
  7192. // Inertia
  7193. if (needToMove) {
  7194. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  7195. this.cameraDirection.x = 0;
  7196. }
  7197. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  7198. this.cameraDirection.y = 0;
  7199. }
  7200. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  7201. this.cameraDirection.z = 0;
  7202. }
  7203. this.cameraDirection.scaleInPlace(this.inertia);
  7204. }
  7205. if (needToRotate) {
  7206. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  7207. this.cameraRotation.x = 0;
  7208. }
  7209. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  7210. this.cameraRotation.y = 0;
  7211. }
  7212. this.cameraRotation.scaleInPlace(this.inertia);
  7213. }
  7214. };
  7215. TargetCamera.prototype._getViewMatrix = function () {
  7216. if (!this.lockedTarget) {
  7217. // Compute
  7218. if (this.upVector.x !== 0 || this.upVector.y !== 1.0 || this.upVector.z !== 0) {
  7219. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  7220. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  7221. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  7222. this._lookAtTemp.invert();
  7223. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  7224. }
  7225. else {
  7226. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  7227. }
  7228. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  7229. // Computing target and final matrix
  7230. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  7231. }
  7232. else {
  7233. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  7234. }
  7235. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  7236. return this._viewMatrix;
  7237. };
  7238. return TargetCamera;
  7239. })(BABYLON.Camera);
  7240. BABYLON.TargetCamera = TargetCamera;
  7241. })(BABYLON || (BABYLON = {}));
  7242. //# sourceMappingURL=babylon.targetCamera.js.map
  7243. var BABYLON;
  7244. (function (BABYLON) {
  7245. var FollowCamera = (function (_super) {
  7246. __extends(FollowCamera, _super);
  7247. function FollowCamera(name, position, scene) {
  7248. _super.call(this, name, position, scene);
  7249. this.radius = 12;
  7250. this.rotationOffset = 0;
  7251. this.heightOffset = 4;
  7252. this.cameraAcceleration = 0.05;
  7253. this.maxCameraSpeed = 20;
  7254. }
  7255. FollowCamera.prototype.getRadians = function (degrees) {
  7256. return degrees * Math.PI / 180;
  7257. };
  7258. FollowCamera.prototype.follow = function (cameraTarget) {
  7259. if (!cameraTarget)
  7260. return;
  7261. var radians = this.getRadians(this.rotationOffset) + cameraTarget.rotation.y;
  7262. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  7263. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  7264. var dx = targetX - this.position.x;
  7265. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  7266. var dz = (targetZ) - this.position.z;
  7267. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  7268. var vy = dy * this.cameraAcceleration;
  7269. var vz = dz * this.cameraAcceleration * 2;
  7270. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  7271. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  7272. }
  7273. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  7274. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  7275. }
  7276. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  7277. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  7278. }
  7279. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  7280. this.setTarget(cameraTarget.position);
  7281. };
  7282. FollowCamera.prototype._update = function () {
  7283. _super.prototype._update.call(this);
  7284. this.follow(this.target);
  7285. };
  7286. return FollowCamera;
  7287. })(BABYLON.TargetCamera);
  7288. BABYLON.FollowCamera = FollowCamera;
  7289. })(BABYLON || (BABYLON = {}));
  7290. //# sourceMappingURL=babylon.followCamera.js.map
  7291. var BABYLON;
  7292. (function (BABYLON) {
  7293. var FreeCamera = (function (_super) {
  7294. __extends(FreeCamera, _super);
  7295. function FreeCamera(name, position, scene) {
  7296. _super.call(this, name, position, scene);
  7297. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  7298. this.keysUp = [38];
  7299. this.keysDown = [40];
  7300. this.keysLeft = [37];
  7301. this.keysRight = [39];
  7302. this.checkCollisions = false;
  7303. this.applyGravity = false;
  7304. this.angularSensibility = 2000.0;
  7305. this._keys = [];
  7306. this._collider = new BABYLON.Collider();
  7307. this._needMoveForGravity = true;
  7308. this._oldPosition = BABYLON.Vector3.Zero();
  7309. this._diffPosition = BABYLON.Vector3.Zero();
  7310. this._newPosition = BABYLON.Vector3.Zero();
  7311. }
  7312. // Controls
  7313. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  7314. var _this = this;
  7315. var previousPosition;
  7316. var engine = this.getEngine();
  7317. if (this._attachedElement) {
  7318. return;
  7319. }
  7320. this._attachedElement = element;
  7321. if (this._onMouseDown === undefined) {
  7322. this._onMouseDown = function (evt) {
  7323. previousPosition = {
  7324. x: evt.clientX,
  7325. y: evt.clientY
  7326. };
  7327. if (!noPreventDefault) {
  7328. evt.preventDefault();
  7329. }
  7330. };
  7331. this._onMouseUp = function (evt) {
  7332. previousPosition = null;
  7333. if (!noPreventDefault) {
  7334. evt.preventDefault();
  7335. }
  7336. };
  7337. this._onMouseOut = function (evt) {
  7338. previousPosition = null;
  7339. _this._keys = [];
  7340. if (!noPreventDefault) {
  7341. evt.preventDefault();
  7342. }
  7343. };
  7344. this._onMouseMove = function (evt) {
  7345. if (!previousPosition && !engine.isPointerLock) {
  7346. return;
  7347. }
  7348. var offsetX;
  7349. var offsetY;
  7350. if (!engine.isPointerLock) {
  7351. offsetX = evt.clientX - previousPosition.x;
  7352. offsetY = evt.clientY - previousPosition.y;
  7353. }
  7354. else {
  7355. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  7356. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  7357. }
  7358. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  7359. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  7360. previousPosition = {
  7361. x: evt.clientX,
  7362. y: evt.clientY
  7363. };
  7364. if (!noPreventDefault) {
  7365. evt.preventDefault();
  7366. }
  7367. };
  7368. this._onKeyDown = function (evt) {
  7369. 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) {
  7370. var index = _this._keys.indexOf(evt.keyCode);
  7371. if (index === -1) {
  7372. _this._keys.push(evt.keyCode);
  7373. }
  7374. if (!noPreventDefault) {
  7375. evt.preventDefault();
  7376. }
  7377. }
  7378. };
  7379. this._onKeyUp = function (evt) {
  7380. 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) {
  7381. var index = _this._keys.indexOf(evt.keyCode);
  7382. if (index >= 0) {
  7383. _this._keys.splice(index, 1);
  7384. }
  7385. if (!noPreventDefault) {
  7386. evt.preventDefault();
  7387. }
  7388. }
  7389. };
  7390. this._onLostFocus = function () {
  7391. _this._keys = [];
  7392. };
  7393. this._reset = function () {
  7394. _this._keys = [];
  7395. previousPosition = null;
  7396. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  7397. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  7398. };
  7399. }
  7400. element.addEventListener("mousedown", this._onMouseDown, false);
  7401. element.addEventListener("mouseup", this._onMouseUp, false);
  7402. element.addEventListener("mouseout", this._onMouseOut, false);
  7403. element.addEventListener("mousemove", this._onMouseMove, false);
  7404. BABYLON.Tools.RegisterTopRootEvents([
  7405. { name: "keydown", handler: this._onKeyDown },
  7406. { name: "keyup", handler: this._onKeyUp },
  7407. { name: "blur", handler: this._onLostFocus }
  7408. ]);
  7409. };
  7410. FreeCamera.prototype.detachControl = function (element) {
  7411. if (this._attachedElement != element) {
  7412. return;
  7413. }
  7414. element.removeEventListener("mousedown", this._onMouseDown);
  7415. element.removeEventListener("mouseup", this._onMouseUp);
  7416. element.removeEventListener("mouseout", this._onMouseOut);
  7417. element.removeEventListener("mousemove", this._onMouseMove);
  7418. BABYLON.Tools.UnregisterTopRootEvents([
  7419. { name: "keydown", handler: this._onKeyDown },
  7420. { name: "keyup", handler: this._onKeyUp },
  7421. { name: "blur", handler: this._onLostFocus }
  7422. ]);
  7423. this._attachedElement = null;
  7424. if (this._reset) {
  7425. this._reset();
  7426. }
  7427. };
  7428. FreeCamera.prototype._collideWithWorld = function (velocity) {
  7429. var globalPosition;
  7430. if (this.parent) {
  7431. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  7432. }
  7433. else {
  7434. globalPosition = this.position;
  7435. }
  7436. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  7437. this._collider.radius = this.ellipsoid;
  7438. this.getScene()._getNewPosition(this._oldPosition, velocity, this._collider, 3, this._newPosition);
  7439. this._newPosition.subtractToRef(this._oldPosition, this._diffPosition);
  7440. if (this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  7441. this.position.addInPlace(this._diffPosition);
  7442. if (this.onCollide) {
  7443. this.onCollide(this._collider.collidedMesh);
  7444. }
  7445. }
  7446. };
  7447. FreeCamera.prototype._checkInputs = function () {
  7448. if (!this._localDirection) {
  7449. this._localDirection = BABYLON.Vector3.Zero();
  7450. this._transformedDirection = BABYLON.Vector3.Zero();
  7451. }
  7452. for (var index = 0; index < this._keys.length; index++) {
  7453. var keyCode = this._keys[index];
  7454. var speed = this._computeLocalCameraSpeed();
  7455. if (this.keysLeft.indexOf(keyCode) !== -1) {
  7456. this._localDirection.copyFromFloats(-speed, 0, 0);
  7457. }
  7458. else if (this.keysUp.indexOf(keyCode) !== -1) {
  7459. this._localDirection.copyFromFloats(0, 0, speed);
  7460. }
  7461. else if (this.keysRight.indexOf(keyCode) !== -1) {
  7462. this._localDirection.copyFromFloats(speed, 0, 0);
  7463. }
  7464. else if (this.keysDown.indexOf(keyCode) !== -1) {
  7465. this._localDirection.copyFromFloats(0, 0, -speed);
  7466. }
  7467. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  7468. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  7469. this.cameraDirection.addInPlace(this._transformedDirection);
  7470. }
  7471. };
  7472. FreeCamera.prototype._decideIfNeedsToMove = function () {
  7473. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  7474. };
  7475. FreeCamera.prototype._updatePosition = function () {
  7476. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  7477. this._collideWithWorld(this.cameraDirection);
  7478. if (this.applyGravity) {
  7479. var oldPosition = this.position;
  7480. this._collideWithWorld(this.getScene().gravity);
  7481. this._needMoveForGravity = (BABYLON.Vector3.DistanceSquared(oldPosition, this.position) != 0);
  7482. }
  7483. }
  7484. else {
  7485. this.position.addInPlace(this.cameraDirection);
  7486. }
  7487. };
  7488. FreeCamera.prototype._update = function () {
  7489. this._checkInputs();
  7490. _super.prototype._update.call(this);
  7491. };
  7492. return FreeCamera;
  7493. })(BABYLON.TargetCamera);
  7494. BABYLON.FreeCamera = FreeCamera;
  7495. })(BABYLON || (BABYLON = {}));
  7496. //# sourceMappingURL=babylon.freeCamera.js.map
  7497. var BABYLON;
  7498. (function (BABYLON) {
  7499. // We're mainly based on the logic defined into the FreeCamera code
  7500. var TouchCamera = (function (_super) {
  7501. __extends(TouchCamera, _super);
  7502. function TouchCamera(name, position, scene) {
  7503. _super.call(this, name, position, scene);
  7504. this._offsetX = null;
  7505. this._offsetY = null;
  7506. this._pointerCount = 0;
  7507. this._pointerPressed = [];
  7508. this.angularSensibility = 200000.0;
  7509. this.moveSensibility = 500.0;
  7510. }
  7511. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  7512. var _this = this;
  7513. var previousPosition;
  7514. if (this._attachedCanvas) {
  7515. return;
  7516. }
  7517. this._attachedCanvas = canvas;
  7518. if (this._onPointerDown === undefined) {
  7519. this._onPointerDown = function (evt) {
  7520. if (!noPreventDefault) {
  7521. evt.preventDefault();
  7522. }
  7523. _this._pointerPressed.push(evt.pointerId);
  7524. if (_this._pointerPressed.length !== 1) {
  7525. return;
  7526. }
  7527. previousPosition = {
  7528. x: evt.clientX,
  7529. y: evt.clientY
  7530. };
  7531. };
  7532. this._onPointerUp = function (evt) {
  7533. if (!noPreventDefault) {
  7534. evt.preventDefault();
  7535. }
  7536. var index = _this._pointerPressed.indexOf(evt.pointerId);
  7537. if (index === -1) {
  7538. return;
  7539. }
  7540. _this._pointerPressed.splice(index, 1);
  7541. if (index != 0) {
  7542. return;
  7543. }
  7544. previousPosition = null;
  7545. _this._offsetX = null;
  7546. _this._offsetY = null;
  7547. };
  7548. this._onPointerMove = function (evt) {
  7549. if (!noPreventDefault) {
  7550. evt.preventDefault();
  7551. }
  7552. if (!previousPosition) {
  7553. return;
  7554. }
  7555. var index = _this._pointerPressed.indexOf(evt.pointerId);
  7556. if (index != 0) {
  7557. return;
  7558. }
  7559. _this._offsetX = evt.clientX - previousPosition.x;
  7560. _this._offsetY = -(evt.clientY - previousPosition.y);
  7561. };
  7562. this._onLostFocus = function () {
  7563. _this._offsetX = null;
  7564. _this._offsetY = null;
  7565. };
  7566. }
  7567. canvas.addEventListener("pointerdown", this._onPointerDown);
  7568. canvas.addEventListener("pointerup", this._onPointerUp);
  7569. canvas.addEventListener("pointerout", this._onPointerUp);
  7570. canvas.addEventListener("pointermove", this._onPointerMove);
  7571. BABYLON.Tools.RegisterTopRootEvents([
  7572. { name: "blur", handler: this._onLostFocus }
  7573. ]);
  7574. };
  7575. TouchCamera.prototype.detachControl = function (canvas) {
  7576. if (this._attachedCanvas != canvas) {
  7577. return;
  7578. }
  7579. canvas.removeEventListener("pointerdown", this._onPointerDown);
  7580. canvas.removeEventListener("pointerup", this._onPointerUp);
  7581. canvas.removeEventListener("pointerout", this._onPointerUp);
  7582. canvas.removeEventListener("pointermove", this._onPointerMove);
  7583. BABYLON.Tools.UnregisterTopRootEvents([
  7584. { name: "blur", handler: this._onLostFocus }
  7585. ]);
  7586. this._attachedCanvas = null;
  7587. };
  7588. TouchCamera.prototype._checkInputs = function () {
  7589. if (!this._offsetX) {
  7590. return;
  7591. }
  7592. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  7593. if (this._pointerPressed.length > 1) {
  7594. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  7595. }
  7596. else {
  7597. var speed = this._computeLocalCameraSpeed();
  7598. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  7599. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  7600. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  7601. }
  7602. };
  7603. return TouchCamera;
  7604. })(BABYLON.FreeCamera);
  7605. BABYLON.TouchCamera = TouchCamera;
  7606. })(BABYLON || (BABYLON = {}));
  7607. //# sourceMappingURL=babylon.touchCamera.js.map
  7608. var BABYLON;
  7609. (function (BABYLON) {
  7610. // We're mainly based on the logic defined into the FreeCamera code
  7611. var DeviceOrientationCamera = (function (_super) {
  7612. __extends(DeviceOrientationCamera, _super);
  7613. function DeviceOrientationCamera(name, position, scene) {
  7614. var _this = this;
  7615. _super.call(this, name, position, scene);
  7616. this._offsetX = null;
  7617. this._offsetY = null;
  7618. this._orientationGamma = 0;
  7619. this._orientationBeta = 0;
  7620. this._initialOrientationGamma = 0;
  7621. this._initialOrientationBeta = 0;
  7622. this.angularSensibility = 10000.0;
  7623. this.moveSensibility = 50.0;
  7624. window.addEventListener("resize", function () {
  7625. _this._initialOrientationGamma = null;
  7626. }, false);
  7627. }
  7628. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  7629. var _this = this;
  7630. if (this._attachedCanvas) {
  7631. return;
  7632. }
  7633. this._attachedCanvas = canvas;
  7634. if (!this._orientationChanged) {
  7635. this._orientationChanged = function (evt) {
  7636. if (!_this._initialOrientationGamma) {
  7637. _this._initialOrientationGamma = evt.gamma;
  7638. _this._initialOrientationBeta = evt.beta;
  7639. }
  7640. _this._orientationGamma = evt.gamma;
  7641. _this._orientationBeta = evt.beta;
  7642. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  7643. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  7644. };
  7645. }
  7646. window.addEventListener("deviceorientation", this._orientationChanged);
  7647. };
  7648. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  7649. if (this._attachedCanvas != canvas) {
  7650. return;
  7651. }
  7652. window.removeEventListener("deviceorientation", this._orientationChanged);
  7653. this._attachedCanvas = null;
  7654. this._orientationGamma = 0;
  7655. this._orientationBeta = 0;
  7656. this._initialOrientationGamma = 0;
  7657. this._initialOrientationBeta = 0;
  7658. };
  7659. DeviceOrientationCamera.prototype._checkInputs = function () {
  7660. if (!this._offsetX) {
  7661. return;
  7662. }
  7663. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  7664. var speed = this._computeLocalCameraSpeed();
  7665. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  7666. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  7667. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  7668. };
  7669. return DeviceOrientationCamera;
  7670. })(BABYLON.FreeCamera);
  7671. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  7672. })(BABYLON || (BABYLON = {}));
  7673. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  7674. var BABYLON;
  7675. (function (BABYLON) {
  7676. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  7677. var ArcRotateCamera = (function (_super) {
  7678. __extends(ArcRotateCamera, _super);
  7679. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  7680. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  7681. this.alpha = alpha;
  7682. this.beta = beta;
  7683. this.radius = radius;
  7684. this.target = target;
  7685. this.inertialAlphaOffset = 0;
  7686. this.inertialBetaOffset = 0;
  7687. this.inertialRadiusOffset = 0;
  7688. this.lowerAlphaLimit = null;
  7689. this.upperAlphaLimit = null;
  7690. this.lowerBetaLimit = 0.01;
  7691. this.upperBetaLimit = Math.PI;
  7692. this.lowerRadiusLimit = null;
  7693. this.upperRadiusLimit = null;
  7694. this.angularSensibility = 1000.0;
  7695. this.wheelPrecision = 3.0;
  7696. this.pinchPrecision = 2.0;
  7697. this.keysUp = [38];
  7698. this.keysDown = [40];
  7699. this.keysLeft = [37];
  7700. this.keysRight = [39];
  7701. this.zoomOnFactor = 1;
  7702. this.targetScreenOffset = BABYLON.Vector2.Zero();
  7703. this._keys = [];
  7704. this._viewMatrix = new BABYLON.Matrix();
  7705. this.checkCollisions = false;
  7706. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  7707. this._collider = new BABYLON.Collider();
  7708. this._previousPosition = BABYLON.Vector3.Zero();
  7709. this._collisionVelocity = BABYLON.Vector3.Zero();
  7710. this._newPosition = BABYLON.Vector3.Zero();
  7711. if (!this.target) {
  7712. this.target = BABYLON.Vector3.Zero();
  7713. }
  7714. this.getViewMatrix();
  7715. }
  7716. ArcRotateCamera.prototype._getTargetPosition = function () {
  7717. return this.target.position || this.target;
  7718. };
  7719. // Cache
  7720. ArcRotateCamera.prototype._initCache = function () {
  7721. _super.prototype._initCache.call(this);
  7722. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7723. this._cache.alpha = undefined;
  7724. this._cache.beta = undefined;
  7725. this._cache.radius = undefined;
  7726. this._cache.targetScreenOffset = undefined;
  7727. };
  7728. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  7729. if (!ignoreParentClass) {
  7730. _super.prototype._updateCache.call(this);
  7731. }
  7732. this._cache.target.copyFrom(this._getTargetPosition());
  7733. this._cache.alpha = this.alpha;
  7734. this._cache.beta = this.beta;
  7735. this._cache.radius = this.radius;
  7736. this._cache.targetScreenOffset = this.targetScreenOffset.clone();
  7737. };
  7738. // Synchronized
  7739. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  7740. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  7741. return false;
  7742. 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);
  7743. };
  7744. // Methods
  7745. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault) {
  7746. var _this = this;
  7747. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  7748. var previousPinchDistance = 0;
  7749. var pointers = new BABYLON.SmartCollection();
  7750. if (this._attachedElement) {
  7751. return;
  7752. }
  7753. this._attachedElement = element;
  7754. var engine = this.getEngine();
  7755. if (this._onPointerDown === undefined) {
  7756. this._onPointerDown = function (evt) {
  7757. pointers.add(evt.pointerId, { x: evt.clientX, y: evt.clientY, type: evt.pointerType });
  7758. cacheSoloPointer = pointers.item(evt.pointerId);
  7759. if (!noPreventDefault) {
  7760. evt.preventDefault();
  7761. }
  7762. };
  7763. this._onPointerUp = function (evt) {
  7764. cacheSoloPointer = null;
  7765. previousPinchDistance = 0;
  7766. pointers.remove(evt.pointerId);
  7767. if (!noPreventDefault) {
  7768. evt.preventDefault();
  7769. }
  7770. };
  7771. this._onPointerMove = function (evt) {
  7772. if (!noPreventDefault) {
  7773. evt.preventDefault();
  7774. }
  7775. switch (pointers.count) {
  7776. case 1:
  7777. //var offsetX = evt.clientX - pointers.item(evt.pointerId).x;
  7778. //var offsetY = evt.clientY - pointers.item(evt.pointerId).y;
  7779. var offsetX = evt.clientX - cacheSoloPointer.x;
  7780. var offsetY = evt.clientY - cacheSoloPointer.y;
  7781. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  7782. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  7783. //pointers.item(evt.pointerId).x = evt.clientX;
  7784. //pointers.item(evt.pointerId).y = evt.clientY;
  7785. cacheSoloPointer.x = evt.clientX;
  7786. cacheSoloPointer.y = evt.clientY;
  7787. break;
  7788. case 2:
  7789. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be usefull to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  7790. pointers.item(evt.pointerId).x = evt.clientX;
  7791. pointers.item(evt.pointerId).y = evt.clientY;
  7792. var direction = 1;
  7793. var distX = pointers.getItemByIndex(0).x - pointers.getItemByIndex(1).x;
  7794. var distY = pointers.getItemByIndex(0).y - pointers.getItemByIndex(1).y;
  7795. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  7796. if (previousPinchDistance === 0) {
  7797. previousPinchDistance = pinchSquaredDistance;
  7798. return;
  7799. }
  7800. if (pinchSquaredDistance !== previousPinchDistance) {
  7801. if (pinchSquaredDistance > previousPinchDistance) {
  7802. direction = -1;
  7803. }
  7804. _this.inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) / (_this.pinchPrecision * _this.wheelPrecision * _this.angularSensibility);
  7805. previousPinchDistance = pinchSquaredDistance;
  7806. }
  7807. break;
  7808. default:
  7809. if (pointers.item(evt.pointerId)) {
  7810. pointers.item(evt.pointerId).x = evt.clientX;
  7811. pointers.item(evt.pointerId).y = evt.clientY;
  7812. }
  7813. }
  7814. };
  7815. this._onMouseMove = function (evt) {
  7816. if (!engine.isPointerLock) {
  7817. return;
  7818. }
  7819. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  7820. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  7821. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  7822. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  7823. if (!noPreventDefault) {
  7824. evt.preventDefault();
  7825. }
  7826. };
  7827. this._wheel = function (event) {
  7828. var delta = 0;
  7829. if (event.wheelDelta) {
  7830. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  7831. }
  7832. else if (event.detail) {
  7833. delta = -event.detail / _this.wheelPrecision;
  7834. }
  7835. if (delta)
  7836. _this.inertialRadiusOffset += delta;
  7837. if (event.preventDefault) {
  7838. if (!noPreventDefault) {
  7839. event.preventDefault();
  7840. }
  7841. }
  7842. };
  7843. this._onKeyDown = function (evt) {
  7844. 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) {
  7845. var index = _this._keys.indexOf(evt.keyCode);
  7846. if (index === -1) {
  7847. _this._keys.push(evt.keyCode);
  7848. }
  7849. if (evt.preventDefault) {
  7850. if (!noPreventDefault) {
  7851. evt.preventDefault();
  7852. }
  7853. }
  7854. }
  7855. };
  7856. this._onKeyUp = function (evt) {
  7857. 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) {
  7858. var index = _this._keys.indexOf(evt.keyCode);
  7859. if (index >= 0) {
  7860. _this._keys.splice(index, 1);
  7861. }
  7862. if (evt.preventDefault) {
  7863. if (!noPreventDefault) {
  7864. evt.preventDefault();
  7865. }
  7866. }
  7867. }
  7868. };
  7869. this._onLostFocus = function () {
  7870. _this._keys = [];
  7871. pointers.empty();
  7872. previousPinchDistance = 0;
  7873. cacheSoloPointer = null;
  7874. };
  7875. this._onGestureStart = function (e) {
  7876. if (window.MSGesture === undefined) {
  7877. return;
  7878. }
  7879. if (!_this._MSGestureHandler) {
  7880. _this._MSGestureHandler = new MSGesture();
  7881. _this._MSGestureHandler.target = element;
  7882. }
  7883. _this._MSGestureHandler.addPointer(e.pointerId);
  7884. };
  7885. this._onGesture = function (e) {
  7886. _this.radius *= e.scale;
  7887. if (e.preventDefault) {
  7888. if (!noPreventDefault) {
  7889. e.stopPropagation();
  7890. e.preventDefault();
  7891. }
  7892. }
  7893. };
  7894. this._reset = function () {
  7895. _this._keys = [];
  7896. _this.inertialAlphaOffset = 0;
  7897. _this.inertialBetaOffset = 0;
  7898. _this.inertialRadiusOffset = 0;
  7899. pointers.empty();
  7900. previousPinchDistance = 0;
  7901. cacheSoloPointer = null;
  7902. };
  7903. }
  7904. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  7905. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  7906. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  7907. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  7908. element.addEventListener("mousemove", this._onMouseMove, false);
  7909. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  7910. element.addEventListener("MSGestureChange", this._onGesture, false);
  7911. element.addEventListener('mousewheel', this._wheel, false);
  7912. element.addEventListener('DOMMouseScroll', this._wheel, false);
  7913. BABYLON.Tools.RegisterTopRootEvents([
  7914. { name: "keydown", handler: this._onKeyDown },
  7915. { name: "keyup", handler: this._onKeyUp },
  7916. { name: "blur", handler: this._onLostFocus }
  7917. ]);
  7918. };
  7919. ArcRotateCamera.prototype.detachControl = function (element) {
  7920. if (this._attachedElement !== element) {
  7921. return;
  7922. }
  7923. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  7924. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  7925. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  7926. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  7927. element.removeEventListener("mousemove", this._onMouseMove);
  7928. element.removeEventListener("MSPointerDown", this._onGestureStart);
  7929. element.removeEventListener("MSGestureChange", this._onGesture);
  7930. element.removeEventListener('mousewheel', this._wheel);
  7931. element.removeEventListener('DOMMouseScroll', this._wheel);
  7932. BABYLON.Tools.UnregisterTopRootEvents([
  7933. { name: "keydown", handler: this._onKeyDown },
  7934. { name: "keyup", handler: this._onKeyUp },
  7935. { name: "blur", handler: this._onLostFocus }
  7936. ]);
  7937. this._MSGestureHandler = null;
  7938. this._attachedElement = null;
  7939. if (this._reset) {
  7940. this._reset();
  7941. }
  7942. };
  7943. ArcRotateCamera.prototype._update = function () {
  7944. for (var index = 0; index < this._keys.length; index++) {
  7945. var keyCode = this._keys[index];
  7946. if (this.keysLeft.indexOf(keyCode) !== -1) {
  7947. this.inertialAlphaOffset -= 0.01;
  7948. }
  7949. else if (this.keysUp.indexOf(keyCode) !== -1) {
  7950. this.inertialBetaOffset -= 0.01;
  7951. }
  7952. else if (this.keysRight.indexOf(keyCode) !== -1) {
  7953. this.inertialAlphaOffset += 0.01;
  7954. }
  7955. else if (this.keysDown.indexOf(keyCode) !== -1) {
  7956. this.inertialBetaOffset += 0.01;
  7957. }
  7958. }
  7959. // Inertia
  7960. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset != 0) {
  7961. this.alpha += this.inertialAlphaOffset;
  7962. this.beta += this.inertialBetaOffset;
  7963. this.radius -= this.inertialRadiusOffset;
  7964. this.inertialAlphaOffset *= this.inertia;
  7965. this.inertialBetaOffset *= this.inertia;
  7966. this.inertialRadiusOffset *= this.inertia;
  7967. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  7968. this.inertialAlphaOffset = 0;
  7969. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  7970. this.inertialBetaOffset = 0;
  7971. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  7972. this.inertialRadiusOffset = 0;
  7973. }
  7974. // Limits
  7975. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  7976. this.alpha = this.lowerAlphaLimit;
  7977. }
  7978. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  7979. this.alpha = this.upperAlphaLimit;
  7980. }
  7981. if (this.lowerBetaLimit && this.beta < this.lowerBetaLimit) {
  7982. this.beta = this.lowerBetaLimit;
  7983. }
  7984. if (this.upperBetaLimit && this.beta > this.upperBetaLimit) {
  7985. this.beta = this.upperBetaLimit;
  7986. }
  7987. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  7988. this.radius = this.lowerRadiusLimit;
  7989. }
  7990. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  7991. this.radius = this.upperRadiusLimit;
  7992. }
  7993. };
  7994. ArcRotateCamera.prototype.setPosition = function (position) {
  7995. var radiusv3 = position.subtract(this._getTargetPosition());
  7996. this.radius = radiusv3.length();
  7997. // Alpha
  7998. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  7999. if (radiusv3.z < 0) {
  8000. this.alpha = 2 * Math.PI - this.alpha;
  8001. }
  8002. // Beta
  8003. this.beta = Math.acos(radiusv3.y / this.radius);
  8004. };
  8005. ArcRotateCamera.prototype._getViewMatrix = function () {
  8006. // Compute
  8007. var cosa = Math.cos(this.alpha);
  8008. var sina = Math.sin(this.alpha);
  8009. var cosb = Math.cos(this.beta);
  8010. var sinb = Math.sin(this.beta);
  8011. var target = this._getTargetPosition();
  8012. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this.position);
  8013. if (this.checkCollisions) {
  8014. this._collider.radius = this.collisionRadius;
  8015. this.position.subtractToRef(this._previousPosition, this._collisionVelocity);
  8016. this.getScene()._getNewPosition(this._previousPosition, this._collisionVelocity, this._collider, 3, this._newPosition);
  8017. if (!this._newPosition.equalsWithEpsilon(this.position)) {
  8018. this.position.copyFrom(this._previousPosition);
  8019. this.alpha = this._previousAlpha;
  8020. this.beta = this._previousBeta;
  8021. this.radius = this._previousRadius;
  8022. if (this.onCollide) {
  8023. this.onCollide(this._collider.collidedMesh);
  8024. }
  8025. }
  8026. }
  8027. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._viewMatrix);
  8028. this._previousAlpha = this.alpha;
  8029. this._previousBeta = this.beta;
  8030. this._previousRadius = this.radius;
  8031. this._previousPosition.copyFrom(this.position);
  8032. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  8033. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  8034. return this._viewMatrix;
  8035. };
  8036. ArcRotateCamera.prototype.zoomOn = function (meshes) {
  8037. meshes = meshes || this.getScene().meshes;
  8038. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  8039. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  8040. this.radius = distance * this.zoomOnFactor;
  8041. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance });
  8042. };
  8043. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance) {
  8044. var meshesOrMinMaxVector;
  8045. var distance;
  8046. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  8047. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  8048. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  8049. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  8050. }
  8051. else {
  8052. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  8053. distance = meshesOrMinMaxVectorAndDistance.distance;
  8054. }
  8055. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  8056. this.maxZ = distance * 2;
  8057. };
  8058. return ArcRotateCamera;
  8059. })(BABYLON.Camera);
  8060. BABYLON.ArcRotateCamera = ArcRotateCamera;
  8061. })(BABYLON || (BABYLON = {}));
  8062. //# sourceMappingURL=babylon.arcRotateCamera.js.mapvar BABYLON;
  8063. (function (BABYLON) {
  8064. /**
  8065. * Represents a scene to be rendered by the engine.
  8066. * @see http://doc.babylonjs.com/page.php?p=21911
  8067. */
  8068. var Scene = (function () {
  8069. /**
  8070. * @constructor
  8071. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  8072. */
  8073. function Scene(engine) {
  8074. // Members
  8075. this.autoClear = true;
  8076. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  8077. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  8078. this.forceWireframe = false;
  8079. this.forcePointsCloud = false;
  8080. this.forceShowBoundingBoxes = false;
  8081. this.animationsEnabled = true;
  8082. 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
  8083. // Fog
  8084. /**
  8085. * is fog enabled on this scene.
  8086. * @type {boolean}
  8087. */
  8088. this.fogEnabled = true;
  8089. this.fogMode = Scene.FOGMODE_NONE;
  8090. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  8091. this.fogDensity = 0.1;
  8092. this.fogStart = 0;
  8093. this.fogEnd = 1000.0;
  8094. // Lights
  8095. /**
  8096. * is shadow enabled on this scene.
  8097. * @type {boolean}
  8098. */
  8099. this.shadowsEnabled = true;
  8100. /**
  8101. * is light enabled on this scene.
  8102. * @type {boolean}
  8103. */
  8104. this.lightsEnabled = true;
  8105. /**
  8106. * All of the lights added to this scene.
  8107. * @see BABYLON.Light
  8108. * @type {BABYLON.Light[]}
  8109. */
  8110. this.lights = new Array();
  8111. // Cameras
  8112. /**
  8113. * All of the cameras added to this scene.
  8114. * @see BABYLON.Camera
  8115. * @type {BABYLON.Camera[]}
  8116. */
  8117. this.cameras = new Array();
  8118. this.activeCameras = new Array();
  8119. // Meshes
  8120. /**
  8121. * All of the (abstract) meshes added to this scene.
  8122. * @see BABYLON.AbstractMesh
  8123. * @type {BABYLON.AbstractMesh[]}
  8124. */
  8125. this.meshes = new Array();
  8126. // Geometries
  8127. this._geometries = new Array();
  8128. this.materials = new Array();
  8129. this.multiMaterials = new Array();
  8130. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  8131. // Textures
  8132. this.texturesEnabled = true;
  8133. this.textures = new Array();
  8134. // Particles
  8135. this.particlesEnabled = true;
  8136. this.particleSystems = new Array();
  8137. // Sprites
  8138. this.spritesEnabled = true;
  8139. this.spriteManagers = new Array();
  8140. // Layers
  8141. this.layers = new Array();
  8142. // Skeletons
  8143. this.skeletonsEnabled = true;
  8144. this.skeletons = new Array();
  8145. // Lens flares
  8146. this.lensFlaresEnabled = true;
  8147. this.lensFlareSystems = new Array();
  8148. // Collisions
  8149. this.collisionsEnabled = true;
  8150. this.gravity = new BABYLON.Vector3(0, -9.0, 0);
  8151. // Postprocesses
  8152. this.postProcessesEnabled = true;
  8153. // Customs render targets
  8154. this.renderTargetsEnabled = true;
  8155. this.dumpNextRenderTargets = false;
  8156. this.customRenderTargets = new Array();
  8157. // Imported meshes
  8158. this.importedMeshesFiles = new Array();
  8159. this._actionManagers = new Array();
  8160. this._meshesForIntersections = new BABYLON.SmartArray(256);
  8161. // Procedural textures
  8162. this.proceduralTexturesEnabled = true;
  8163. this._proceduralTextures = new Array();
  8164. this.soundTracks = new Array();
  8165. this._audioEnabled = true;
  8166. this._headphone = false;
  8167. this._totalVertices = 0;
  8168. this._activeVertices = 0;
  8169. this._activeParticles = 0;
  8170. this._lastFrameDuration = 0;
  8171. this._evaluateActiveMeshesDuration = 0;
  8172. this._renderTargetsDuration = 0;
  8173. this._particlesDuration = 0;
  8174. this._renderDuration = 0;
  8175. this._spritesDuration = 0;
  8176. this._animationRatio = 0;
  8177. this._renderId = 0;
  8178. this._executeWhenReadyTimeoutId = -1;
  8179. this._toBeDisposed = new BABYLON.SmartArray(256);
  8180. this._onReadyCallbacks = new Array();
  8181. this._pendingData = []; //ANY
  8182. this._onBeforeRenderCallbacks = new Array();
  8183. this._onAfterRenderCallbacks = new Array();
  8184. this._activeMeshes = new BABYLON.SmartArray(256);
  8185. this._processedMaterials = new BABYLON.SmartArray(256);
  8186. this._renderTargets = new BABYLON.SmartArray(256);
  8187. this._activeParticleSystems = new BABYLON.SmartArray(256);
  8188. this._activeSkeletons = new BABYLON.SmartArray(32);
  8189. this._activeBones = 0;
  8190. this._activeAnimatables = new Array();
  8191. this._transformMatrix = BABYLON.Matrix.Zero();
  8192. this._scaledPosition = BABYLON.Vector3.Zero();
  8193. this._scaledVelocity = BABYLON.Vector3.Zero();
  8194. this._engine = engine;
  8195. engine.scenes.push(this);
  8196. this._renderingManager = new BABYLON.RenderingManager(this);
  8197. this.postProcessManager = new BABYLON.PostProcessManager(this);
  8198. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  8199. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  8200. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  8201. this.attachControl();
  8202. this._debugLayer = new BABYLON.DebugLayer(this);
  8203. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  8204. //simplification queue
  8205. this.simplificationQueue = new BABYLON.SimplificationQueue();
  8206. }
  8207. Object.defineProperty(Scene, "FOGMODE_NONE", {
  8208. get: function () {
  8209. return Scene._FOGMODE_NONE;
  8210. },
  8211. enumerable: true,
  8212. configurable: true
  8213. });
  8214. Object.defineProperty(Scene, "FOGMODE_EXP", {
  8215. get: function () {
  8216. return Scene._FOGMODE_EXP;
  8217. },
  8218. enumerable: true,
  8219. configurable: true
  8220. });
  8221. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  8222. get: function () {
  8223. return Scene._FOGMODE_EXP2;
  8224. },
  8225. enumerable: true,
  8226. configurable: true
  8227. });
  8228. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  8229. get: function () {
  8230. return Scene._FOGMODE_LINEAR;
  8231. },
  8232. enumerable: true,
  8233. configurable: true
  8234. });
  8235. Object.defineProperty(Scene.prototype, "debugLayer", {
  8236. // Properties
  8237. get: function () {
  8238. return this._debugLayer;
  8239. },
  8240. enumerable: true,
  8241. configurable: true
  8242. });
  8243. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  8244. /**
  8245. * The mesh that is currently under the pointer.
  8246. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  8247. */
  8248. get: function () {
  8249. return this._meshUnderPointer;
  8250. },
  8251. enumerable: true,
  8252. configurable: true
  8253. });
  8254. Object.defineProperty(Scene.prototype, "pointerX", {
  8255. /**
  8256. * Current on-screen X position of the pointer
  8257. * @return {number} X position of the pointer
  8258. */
  8259. get: function () {
  8260. return this._pointerX;
  8261. },
  8262. enumerable: true,
  8263. configurable: true
  8264. });
  8265. Object.defineProperty(Scene.prototype, "pointerY", {
  8266. /**
  8267. * Current on-screen Y position of the pointer
  8268. * @return {number} Y position of the pointer
  8269. */
  8270. get: function () {
  8271. return this._pointerY;
  8272. },
  8273. enumerable: true,
  8274. configurable: true
  8275. });
  8276. Scene.prototype.getCachedMaterial = function () {
  8277. return this._cachedMaterial;
  8278. };
  8279. Scene.prototype.getBoundingBoxRenderer = function () {
  8280. return this._boundingBoxRenderer;
  8281. };
  8282. Scene.prototype.getOutlineRenderer = function () {
  8283. return this._outlineRenderer;
  8284. };
  8285. Scene.prototype.getEngine = function () {
  8286. return this._engine;
  8287. };
  8288. Scene.prototype.getTotalVertices = function () {
  8289. return this._totalVertices;
  8290. };
  8291. Scene.prototype.getActiveVertices = function () {
  8292. return this._activeVertices;
  8293. };
  8294. Scene.prototype.getActiveParticles = function () {
  8295. return this._activeParticles;
  8296. };
  8297. Scene.prototype.getActiveBones = function () {
  8298. return this._activeBones;
  8299. };
  8300. // Stats
  8301. Scene.prototype.getLastFrameDuration = function () {
  8302. return this._lastFrameDuration;
  8303. };
  8304. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  8305. return this._evaluateActiveMeshesDuration;
  8306. };
  8307. Scene.prototype.getActiveMeshes = function () {
  8308. return this._activeMeshes;
  8309. };
  8310. Scene.prototype.getRenderTargetsDuration = function () {
  8311. return this._renderTargetsDuration;
  8312. };
  8313. Scene.prototype.getRenderDuration = function () {
  8314. return this._renderDuration;
  8315. };
  8316. Scene.prototype.getParticlesDuration = function () {
  8317. return this._particlesDuration;
  8318. };
  8319. Scene.prototype.getSpritesDuration = function () {
  8320. return this._spritesDuration;
  8321. };
  8322. Scene.prototype.getAnimationRatio = function () {
  8323. return this._animationRatio;
  8324. };
  8325. Scene.prototype.getRenderId = function () {
  8326. return this._renderId;
  8327. };
  8328. Scene.prototype.incrementRenderId = function () {
  8329. this._renderId++;
  8330. };
  8331. Scene.prototype._updatePointerPosition = function (evt) {
  8332. var canvasRect = this._engine.getRenderingCanvasClientRect();
  8333. this._pointerX = evt.clientX - canvasRect.left;
  8334. this._pointerY = evt.clientY - canvasRect.top;
  8335. if (this.cameraToUseForPointers) {
  8336. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  8337. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  8338. }
  8339. };
  8340. // Pointers handling
  8341. Scene.prototype.attachControl = function () {
  8342. var _this = this;
  8343. this._onPointerMove = function (evt) {
  8344. var canvas = _this._engine.getRenderingCanvas();
  8345. _this._updatePointerPosition(evt);
  8346. 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);
  8347. if (pickResult.hit) {
  8348. _this._meshUnderPointer = pickResult.pickedMesh;
  8349. _this.setPointerOverMesh(pickResult.pickedMesh);
  8350. canvas.style.cursor = "pointer";
  8351. }
  8352. else {
  8353. _this.setPointerOverMesh(null);
  8354. canvas.style.cursor = "";
  8355. _this._meshUnderPointer = null;
  8356. }
  8357. };
  8358. this._onPointerDown = function (evt) {
  8359. var predicate = null;
  8360. if (!_this.onPointerDown) {
  8361. predicate = function (mesh) {
  8362. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  8363. };
  8364. }
  8365. _this._updatePointerPosition(evt);
  8366. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  8367. if (pickResult.hit) {
  8368. if (pickResult.pickedMesh.actionManager) {
  8369. switch (evt.button) {
  8370. case 0:
  8371. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  8372. break;
  8373. case 1:
  8374. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  8375. break;
  8376. case 2:
  8377. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  8378. break;
  8379. }
  8380. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  8381. }
  8382. }
  8383. if (_this.onPointerDown) {
  8384. _this.onPointerDown(evt, pickResult);
  8385. }
  8386. };
  8387. this._onKeyDown = function (evt) {
  8388. if (_this.actionManager) {
  8389. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  8390. }
  8391. };
  8392. this._onKeyUp = function (evt) {
  8393. if (_this.actionManager) {
  8394. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  8395. }
  8396. };
  8397. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  8398. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  8399. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  8400. BABYLON.Tools.RegisterTopRootEvents([
  8401. { name: "keydown", handler: this._onKeyDown },
  8402. { name: "keyup", handler: this._onKeyUp }
  8403. ]);
  8404. };
  8405. Scene.prototype.detachControl = function () {
  8406. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  8407. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  8408. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  8409. BABYLON.Tools.UnregisterTopRootEvents([
  8410. { name: "keydown", handler: this._onKeyDown },
  8411. { name: "keyup", handler: this._onKeyUp }
  8412. ]);
  8413. };
  8414. // Ready
  8415. Scene.prototype.isReady = function () {
  8416. if (this._pendingData.length > 0) {
  8417. return false;
  8418. }
  8419. for (var index = 0; index < this._geometries.length; index++) {
  8420. var geometry = this._geometries[index];
  8421. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  8422. return false;
  8423. }
  8424. }
  8425. for (index = 0; index < this.meshes.length; index++) {
  8426. var mesh = this.meshes[index];
  8427. if (!mesh.isReady()) {
  8428. return false;
  8429. }
  8430. var mat = mesh.material;
  8431. if (mat) {
  8432. if (!mat.isReady(mesh)) {
  8433. return false;
  8434. }
  8435. }
  8436. }
  8437. return true;
  8438. };
  8439. Scene.prototype.resetCachedMaterial = function () {
  8440. this._cachedMaterial = null;
  8441. };
  8442. Scene.prototype.registerBeforeRender = function (func) {
  8443. this._onBeforeRenderCallbacks.push(func);
  8444. };
  8445. Scene.prototype.unregisterBeforeRender = function (func) {
  8446. var index = this._onBeforeRenderCallbacks.indexOf(func);
  8447. if (index > -1) {
  8448. this._onBeforeRenderCallbacks.splice(index, 1);
  8449. }
  8450. };
  8451. Scene.prototype.registerAfterRender = function (func) {
  8452. this._onAfterRenderCallbacks.push(func);
  8453. };
  8454. Scene.prototype.unregisterAfterRender = function (func) {
  8455. var index = this._onAfterRenderCallbacks.indexOf(func);
  8456. if (index > -1) {
  8457. this._onAfterRenderCallbacks.splice(index, 1);
  8458. }
  8459. };
  8460. Scene.prototype._addPendingData = function (data) {
  8461. this._pendingData.push(data);
  8462. };
  8463. Scene.prototype._removePendingData = function (data) {
  8464. var index = this._pendingData.indexOf(data);
  8465. if (index !== -1) {
  8466. this._pendingData.splice(index, 1);
  8467. }
  8468. };
  8469. Scene.prototype.getWaitingItemsCount = function () {
  8470. return this._pendingData.length;
  8471. };
  8472. /**
  8473. * Registers a function to be executed when the scene is ready.
  8474. * @param {Function} func - the function to be executed.
  8475. */
  8476. Scene.prototype.executeWhenReady = function (func) {
  8477. var _this = this;
  8478. this._onReadyCallbacks.push(func);
  8479. if (this._executeWhenReadyTimeoutId !== -1) {
  8480. return;
  8481. }
  8482. this._executeWhenReadyTimeoutId = setTimeout(function () {
  8483. _this._checkIsReady();
  8484. }, 150);
  8485. };
  8486. Scene.prototype._checkIsReady = function () {
  8487. var _this = this;
  8488. if (this.isReady()) {
  8489. this._onReadyCallbacks.forEach(function (func) {
  8490. func();
  8491. });
  8492. this._onReadyCallbacks = [];
  8493. this._executeWhenReadyTimeoutId = -1;
  8494. return;
  8495. }
  8496. this._executeWhenReadyTimeoutId = setTimeout(function () {
  8497. _this._checkIsReady();
  8498. }, 150);
  8499. };
  8500. // Animations
  8501. /**
  8502. * Will start the animation sequence of a given target
  8503. * @param target - the target
  8504. * @param {number} from - from which frame should animation start
  8505. * @param {number} to - till which frame should animation run.
  8506. * @param {boolean} [loop] - should the animation loop
  8507. * @param {number} [speedRatio] - the speed in which to run the animation
  8508. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  8509. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  8510. * @return {BABYLON.Animatable} the animatable object created for this animation
  8511. * @see BABYLON.Animatable
  8512. * @see http://doc.babylonjs.com/page.php?p=22081
  8513. */
  8514. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  8515. if (speedRatio === undefined) {
  8516. speedRatio = 1.0;
  8517. }
  8518. this.stopAnimation(target);
  8519. if (!animatable) {
  8520. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  8521. }
  8522. // Local animations
  8523. if (target.animations) {
  8524. animatable.appendAnimations(target, target.animations);
  8525. }
  8526. // Children animations
  8527. if (target.getAnimatables) {
  8528. var animatables = target.getAnimatables();
  8529. for (var index = 0; index < animatables.length; index++) {
  8530. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  8531. }
  8532. }
  8533. return animatable;
  8534. };
  8535. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  8536. if (speedRatio === undefined) {
  8537. speedRatio = 1.0;
  8538. }
  8539. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  8540. return animatable;
  8541. };
  8542. Scene.prototype.getAnimatableByTarget = function (target) {
  8543. for (var index = 0; index < this._activeAnimatables.length; index++) {
  8544. if (this._activeAnimatables[index].target === target) {
  8545. return this._activeAnimatables[index];
  8546. }
  8547. }
  8548. return null;
  8549. };
  8550. /**
  8551. * Will stop the animation of the given target
  8552. * @param target - the target
  8553. * @see beginAnimation
  8554. */
  8555. Scene.prototype.stopAnimation = function (target) {
  8556. var animatable = this.getAnimatableByTarget(target);
  8557. if (animatable) {
  8558. animatable.stop();
  8559. }
  8560. };
  8561. Scene.prototype._animate = function () {
  8562. if (!this.animationsEnabled) {
  8563. return;
  8564. }
  8565. if (!this._animationStartDate) {
  8566. this._animationStartDate = BABYLON.Tools.Now;
  8567. }
  8568. // Getting time
  8569. var now = BABYLON.Tools.Now;
  8570. var delay = now - this._animationStartDate;
  8571. for (var index = 0; index < this._activeAnimatables.length; index++) {
  8572. this._activeAnimatables[index]._animate(delay);
  8573. }
  8574. };
  8575. // Matrix
  8576. Scene.prototype.getViewMatrix = function () {
  8577. return this._viewMatrix;
  8578. };
  8579. Scene.prototype.getProjectionMatrix = function () {
  8580. return this._projectionMatrix;
  8581. };
  8582. Scene.prototype.getTransformMatrix = function () {
  8583. return this._transformMatrix;
  8584. };
  8585. Scene.prototype.setTransformMatrix = function (view, projection) {
  8586. this._viewMatrix = view;
  8587. this._projectionMatrix = projection;
  8588. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  8589. };
  8590. // Methods
  8591. Scene.prototype.addMesh = function (newMesh) {
  8592. var position = this.meshes.push(newMesh);
  8593. if (this.onNewMeshAdded) {
  8594. this.onNewMeshAdded(newMesh, position, this);
  8595. }
  8596. };
  8597. Scene.prototype.removeMesh = function (toRemove) {
  8598. var index = this.meshes.indexOf(toRemove);
  8599. if (index !== -1) {
  8600. // Remove from the scene if mesh found
  8601. this.meshes.splice(index, 1);
  8602. }
  8603. if (this.onMeshRemoved) {
  8604. this.onMeshRemoved(toRemove);
  8605. }
  8606. return index;
  8607. };
  8608. Scene.prototype.removeLight = function (toRemove) {
  8609. var index = this.lights.indexOf(toRemove);
  8610. if (index !== -1) {
  8611. // Remove from the scene if mesh found
  8612. this.lights.splice(index, 1);
  8613. }
  8614. if (this.onLightRemoved) {
  8615. this.onLightRemoved(toRemove);
  8616. }
  8617. return index;
  8618. };
  8619. Scene.prototype.removeCamera = function (toRemove) {
  8620. var index = this.cameras.indexOf(toRemove);
  8621. if (index !== -1) {
  8622. // Remove from the scene if mesh found
  8623. this.cameras.splice(index, 1);
  8624. }
  8625. if (this.onCameraRemoved) {
  8626. this.onCameraRemoved(toRemove);
  8627. }
  8628. return index;
  8629. };
  8630. Scene.prototype.addLight = function (newLight) {
  8631. var position = this.lights.push(newLight);
  8632. if (this.onNewLightAdded) {
  8633. this.onNewLightAdded(newLight, position, this);
  8634. }
  8635. };
  8636. Scene.prototype.addCamera = function (newCamera) {
  8637. var position = this.cameras.push(newCamera);
  8638. if (this.onNewCameraAdded) {
  8639. this.onNewCameraAdded(newCamera, position, this);
  8640. }
  8641. };
  8642. /**
  8643. * sets the active camera of the scene using its ID
  8644. * @param {string} id - the camera's ID
  8645. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  8646. * @see activeCamera
  8647. */
  8648. Scene.prototype.setActiveCameraByID = function (id) {
  8649. var camera = this.getCameraByID(id);
  8650. if (camera) {
  8651. this.activeCamera = camera;
  8652. return camera;
  8653. }
  8654. return null;
  8655. };
  8656. /**
  8657. * sets the active camera of the scene using its name
  8658. * @param {string} name - the camera's name
  8659. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  8660. * @see activeCamera
  8661. */
  8662. Scene.prototype.setActiveCameraByName = function (name) {
  8663. var camera = this.getCameraByName(name);
  8664. if (camera) {
  8665. this.activeCamera = camera;
  8666. return camera;
  8667. }
  8668. return null;
  8669. };
  8670. /**
  8671. * get a material using its id
  8672. * @param {string} the material's ID
  8673. * @return {BABYLON.Material|null} the material or null if none found.
  8674. */
  8675. Scene.prototype.getMaterialByID = function (id) {
  8676. for (var index = 0; index < this.materials.length; index++) {
  8677. if (this.materials[index].id === id) {
  8678. return this.materials[index];
  8679. }
  8680. }
  8681. return null;
  8682. };
  8683. /**
  8684. * get a material using its name
  8685. * @param {string} the material's name
  8686. * @return {BABYLON.Material|null} the material or null if none found.
  8687. */
  8688. Scene.prototype.getMaterialByName = function (name) {
  8689. for (var index = 0; index < this.materials.length; index++) {
  8690. if (this.materials[index].name === name) {
  8691. return this.materials[index];
  8692. }
  8693. }
  8694. return null;
  8695. };
  8696. Scene.prototype.getCameraByID = function (id) {
  8697. for (var index = 0; index < this.cameras.length; index++) {
  8698. if (this.cameras[index].id === id) {
  8699. return this.cameras[index];
  8700. }
  8701. }
  8702. return null;
  8703. };
  8704. /**
  8705. * get a camera using its name
  8706. * @param {string} the camera's name
  8707. * @return {BABYLON.Camera|null} the camera or null if none found.
  8708. */
  8709. Scene.prototype.getCameraByName = function (name) {
  8710. for (var index = 0; index < this.cameras.length; index++) {
  8711. if (this.cameras[index].name === name) {
  8712. return this.cameras[index];
  8713. }
  8714. }
  8715. return null;
  8716. };
  8717. /**
  8718. * get a light node using its name
  8719. * @param {string} the light's name
  8720. * @return {BABYLON.Light|null} the light or null if none found.
  8721. */
  8722. Scene.prototype.getLightByName = function (name) {
  8723. for (var index = 0; index < this.lights.length; index++) {
  8724. if (this.lights[index].name === name) {
  8725. return this.lights[index];
  8726. }
  8727. }
  8728. return null;
  8729. };
  8730. /**
  8731. * get a light node using its ID
  8732. * @param {string} the light's id
  8733. * @return {BABYLON.Light|null} the light or null if none found.
  8734. */
  8735. Scene.prototype.getLightByID = function (id) {
  8736. for (var index = 0; index < this.lights.length; index++) {
  8737. if (this.lights[index].id === id) {
  8738. return this.lights[index];
  8739. }
  8740. }
  8741. return null;
  8742. };
  8743. /**
  8744. * get a geometry using its ID
  8745. * @param {string} the geometry's id
  8746. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  8747. */
  8748. Scene.prototype.getGeometryByID = function (id) {
  8749. for (var index = 0; index < this._geometries.length; index++) {
  8750. if (this._geometries[index].id === id) {
  8751. return this._geometries[index];
  8752. }
  8753. }
  8754. return null;
  8755. };
  8756. /**
  8757. * add a new geometry to this scene.
  8758. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  8759. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  8760. * @return {boolean} was the geometry added or not
  8761. */
  8762. Scene.prototype.pushGeometry = function (geometry, force) {
  8763. if (!force && this.getGeometryByID(geometry.id)) {
  8764. return false;
  8765. }
  8766. this._geometries.push(geometry);
  8767. return true;
  8768. };
  8769. Scene.prototype.getGeometries = function () {
  8770. return this._geometries;
  8771. };
  8772. /**
  8773. * Get a the first added mesh found of a given ID
  8774. * @param {string} id - the id to search for
  8775. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  8776. */
  8777. Scene.prototype.getMeshByID = function (id) {
  8778. for (var index = 0; index < this.meshes.length; index++) {
  8779. if (this.meshes[index].id === id) {
  8780. return this.meshes[index];
  8781. }
  8782. }
  8783. return null;
  8784. };
  8785. /**
  8786. * Get a the last added mesh found of a given ID
  8787. * @param {string} id - the id to search for
  8788. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  8789. */
  8790. Scene.prototype.getLastMeshByID = function (id) {
  8791. for (var index = this.meshes.length - 1; index >= 0; index--) {
  8792. if (this.meshes[index].id === id) {
  8793. return this.meshes[index];
  8794. }
  8795. }
  8796. return null;
  8797. };
  8798. /**
  8799. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  8800. * @param {string} id - the id to search for
  8801. * @return {BABYLON.Node|null} the node found or null if not found at all.
  8802. */
  8803. Scene.prototype.getLastEntryByID = function (id) {
  8804. for (var index = this.meshes.length - 1; index >= 0; index--) {
  8805. if (this.meshes[index].id === id) {
  8806. return this.meshes[index];
  8807. }
  8808. }
  8809. for (index = this.cameras.length - 1; index >= 0; index--) {
  8810. if (this.cameras[index].id === id) {
  8811. return this.cameras[index];
  8812. }
  8813. }
  8814. for (index = this.lights.length - 1; index >= 0; index--) {
  8815. if (this.lights[index].id === id) {
  8816. return this.lights[index];
  8817. }
  8818. }
  8819. return null;
  8820. };
  8821. Scene.prototype.getNodeByName = function (name) {
  8822. var mesh = this.getMeshByName(name);
  8823. if (mesh) {
  8824. return mesh;
  8825. }
  8826. var light = this.getLightByName(name);
  8827. if (light) {
  8828. return light;
  8829. }
  8830. return this.getCameraByName(name);
  8831. };
  8832. Scene.prototype.getMeshByName = function (name) {
  8833. for (var index = 0; index < this.meshes.length; index++) {
  8834. if (this.meshes[index].name === name) {
  8835. return this.meshes[index];
  8836. }
  8837. }
  8838. return null;
  8839. };
  8840. Scene.prototype.getSoundByName = function (name) {
  8841. for (var index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  8842. if (this.mainSoundTrack.soundCollection[index].name === name) {
  8843. return this.mainSoundTrack.soundCollection[index];
  8844. }
  8845. }
  8846. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  8847. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  8848. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  8849. return this.soundTracks[sdIndex].soundCollection[index];
  8850. }
  8851. }
  8852. }
  8853. return null;
  8854. };
  8855. Scene.prototype.getLastSkeletonByID = function (id) {
  8856. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  8857. if (this.skeletons[index].id === id) {
  8858. return this.skeletons[index];
  8859. }
  8860. }
  8861. return null;
  8862. };
  8863. Scene.prototype.getSkeletonById = function (id) {
  8864. for (var index = 0; index < this.skeletons.length; index++) {
  8865. if (this.skeletons[index].id === id) {
  8866. return this.skeletons[index];
  8867. }
  8868. }
  8869. return null;
  8870. };
  8871. Scene.prototype.getSkeletonByName = function (name) {
  8872. for (var index = 0; index < this.skeletons.length; index++) {
  8873. if (this.skeletons[index].name === name) {
  8874. return this.skeletons[index];
  8875. }
  8876. }
  8877. return null;
  8878. };
  8879. Scene.prototype.isActiveMesh = function (mesh) {
  8880. return (this._activeMeshes.indexOf(mesh) !== -1);
  8881. };
  8882. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  8883. if (mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  8884. var material = subMesh.getMaterial();
  8885. if (mesh.showSubMeshesBoundingBox) {
  8886. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  8887. }
  8888. if (material) {
  8889. // Render targets
  8890. if (material.getRenderTargetTextures) {
  8891. if (this._processedMaterials.indexOf(material) === -1) {
  8892. this._processedMaterials.push(material);
  8893. this._renderTargets.concat(material.getRenderTargetTextures());
  8894. }
  8895. }
  8896. // Dispatch
  8897. this._activeVertices += subMesh.indexCount;
  8898. this._renderingManager.dispatch(subMesh);
  8899. }
  8900. }
  8901. };
  8902. Scene.prototype._evaluateActiveMeshes = function () {
  8903. this.activeCamera._activeMeshes.reset();
  8904. this._activeMeshes.reset();
  8905. this._renderingManager.reset();
  8906. this._processedMaterials.reset();
  8907. this._activeParticleSystems.reset();
  8908. this._activeSkeletons.reset();
  8909. this._boundingBoxRenderer.reset();
  8910. if (!this._frustumPlanes) {
  8911. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  8912. }
  8913. else {
  8914. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  8915. }
  8916. // Meshes
  8917. var meshes;
  8918. var len;
  8919. if (this._selectionOctree) {
  8920. var selection = this._selectionOctree.select(this._frustumPlanes);
  8921. meshes = selection.data;
  8922. len = selection.length;
  8923. }
  8924. else {
  8925. len = this.meshes.length;
  8926. meshes = this.meshes;
  8927. }
  8928. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  8929. var mesh = meshes[meshIndex];
  8930. if (mesh.isBlocked) {
  8931. continue;
  8932. }
  8933. this._totalVertices += mesh.getTotalVertices();
  8934. if (!mesh.isReady()) {
  8935. continue;
  8936. }
  8937. mesh.computeWorldMatrix();
  8938. // Intersections
  8939. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  8940. this._meshesForIntersections.pushNoDuplicate(mesh);
  8941. }
  8942. // Switch to current LOD
  8943. var meshLOD = mesh.getLOD(this.activeCamera);
  8944. if (!meshLOD) {
  8945. continue;
  8946. }
  8947. mesh._preActivate();
  8948. if (mesh.isEnabled() && mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  8949. this._activeMeshes.push(mesh);
  8950. this.activeCamera._activeMeshes.push(mesh);
  8951. mesh._activate(this._renderId);
  8952. this._activeMesh(meshLOD);
  8953. }
  8954. }
  8955. // Particle systems
  8956. var beforeParticlesDate = BABYLON.Tools.Now;
  8957. if (this.particlesEnabled) {
  8958. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  8959. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  8960. var particleSystem = this.particleSystems[particleIndex];
  8961. if (!particleSystem.isStarted()) {
  8962. continue;
  8963. }
  8964. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  8965. this._activeParticleSystems.push(particleSystem);
  8966. particleSystem.animate();
  8967. }
  8968. }
  8969. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  8970. }
  8971. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  8972. };
  8973. Scene.prototype._activeMesh = function (mesh) {
  8974. if (mesh.skeleton && this.skeletonsEnabled) {
  8975. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  8976. }
  8977. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  8978. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  8979. }
  8980. if (mesh && mesh.subMeshes) {
  8981. // Submeshes Octrees
  8982. var len;
  8983. var subMeshes;
  8984. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  8985. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  8986. len = intersections.length;
  8987. subMeshes = intersections.data;
  8988. }
  8989. else {
  8990. subMeshes = mesh.subMeshes;
  8991. len = subMeshes.length;
  8992. }
  8993. for (var subIndex = 0; subIndex < len; subIndex++) {
  8994. var subMesh = subMeshes[subIndex];
  8995. this._evaluateSubMesh(subMesh, mesh);
  8996. }
  8997. }
  8998. };
  8999. Scene.prototype.updateTransformMatrix = function (force) {
  9000. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  9001. };
  9002. Scene.prototype._renderForCamera = function (camera) {
  9003. var engine = this._engine;
  9004. this.activeCamera = camera;
  9005. if (!this.activeCamera)
  9006. throw new Error("Active camera not set");
  9007. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  9008. // Viewport
  9009. engine.setViewport(this.activeCamera.viewport);
  9010. // Camera
  9011. this._renderId++;
  9012. this.updateTransformMatrix();
  9013. if (this.beforeCameraRender) {
  9014. this.beforeCameraRender(this.activeCamera);
  9015. }
  9016. // Meshes
  9017. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  9018. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  9019. this._evaluateActiveMeshes();
  9020. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  9021. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  9022. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  9023. var skeleton = this._activeSkeletons.data[skeletonIndex];
  9024. skeleton.prepare();
  9025. }
  9026. // Render targets
  9027. var beforeRenderTargetDate = BABYLON.Tools.Now;
  9028. if (this.renderTargetsEnabled) {
  9029. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  9030. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  9031. var renderTarget = this._renderTargets.data[renderIndex];
  9032. if (renderTarget._shouldRender()) {
  9033. this._renderId++;
  9034. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  9035. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  9036. }
  9037. }
  9038. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  9039. this._renderId++;
  9040. }
  9041. if (this._renderTargets.length > 0) {
  9042. engine.restoreDefaultFramebuffer();
  9043. }
  9044. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  9045. // Prepare Frame
  9046. this.postProcessManager._prepareFrame();
  9047. var beforeRenderDate = BABYLON.Tools.Now;
  9048. // Backgrounds
  9049. if (this.layers.length) {
  9050. engine.setDepthBuffer(false);
  9051. var layerIndex;
  9052. var layer;
  9053. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  9054. layer = this.layers[layerIndex];
  9055. if (layer.isBackground) {
  9056. layer.render();
  9057. }
  9058. }
  9059. engine.setDepthBuffer(true);
  9060. }
  9061. // Render
  9062. BABYLON.Tools.StartPerformanceCounter("Main render");
  9063. this._renderingManager.render(null, null, true, true);
  9064. BABYLON.Tools.EndPerformanceCounter("Main render");
  9065. // Bounding boxes
  9066. this._boundingBoxRenderer.render();
  9067. // Lens flares
  9068. if (this.lensFlaresEnabled) {
  9069. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  9070. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  9071. this.lensFlareSystems[lensFlareSystemIndex].render();
  9072. }
  9073. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  9074. }
  9075. // Foregrounds
  9076. if (this.layers.length) {
  9077. engine.setDepthBuffer(false);
  9078. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  9079. layer = this.layers[layerIndex];
  9080. if (!layer.isBackground) {
  9081. layer.render();
  9082. }
  9083. }
  9084. engine.setDepthBuffer(true);
  9085. }
  9086. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  9087. // Finalize frame
  9088. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  9089. // Update camera
  9090. this.activeCamera._updateFromScene();
  9091. // Reset some special arrays
  9092. this._renderTargets.reset();
  9093. if (this.afterCameraRender) {
  9094. this.afterCameraRender(this.activeCamera);
  9095. }
  9096. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  9097. };
  9098. Scene.prototype._processSubCameras = function (camera) {
  9099. if (camera.subCameras.length === 0) {
  9100. this._renderForCamera(camera);
  9101. return;
  9102. }
  9103. for (var index = 0; index < camera.subCameras.length; index++) {
  9104. this._renderForCamera(camera.subCameras[index]);
  9105. }
  9106. this.activeCamera = camera;
  9107. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  9108. // Update camera
  9109. this.activeCamera._updateFromScene();
  9110. };
  9111. Scene.prototype._checkIntersections = function () {
  9112. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  9113. var sourceMesh = this._meshesForIntersections.data[index];
  9114. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  9115. var action = sourceMesh.actionManager.actions[actionIndex];
  9116. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  9117. var parameters = action.getTriggerParameter();
  9118. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  9119. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  9120. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  9121. if (areIntersecting && currentIntersectionInProgress === -1) {
  9122. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  9123. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  9124. sourceMesh._intersectionsInProgress.push(otherMesh);
  9125. }
  9126. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  9127. sourceMesh._intersectionsInProgress.push(otherMesh);
  9128. }
  9129. }
  9130. else if (!areIntersecting && currentIntersectionInProgress > -1 && action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  9131. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  9132. var indexOfOther = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  9133. if (indexOfOther > -1) {
  9134. sourceMesh._intersectionsInProgress.splice(indexOfOther, 1);
  9135. }
  9136. }
  9137. }
  9138. }
  9139. }
  9140. };
  9141. Scene.prototype.render = function () {
  9142. var startDate = BABYLON.Tools.Now;
  9143. this._particlesDuration = 0;
  9144. this._spritesDuration = 0;
  9145. this._activeParticles = 0;
  9146. this._renderDuration = 0;
  9147. this._renderTargetsDuration = 0;
  9148. this._evaluateActiveMeshesDuration = 0;
  9149. this._totalVertices = 0;
  9150. this._activeVertices = 0;
  9151. this._activeBones = 0;
  9152. this.getEngine().resetDrawCalls();
  9153. this._meshesForIntersections.reset();
  9154. this.resetCachedMaterial();
  9155. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  9156. // Actions
  9157. if (this.actionManager) {
  9158. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  9159. }
  9160. //Simplification Queue
  9161. if (!this.simplificationQueue.running) {
  9162. this.simplificationQueue.executeNext();
  9163. }
  9164. // Before render
  9165. if (this.beforeRender) {
  9166. this.beforeRender();
  9167. }
  9168. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  9169. this._onBeforeRenderCallbacks[callbackIndex]();
  9170. }
  9171. // Animations
  9172. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  9173. this._animationRatio = deltaTime * (60.0 / 1000.0);
  9174. this._animate();
  9175. // Physics
  9176. if (this._physicsEngine) {
  9177. BABYLON.Tools.StartPerformanceCounter("Physics");
  9178. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  9179. BABYLON.Tools.EndPerformanceCounter("Physics");
  9180. }
  9181. // Customs render targets
  9182. var beforeRenderTargetDate = BABYLON.Tools.Now;
  9183. var engine = this.getEngine();
  9184. var currentActiveCamera = this.activeCamera;
  9185. if (this.renderTargetsEnabled) {
  9186. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  9187. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  9188. var renderTarget = this.customRenderTargets[customIndex];
  9189. if (renderTarget._shouldRender()) {
  9190. this._renderId++;
  9191. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  9192. if (!this.activeCamera)
  9193. throw new Error("Active camera not set");
  9194. // Viewport
  9195. engine.setViewport(this.activeCamera.viewport);
  9196. // Camera
  9197. this.updateTransformMatrix();
  9198. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  9199. }
  9200. }
  9201. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  9202. this._renderId++;
  9203. }
  9204. if (this.customRenderTargets.length > 0) {
  9205. engine.restoreDefaultFramebuffer();
  9206. }
  9207. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  9208. this.activeCamera = currentActiveCamera;
  9209. // Procedural textures
  9210. if (this.proceduralTexturesEnabled) {
  9211. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  9212. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  9213. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  9214. if (proceduralTexture._shouldRender()) {
  9215. proceduralTexture.render();
  9216. }
  9217. }
  9218. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  9219. }
  9220. // Clear
  9221. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  9222. // Shadows
  9223. if (this.shadowsEnabled) {
  9224. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  9225. var light = this.lights[lightIndex];
  9226. var shadowGenerator = light.getShadowGenerator();
  9227. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  9228. this._renderTargets.push(shadowGenerator.getShadowMap());
  9229. }
  9230. }
  9231. }
  9232. // Depth renderer
  9233. if (this._depthRenderer) {
  9234. this._renderTargets.push(this._depthRenderer.getDepthMap());
  9235. }
  9236. // RenderPipeline
  9237. this.postProcessRenderPipelineManager.update();
  9238. // Multi-cameras?
  9239. if (this.activeCameras.length > 0) {
  9240. var currentRenderId = this._renderId;
  9241. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  9242. this._renderId = currentRenderId;
  9243. this._processSubCameras(this.activeCameras[cameraIndex]);
  9244. }
  9245. }
  9246. else {
  9247. if (!this.activeCamera) {
  9248. throw new Error("No camera defined");
  9249. }
  9250. this._processSubCameras(this.activeCamera);
  9251. }
  9252. // Intersection checks
  9253. this._checkIntersections();
  9254. // Update the audio listener attached to the camera
  9255. this._updateAudioParameters();
  9256. // After render
  9257. if (this.afterRender) {
  9258. this.afterRender();
  9259. }
  9260. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  9261. this._onAfterRenderCallbacks[callbackIndex]();
  9262. }
  9263. for (var index = 0; index < this._toBeDisposed.length; index++) {
  9264. this._toBeDisposed.data[index].dispose();
  9265. this._toBeDisposed[index] = null;
  9266. }
  9267. this._toBeDisposed.reset();
  9268. if (this.dumpNextRenderTargets) {
  9269. this.dumpNextRenderTargets = false;
  9270. }
  9271. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  9272. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  9273. };
  9274. Scene.prototype._updateAudioParameters = function () {
  9275. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 0)) {
  9276. return;
  9277. }
  9278. var listeningCamera;
  9279. var audioEngine = BABYLON.Engine.audioEngine;
  9280. if (this.activeCameras.length > 0) {
  9281. listeningCamera = this.activeCameras[0];
  9282. }
  9283. else {
  9284. listeningCamera = this.activeCamera;
  9285. }
  9286. if (listeningCamera && audioEngine.canUseWebAudio) {
  9287. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  9288. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  9289. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  9290. cameraDirection.normalize();
  9291. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  9292. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  9293. var sound = this.mainSoundTrack.soundCollection[i];
  9294. if (sound.useCustomAttenuation) {
  9295. sound.updateDistanceFromListener();
  9296. }
  9297. }
  9298. for (i = 0; i < this.soundTracks.length; i++) {
  9299. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  9300. sound = this.soundTracks[i].soundCollection[j];
  9301. if (sound.useCustomAttenuation) {
  9302. sound.updateDistanceFromListener();
  9303. }
  9304. }
  9305. }
  9306. }
  9307. };
  9308. Object.defineProperty(Scene.prototype, "audioEnabled", {
  9309. // Audio
  9310. get: function () {
  9311. return this._audioEnabled;
  9312. },
  9313. set: function (value) {
  9314. this._audioEnabled = value;
  9315. if (this._audioEnabled) {
  9316. this._enableAudio();
  9317. }
  9318. else {
  9319. this._disableAudio();
  9320. }
  9321. },
  9322. enumerable: true,
  9323. configurable: true
  9324. });
  9325. Scene.prototype._disableAudio = function () {
  9326. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  9327. this.mainSoundTrack.soundCollection[i].pause();
  9328. }
  9329. for (i = 0; i < this.soundTracks.length; i++) {
  9330. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  9331. this.soundTracks[i].soundCollection[j].pause();
  9332. }
  9333. }
  9334. };
  9335. Scene.prototype._enableAudio = function () {
  9336. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  9337. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  9338. this.mainSoundTrack.soundCollection[i].play();
  9339. }
  9340. }
  9341. for (i = 0; i < this.soundTracks.length; i++) {
  9342. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  9343. if (this.soundTracks[i].soundCollection[j].isPaused) {
  9344. this.soundTracks[i].soundCollection[j].play();
  9345. }
  9346. }
  9347. }
  9348. };
  9349. Object.defineProperty(Scene.prototype, "headphone", {
  9350. get: function () {
  9351. return this._headphone;
  9352. },
  9353. set: function (value) {
  9354. this._headphone = value;
  9355. if (this._headphone) {
  9356. this._switchAudioModeForHeadphones();
  9357. }
  9358. else {
  9359. this._switchAudioModeForNormalSpeakers();
  9360. }
  9361. },
  9362. enumerable: true,
  9363. configurable: true
  9364. });
  9365. Scene.prototype._switchAudioModeForHeadphones = function () {
  9366. this.mainSoundTrack.switchPanningModelToHRTF();
  9367. for (var i = 0; i < this.soundTracks.length; i++) {
  9368. this.soundTracks[i].switchPanningModelToHRTF();
  9369. }
  9370. };
  9371. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  9372. this.mainSoundTrack.switchPanningModelToEqualPower();
  9373. for (var i = 0; i < this.soundTracks.length; i++) {
  9374. this.soundTracks[i].switchPanningModelToEqualPower();
  9375. }
  9376. };
  9377. Scene.prototype.enableDepthRenderer = function () {
  9378. if (this._depthRenderer) {
  9379. return this._depthRenderer;
  9380. }
  9381. this._depthRenderer = new BABYLON.DepthRenderer(this);
  9382. return this._depthRenderer;
  9383. };
  9384. Scene.prototype.disableDepthRenderer = function () {
  9385. if (!this._depthRenderer) {
  9386. return;
  9387. }
  9388. this._depthRenderer.dispose();
  9389. this._depthRenderer = null;
  9390. };
  9391. Scene.prototype.dispose = function () {
  9392. this.beforeRender = null;
  9393. this.afterRender = null;
  9394. this.skeletons = [];
  9395. this._boundingBoxRenderer.dispose();
  9396. if (this._depthRenderer) {
  9397. this._depthRenderer.dispose();
  9398. }
  9399. // Debug layer
  9400. this.debugLayer.hide();
  9401. // Events
  9402. if (this.onDispose) {
  9403. this.onDispose();
  9404. }
  9405. this._onBeforeRenderCallbacks = [];
  9406. this._onAfterRenderCallbacks = [];
  9407. this.detachControl();
  9408. // Release sounds & sounds tracks
  9409. this.disposeSounds();
  9410. // Detach cameras
  9411. var canvas = this._engine.getRenderingCanvas();
  9412. var index;
  9413. for (index = 0; index < this.cameras.length; index++) {
  9414. this.cameras[index].detachControl(canvas);
  9415. }
  9416. while (this.lights.length) {
  9417. this.lights[0].dispose();
  9418. }
  9419. while (this.meshes.length) {
  9420. this.meshes[0].dispose(true);
  9421. }
  9422. while (this.cameras.length) {
  9423. this.cameras[0].dispose();
  9424. }
  9425. while (this.materials.length) {
  9426. this.materials[0].dispose();
  9427. }
  9428. while (this.particleSystems.length) {
  9429. this.particleSystems[0].dispose();
  9430. }
  9431. while (this.spriteManagers.length) {
  9432. this.spriteManagers[0].dispose();
  9433. }
  9434. while (this.layers.length) {
  9435. this.layers[0].dispose();
  9436. }
  9437. while (this.textures.length) {
  9438. this.textures[0].dispose();
  9439. }
  9440. // Post-processes
  9441. this.postProcessManager.dispose();
  9442. // Physics
  9443. if (this._physicsEngine) {
  9444. this.disablePhysicsEngine();
  9445. }
  9446. // Remove from engine
  9447. index = this._engine.scenes.indexOf(this);
  9448. if (index > -1) {
  9449. this._engine.scenes.splice(index, 1);
  9450. }
  9451. this._engine.wipeCaches();
  9452. };
  9453. // Release sounds & sounds tracks
  9454. Scene.prototype.disposeSounds = function () {
  9455. this.mainSoundTrack.dispose();
  9456. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  9457. this.soundTracks[scIndex].dispose();
  9458. }
  9459. };
  9460. // Collisions
  9461. Scene.prototype._getNewPosition = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  9462. if (excludedMesh === void 0) { excludedMesh = null; }
  9463. position.divideToRef(collider.radius, this._scaledPosition);
  9464. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9465. collider.retry = 0;
  9466. collider.initialVelocity = this._scaledVelocity;
  9467. collider.initialPosition = this._scaledPosition;
  9468. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, finalPosition, excludedMesh);
  9469. finalPosition.multiplyInPlace(collider.radius);
  9470. };
  9471. Scene.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  9472. if (excludedMesh === void 0) { excludedMesh = null; }
  9473. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  9474. if (collider.retry >= maximumRetry) {
  9475. finalPosition.copyFrom(position);
  9476. return;
  9477. }
  9478. collider._initialize(position, velocity, closeDistance);
  9479. for (var index = 0; index < this.meshes.length; index++) {
  9480. var mesh = this.meshes[index];
  9481. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  9482. mesh._checkCollision(collider);
  9483. }
  9484. }
  9485. if (!collider.collisionFound) {
  9486. position.addToRef(velocity, finalPosition);
  9487. return;
  9488. }
  9489. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  9490. collider._getResponse(position, velocity);
  9491. }
  9492. if (velocity.length() <= closeDistance) {
  9493. finalPosition.copyFrom(position);
  9494. return;
  9495. }
  9496. collider.retry++;
  9497. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  9498. };
  9499. // Octrees
  9500. Scene.prototype.getWorldExtends = function () {
  9501. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9502. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  9503. for (var index = 0; index < this.meshes.length; index++) {
  9504. var mesh = this.meshes[index];
  9505. mesh.computeWorldMatrix(true);
  9506. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  9507. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  9508. BABYLON.Tools.CheckExtends(minBox, min, max);
  9509. BABYLON.Tools.CheckExtends(maxBox, min, max);
  9510. }
  9511. return {
  9512. min: min,
  9513. max: max
  9514. };
  9515. };
  9516. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  9517. if (maxCapacity === void 0) { maxCapacity = 64; }
  9518. if (maxDepth === void 0) { maxDepth = 2; }
  9519. if (!this._selectionOctree) {
  9520. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  9521. }
  9522. var worldExtends = this.getWorldExtends();
  9523. // Update octree
  9524. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  9525. return this._selectionOctree;
  9526. };
  9527. // Picking
  9528. Scene.prototype.createPickingRay = function (x, y, world, camera) {
  9529. var engine = this._engine;
  9530. if (!camera) {
  9531. if (!this.activeCamera)
  9532. throw new Error("Active camera not set");
  9533. camera = this.activeCamera;
  9534. }
  9535. var cameraViewport = camera.viewport;
  9536. var viewport = cameraViewport.toGlobal(engine);
  9537. // Moving coordinates to local viewport world
  9538. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  9539. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  9540. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  9541. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  9542. };
  9543. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  9544. var pickingInfo = null;
  9545. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  9546. var mesh = this.meshes[meshIndex];
  9547. if (predicate) {
  9548. if (!predicate(mesh)) {
  9549. continue;
  9550. }
  9551. }
  9552. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  9553. continue;
  9554. }
  9555. var world = mesh.getWorldMatrix();
  9556. var ray = rayFunction(world);
  9557. var result = mesh.intersects(ray, fastCheck);
  9558. if (!result || !result.hit)
  9559. continue;
  9560. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  9561. continue;
  9562. pickingInfo = result;
  9563. if (fastCheck) {
  9564. break;
  9565. }
  9566. }
  9567. return pickingInfo || new BABYLON.PickingInfo();
  9568. };
  9569. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  9570. var _this = this;
  9571. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  9572. /// <param name="x">X position on screen</param>
  9573. /// <param name="y">Y position on screen</param>
  9574. /// <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>
  9575. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  9576. /// <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>
  9577. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  9578. };
  9579. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  9580. var _this = this;
  9581. return this._internalPick(function (world) {
  9582. if (!_this._pickWithRayInverseMatrix) {
  9583. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  9584. }
  9585. world.invertToRef(_this._pickWithRayInverseMatrix);
  9586. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  9587. }, predicate, fastCheck);
  9588. };
  9589. Scene.prototype.setPointerOverMesh = function (mesh) {
  9590. if (this._pointerOverMesh === mesh) {
  9591. return;
  9592. }
  9593. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  9594. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  9595. }
  9596. this._pointerOverMesh = mesh;
  9597. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  9598. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  9599. }
  9600. };
  9601. Scene.prototype.getPointerOverMesh = function () {
  9602. return this._pointerOverMesh;
  9603. };
  9604. // Physics
  9605. Scene.prototype.getPhysicsEngine = function () {
  9606. return this._physicsEngine;
  9607. };
  9608. Scene.prototype.enablePhysics = function (gravity, plugin) {
  9609. if (this._physicsEngine) {
  9610. return true;
  9611. }
  9612. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  9613. if (!this._physicsEngine.isSupported()) {
  9614. this._physicsEngine = null;
  9615. return false;
  9616. }
  9617. this._physicsEngine._initialize(gravity);
  9618. return true;
  9619. };
  9620. Scene.prototype.disablePhysicsEngine = function () {
  9621. if (!this._physicsEngine) {
  9622. return;
  9623. }
  9624. this._physicsEngine.dispose();
  9625. this._physicsEngine = undefined;
  9626. };
  9627. Scene.prototype.isPhysicsEnabled = function () {
  9628. return this._physicsEngine !== undefined;
  9629. };
  9630. Scene.prototype.setGravity = function (gravity) {
  9631. if (!this._physicsEngine) {
  9632. return;
  9633. }
  9634. this._physicsEngine._setGravity(gravity);
  9635. };
  9636. Scene.prototype.createCompoundImpostor = function (parts, options) {
  9637. if (parts.parts) {
  9638. options = parts;
  9639. parts = parts.parts;
  9640. }
  9641. if (!this._physicsEngine) {
  9642. return null;
  9643. }
  9644. for (var index = 0; index < parts.length; index++) {
  9645. var mesh = parts[index].mesh;
  9646. mesh._physicImpostor = parts[index].impostor;
  9647. mesh._physicsMass = options.mass / parts.length;
  9648. mesh._physicsFriction = options.friction;
  9649. mesh._physicRestitution = options.restitution;
  9650. }
  9651. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  9652. };
  9653. Scene.prototype.deleteCompoundImpostor = function (compound) {
  9654. for (var index = 0; index < compound.parts.length; index++) {
  9655. var mesh = compound.parts[index].mesh;
  9656. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  9657. this._physicsEngine._unregisterMesh(mesh);
  9658. }
  9659. };
  9660. // Misc.
  9661. Scene.prototype.createDefaultCameraOrLight = function () {
  9662. // Light
  9663. if (this.lights.length === 0) {
  9664. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  9665. }
  9666. // Camera
  9667. if (!this.activeCamera) {
  9668. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  9669. // Compute position
  9670. var worldExtends = this.getWorldExtends();
  9671. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  9672. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  9673. camera.setTarget(worldCenter);
  9674. this.activeCamera = camera;
  9675. }
  9676. };
  9677. // Tags
  9678. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  9679. if (tagsQuery === undefined) {
  9680. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  9681. return list;
  9682. }
  9683. var listByTags = [];
  9684. forEach = forEach || (function (item) {
  9685. return;
  9686. });
  9687. for (var i in list) {
  9688. var item = list[i];
  9689. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  9690. listByTags.push(item);
  9691. forEach(item);
  9692. }
  9693. }
  9694. return listByTags;
  9695. };
  9696. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  9697. return this._getByTags(this.meshes, tagsQuery, forEach);
  9698. };
  9699. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  9700. return this._getByTags(this.cameras, tagsQuery, forEach);
  9701. };
  9702. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  9703. return this._getByTags(this.lights, tagsQuery, forEach);
  9704. };
  9705. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  9706. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  9707. };
  9708. // Statics
  9709. Scene._FOGMODE_NONE = 0;
  9710. Scene._FOGMODE_EXP = 1;
  9711. Scene._FOGMODE_EXP2 = 2;
  9712. Scene._FOGMODE_LINEAR = 3;
  9713. Scene.MinDeltaTime = 1.0;
  9714. Scene.MaxDeltaTime = 1000.0;
  9715. return Scene;
  9716. })();
  9717. BABYLON.Scene = Scene;
  9718. })(BABYLON || (BABYLON = {}));
  9719. //# sourceMappingURL=babylon.scene.js.mapvar BABYLON;
  9720. (function (BABYLON) {
  9721. var VertexBuffer = (function () {
  9722. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  9723. if (engine instanceof BABYLON.Mesh) {
  9724. this._engine = engine.getScene().getEngine();
  9725. }
  9726. else {
  9727. this._engine = engine;
  9728. }
  9729. this._updatable = updatable;
  9730. this._data = data;
  9731. if (!postponeInternalCreation) {
  9732. this.create();
  9733. }
  9734. this._kind = kind;
  9735. if (stride) {
  9736. this._strideSize = stride;
  9737. return;
  9738. }
  9739. switch (kind) {
  9740. case VertexBuffer.PositionKind:
  9741. this._strideSize = 3;
  9742. break;
  9743. case VertexBuffer.NormalKind:
  9744. this._strideSize = 3;
  9745. break;
  9746. case VertexBuffer.UVKind:
  9747. this._strideSize = 2;
  9748. break;
  9749. case VertexBuffer.UV2Kind:
  9750. this._strideSize = 2;
  9751. break;
  9752. case VertexBuffer.ColorKind:
  9753. this._strideSize = 4;
  9754. break;
  9755. case VertexBuffer.MatricesIndicesKind:
  9756. this._strideSize = 4;
  9757. break;
  9758. case VertexBuffer.MatricesWeightsKind:
  9759. this._strideSize = 4;
  9760. break;
  9761. }
  9762. }
  9763. // Properties
  9764. VertexBuffer.prototype.isUpdatable = function () {
  9765. return this._updatable;
  9766. };
  9767. VertexBuffer.prototype.getData = function () {
  9768. return this._data;
  9769. };
  9770. VertexBuffer.prototype.getBuffer = function () {
  9771. return this._buffer;
  9772. };
  9773. VertexBuffer.prototype.getStrideSize = function () {
  9774. return this._strideSize;
  9775. };
  9776. // Methods
  9777. VertexBuffer.prototype.create = function (data) {
  9778. if (!data && this._buffer) {
  9779. return; // nothing to do
  9780. }
  9781. data = data || this._data;
  9782. if (!this._buffer) {
  9783. if (this._updatable) {
  9784. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  9785. }
  9786. else {
  9787. this._buffer = this._engine.createVertexBuffer(data);
  9788. }
  9789. }
  9790. if (this._updatable) {
  9791. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  9792. this._data = data;
  9793. }
  9794. };
  9795. VertexBuffer.prototype.update = function (data) {
  9796. this.create(data);
  9797. };
  9798. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  9799. if (!this._buffer) {
  9800. return;
  9801. }
  9802. if (this._updatable) {
  9803. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  9804. this._data = null;
  9805. }
  9806. };
  9807. VertexBuffer.prototype.dispose = function () {
  9808. if (!this._buffer) {
  9809. return;
  9810. }
  9811. if (this._engine._releaseBuffer(this._buffer)) {
  9812. this._buffer = null;
  9813. }
  9814. };
  9815. Object.defineProperty(VertexBuffer, "PositionKind", {
  9816. get: function () {
  9817. return VertexBuffer._PositionKind;
  9818. },
  9819. enumerable: true,
  9820. configurable: true
  9821. });
  9822. Object.defineProperty(VertexBuffer, "NormalKind", {
  9823. get: function () {
  9824. return VertexBuffer._NormalKind;
  9825. },
  9826. enumerable: true,
  9827. configurable: true
  9828. });
  9829. Object.defineProperty(VertexBuffer, "UVKind", {
  9830. get: function () {
  9831. return VertexBuffer._UVKind;
  9832. },
  9833. enumerable: true,
  9834. configurable: true
  9835. });
  9836. Object.defineProperty(VertexBuffer, "UV2Kind", {
  9837. get: function () {
  9838. return VertexBuffer._UV2Kind;
  9839. },
  9840. enumerable: true,
  9841. configurable: true
  9842. });
  9843. Object.defineProperty(VertexBuffer, "ColorKind", {
  9844. get: function () {
  9845. return VertexBuffer._ColorKind;
  9846. },
  9847. enumerable: true,
  9848. configurable: true
  9849. });
  9850. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  9851. get: function () {
  9852. return VertexBuffer._MatricesIndicesKind;
  9853. },
  9854. enumerable: true,
  9855. configurable: true
  9856. });
  9857. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  9858. get: function () {
  9859. return VertexBuffer._MatricesWeightsKind;
  9860. },
  9861. enumerable: true,
  9862. configurable: true
  9863. });
  9864. // Enums
  9865. VertexBuffer._PositionKind = "position";
  9866. VertexBuffer._NormalKind = "normal";
  9867. VertexBuffer._UVKind = "uv";
  9868. VertexBuffer._UV2Kind = "uv2";
  9869. VertexBuffer._ColorKind = "color";
  9870. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  9871. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  9872. return VertexBuffer;
  9873. })();
  9874. BABYLON.VertexBuffer = VertexBuffer;
  9875. })(BABYLON || (BABYLON = {}));
  9876. //# sourceMappingURL=babylon.vertexBuffer.js.map
  9877. var BABYLON;
  9878. (function (BABYLON) {
  9879. var AbstractMesh = (function (_super) {
  9880. __extends(AbstractMesh, _super);
  9881. function AbstractMesh(name, scene) {
  9882. _super.call(this, name, scene);
  9883. // Properties
  9884. this.definedFacingForward = true; // orientation for POV movement & rotation
  9885. this.position = new BABYLON.Vector3(0, 0, 0);
  9886. this.rotation = new BABYLON.Vector3(0, 0, 0);
  9887. this.scaling = new BABYLON.Vector3(1, 1, 1);
  9888. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  9889. this.visibility = 1.0;
  9890. this.alphaIndex = Number.MAX_VALUE;
  9891. this.infiniteDistance = false;
  9892. this.isVisible = true;
  9893. this.isPickable = true;
  9894. this.showBoundingBox = false;
  9895. this.showSubMeshesBoundingBox = false;
  9896. this.onDispose = null;
  9897. this.checkCollisions = false;
  9898. this.isBlocker = false;
  9899. this.renderingGroupId = 0;
  9900. this.receiveShadows = false;
  9901. this.renderOutline = false;
  9902. this.outlineColor = BABYLON.Color3.Red();
  9903. this.outlineWidth = 0.02;
  9904. this.renderOverlay = false;
  9905. this.overlayColor = BABYLON.Color3.Red();
  9906. this.overlayAlpha = 0.5;
  9907. this.hasVertexAlpha = false;
  9908. this.useVertexColors = true;
  9909. this.applyFog = true;
  9910. this.useOctreeForRenderingSelection = true;
  9911. this.useOctreeForPicking = true;
  9912. this.useOctreeForCollisions = true;
  9913. this.layerMask = 0x0FFFFFFF;
  9914. // Physics
  9915. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  9916. // Collisions
  9917. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  9918. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  9919. this._collider = new BABYLON.Collider();
  9920. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  9921. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  9922. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  9923. // Cache
  9924. this._localScaling = BABYLON.Matrix.Zero();
  9925. this._localRotation = BABYLON.Matrix.Zero();
  9926. this._localTranslation = BABYLON.Matrix.Zero();
  9927. this._localBillboard = BABYLON.Matrix.Zero();
  9928. this._localPivotScaling = BABYLON.Matrix.Zero();
  9929. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  9930. this._localWorld = BABYLON.Matrix.Zero();
  9931. this._worldMatrix = BABYLON.Matrix.Zero();
  9932. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  9933. this._absolutePosition = BABYLON.Vector3.Zero();
  9934. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  9935. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  9936. this._isDirty = false;
  9937. this._pivotMatrix = BABYLON.Matrix.Identity();
  9938. this._isDisposed = false;
  9939. this._renderId = 0;
  9940. this._intersectionsInProgress = new Array();
  9941. this._onAfterWorldMatrixUpdate = new Array();
  9942. scene.addMesh(this);
  9943. }
  9944. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  9945. get: function () {
  9946. return AbstractMesh._BILLBOARDMODE_NONE;
  9947. },
  9948. enumerable: true,
  9949. configurable: true
  9950. });
  9951. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  9952. get: function () {
  9953. return AbstractMesh._BILLBOARDMODE_X;
  9954. },
  9955. enumerable: true,
  9956. configurable: true
  9957. });
  9958. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  9959. get: function () {
  9960. return AbstractMesh._BILLBOARDMODE_Y;
  9961. },
  9962. enumerable: true,
  9963. configurable: true
  9964. });
  9965. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  9966. get: function () {
  9967. return AbstractMesh._BILLBOARDMODE_Z;
  9968. },
  9969. enumerable: true,
  9970. configurable: true
  9971. });
  9972. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  9973. get: function () {
  9974. return AbstractMesh._BILLBOARDMODE_ALL;
  9975. },
  9976. enumerable: true,
  9977. configurable: true
  9978. });
  9979. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  9980. // Methods
  9981. get: function () {
  9982. return false;
  9983. },
  9984. enumerable: true,
  9985. configurable: true
  9986. });
  9987. AbstractMesh.prototype.getLOD = function (camera) {
  9988. return this;
  9989. };
  9990. AbstractMesh.prototype.getTotalVertices = function () {
  9991. return 0;
  9992. };
  9993. AbstractMesh.prototype.getIndices = function () {
  9994. return null;
  9995. };
  9996. AbstractMesh.prototype.getVerticesData = function (kind) {
  9997. return null;
  9998. };
  9999. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  10000. return false;
  10001. };
  10002. AbstractMesh.prototype.getBoundingInfo = function () {
  10003. if (this._masterMesh) {
  10004. return this._masterMesh.getBoundingInfo();
  10005. }
  10006. if (!this._boundingInfo) {
  10007. this._updateBoundingInfo();
  10008. }
  10009. return this._boundingInfo;
  10010. };
  10011. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  10012. get: function () {
  10013. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  10014. },
  10015. enumerable: true,
  10016. configurable: true
  10017. });
  10018. AbstractMesh.prototype._preActivate = function () {
  10019. };
  10020. AbstractMesh.prototype._activate = function (renderId) {
  10021. this._renderId = renderId;
  10022. };
  10023. AbstractMesh.prototype.getWorldMatrix = function () {
  10024. if (this._masterMesh) {
  10025. return this._masterMesh.getWorldMatrix();
  10026. }
  10027. if (this._currentRenderId !== this.getScene().getRenderId()) {
  10028. this.computeWorldMatrix();
  10029. }
  10030. return this._worldMatrix;
  10031. };
  10032. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  10033. get: function () {
  10034. return this._worldMatrix;
  10035. },
  10036. enumerable: true,
  10037. configurable: true
  10038. });
  10039. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  10040. get: function () {
  10041. return this._absolutePosition;
  10042. },
  10043. enumerable: true,
  10044. configurable: true
  10045. });
  10046. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  10047. if (!this.rotationQuaternion) {
  10048. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  10049. this.rotation = BABYLON.Vector3.Zero();
  10050. }
  10051. if (!space || space === 0 /* LOCAL */) {
  10052. var rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  10053. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  10054. }
  10055. else {
  10056. if (this.parent) {
  10057. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  10058. invertParentWorldMatrix.invert();
  10059. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  10060. }
  10061. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  10062. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  10063. }
  10064. };
  10065. AbstractMesh.prototype.translate = function (axis, distance, space) {
  10066. var displacementVector = axis.scale(distance);
  10067. if (!space || space === 0 /* LOCAL */) {
  10068. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  10069. this.setPositionWithLocalVector(tempV3);
  10070. }
  10071. else {
  10072. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  10073. }
  10074. };
  10075. AbstractMesh.prototype.getAbsolutePosition = function () {
  10076. this.computeWorldMatrix();
  10077. return this._absolutePosition;
  10078. };
  10079. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  10080. if (!absolutePosition) {
  10081. return;
  10082. }
  10083. var absolutePositionX;
  10084. var absolutePositionY;
  10085. var absolutePositionZ;
  10086. if (absolutePosition.x === undefined) {
  10087. if (arguments.length < 3) {
  10088. return;
  10089. }
  10090. absolutePositionX = arguments[0];
  10091. absolutePositionY = arguments[1];
  10092. absolutePositionZ = arguments[2];
  10093. }
  10094. else {
  10095. absolutePositionX = absolutePosition.x;
  10096. absolutePositionY = absolutePosition.y;
  10097. absolutePositionZ = absolutePosition.z;
  10098. }
  10099. if (this.parent) {
  10100. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  10101. invertParentWorldMatrix.invert();
  10102. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  10103. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  10104. }
  10105. else {
  10106. this.position.x = absolutePositionX;
  10107. this.position.y = absolutePositionY;
  10108. this.position.z = absolutePositionZ;
  10109. }
  10110. };
  10111. // ================================== Point of View Movement =================================
  10112. /**
  10113. * Perform relative position change from the point of view of behind the front of the mesh.
  10114. * This is performed taking into account the meshes current rotation, so you do not have to care.
  10115. * Supports definition of mesh facing forward or backward.
  10116. * @param {number} amountRight
  10117. * @param {number} amountUp
  10118. * @param {number} amountForward
  10119. */
  10120. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  10121. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  10122. };
  10123. /**
  10124. * Calculate relative position change from the point of view of behind the front of the mesh.
  10125. * This is performed taking into account the meshes current rotation, so you do not have to care.
  10126. * Supports definition of mesh facing forward or backward.
  10127. * @param {number} amountRight
  10128. * @param {number} amountUp
  10129. * @param {number} amountForward
  10130. */
  10131. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  10132. var rotMatrix = new BABYLON.Matrix();
  10133. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  10134. rotQuaternion.toRotationMatrix(rotMatrix);
  10135. var translationDelta = BABYLON.Vector3.Zero();
  10136. var defForwardMult = this.definedFacingForward ? -1 : 1;
  10137. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  10138. return translationDelta;
  10139. };
  10140. // ================================== Point of View Rotation =================================
  10141. /**
  10142. * Perform relative rotation change from the point of view of behind the front of the mesh.
  10143. * Supports definition of mesh facing forward or backward.
  10144. * @param {number} flipBack
  10145. * @param {number} twirlClockwise
  10146. * @param {number} tiltRight
  10147. */
  10148. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  10149. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  10150. };
  10151. /**
  10152. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  10153. * Supports definition of mesh facing forward or backward.
  10154. * @param {number} flipBack
  10155. * @param {number} twirlClockwise
  10156. * @param {number} tiltRight
  10157. */
  10158. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  10159. var defForwardMult = this.definedFacingForward ? 1 : -1;
  10160. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  10161. };
  10162. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  10163. this._pivotMatrix = matrix;
  10164. this._cache.pivotMatrixUpdated = true;
  10165. };
  10166. AbstractMesh.prototype.getPivotMatrix = function () {
  10167. return this._pivotMatrix;
  10168. };
  10169. AbstractMesh.prototype._isSynchronized = function () {
  10170. if (this._isDirty) {
  10171. return false;
  10172. }
  10173. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  10174. return false;
  10175. if (this._cache.pivotMatrixUpdated) {
  10176. return false;
  10177. }
  10178. if (this.infiniteDistance) {
  10179. return false;
  10180. }
  10181. if (!this._cache.position.equals(this.position))
  10182. return false;
  10183. if (this.rotationQuaternion) {
  10184. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  10185. return false;
  10186. }
  10187. else {
  10188. if (!this._cache.rotation.equals(this.rotation))
  10189. return false;
  10190. }
  10191. if (!this._cache.scaling.equals(this.scaling))
  10192. return false;
  10193. return true;
  10194. };
  10195. AbstractMesh.prototype._initCache = function () {
  10196. _super.prototype._initCache.call(this);
  10197. this._cache.localMatrixUpdated = false;
  10198. this._cache.position = BABYLON.Vector3.Zero();
  10199. this._cache.scaling = BABYLON.Vector3.Zero();
  10200. this._cache.rotation = BABYLON.Vector3.Zero();
  10201. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  10202. };
  10203. AbstractMesh.prototype.markAsDirty = function (property) {
  10204. if (property === "rotation") {
  10205. this.rotationQuaternion = null;
  10206. }
  10207. this._currentRenderId = Number.MAX_VALUE;
  10208. this._isDirty = true;
  10209. };
  10210. AbstractMesh.prototype._updateBoundingInfo = function () {
  10211. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  10212. this._boundingInfo._update(this.worldMatrixFromCache);
  10213. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  10214. };
  10215. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  10216. if (!this.subMeshes) {
  10217. return;
  10218. }
  10219. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  10220. var subMesh = this.subMeshes[subIndex];
  10221. subMesh.updateBoundingInfo(matrix);
  10222. }
  10223. };
  10224. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  10225. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  10226. return this._worldMatrix;
  10227. }
  10228. this._cache.position.copyFrom(this.position);
  10229. this._cache.scaling.copyFrom(this.scaling);
  10230. this._cache.pivotMatrixUpdated = false;
  10231. this._currentRenderId = this.getScene().getRenderId();
  10232. this._isDirty = false;
  10233. // Scaling
  10234. BABYLON.Matrix.ScalingToRef(this.scaling.x, this.scaling.y, this.scaling.z, this._localScaling);
  10235. // Rotation
  10236. if (this.rotationQuaternion) {
  10237. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  10238. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  10239. }
  10240. else {
  10241. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  10242. this._cache.rotation.copyFrom(this.rotation);
  10243. }
  10244. // Translation
  10245. if (this.infiniteDistance && !this.parent) {
  10246. var camera = this.getScene().activeCamera;
  10247. var cameraWorldMatrix = camera.getWorldMatrix();
  10248. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  10249. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  10250. }
  10251. else {
  10252. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  10253. }
  10254. // Composing transformations
  10255. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  10256. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  10257. // Billboarding
  10258. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  10259. var localPosition = this.position.clone();
  10260. var zero = this.getScene().activeCamera.position.clone();
  10261. if (this.parent && this.parent.position) {
  10262. localPosition.addInPlace(this.parent.position);
  10263. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  10264. }
  10265. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) === AbstractMesh.BILLBOARDMODE_ALL) {
  10266. zero = this.getScene().activeCamera.position;
  10267. }
  10268. else {
  10269. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  10270. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  10271. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  10272. zero.y = localPosition.y + 0.001;
  10273. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  10274. zero.z = localPosition.z + 0.001;
  10275. }
  10276. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  10277. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  10278. this._localBillboard.invert();
  10279. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  10280. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  10281. }
  10282. // Local world
  10283. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  10284. // Parent
  10285. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  10286. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  10287. }
  10288. else {
  10289. this._worldMatrix.copyFrom(this._localWorld);
  10290. }
  10291. // Bounding info
  10292. this._updateBoundingInfo();
  10293. // Absolute position
  10294. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  10295. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  10296. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  10297. }
  10298. return this._worldMatrix;
  10299. };
  10300. /**
  10301. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  10302. * @param func: callback function to add
  10303. */
  10304. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  10305. this._onAfterWorldMatrixUpdate.push(func);
  10306. };
  10307. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  10308. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  10309. if (index > -1) {
  10310. this._onAfterWorldMatrixUpdate.splice(index, 1);
  10311. }
  10312. };
  10313. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  10314. this.computeWorldMatrix();
  10315. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  10316. };
  10317. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  10318. this.computeWorldMatrix();
  10319. var invLocalWorldMatrix = this._localWorld.clone();
  10320. invLocalWorldMatrix.invert();
  10321. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  10322. };
  10323. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  10324. this.computeWorldMatrix();
  10325. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  10326. };
  10327. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  10328. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  10329. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  10330. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  10331. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  10332. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  10333. /// <returns>Mesh oriented towards targetMesh</returns>
  10334. yawCor = yawCor || 0; // default to zero if undefined
  10335. pitchCor = pitchCor || 0;
  10336. rollCor = rollCor || 0;
  10337. var dv = targetPoint.subtract(this.position);
  10338. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  10339. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  10340. var pitch = Math.atan2(dv.y, len);
  10341. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  10342. };
  10343. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  10344. if (!this._boundingInfo.isInFrustum(frustumPlanes)) {
  10345. return false;
  10346. }
  10347. return true;
  10348. };
  10349. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  10350. if (!camera) {
  10351. camera = this.getScene().activeCamera;
  10352. }
  10353. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  10354. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  10355. return false;
  10356. }
  10357. return true;
  10358. };
  10359. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  10360. if (!this._boundingInfo || !mesh._boundingInfo) {
  10361. return false;
  10362. }
  10363. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  10364. };
  10365. AbstractMesh.prototype.intersectsPoint = function (point) {
  10366. if (!this._boundingInfo) {
  10367. return false;
  10368. }
  10369. return this._boundingInfo.intersectsPoint(point);
  10370. };
  10371. // Physics
  10372. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  10373. var physicsEngine = this.getScene().getPhysicsEngine();
  10374. if (!physicsEngine) {
  10375. return;
  10376. }
  10377. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  10378. if (impostor.impostor) {
  10379. // Old API
  10380. options = impostor;
  10381. impostor = impostor.impostor;
  10382. }
  10383. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  10384. physicsEngine._unregisterMesh(this);
  10385. return;
  10386. }
  10387. if (!options) {
  10388. options = { mass: 0, friction: 0.2, restitution: 0.2 };
  10389. }
  10390. else {
  10391. if (!options.mass && options.mass !== 0)
  10392. options.mass = 0;
  10393. if (!options.friction && options.friction !== 0)
  10394. options.friction = 0.2;
  10395. if (!options.restitution && options.restitution !== 0)
  10396. options.restitution = 0.2;
  10397. }
  10398. this._physicImpostor = impostor;
  10399. this._physicsMass = options.mass;
  10400. this._physicsFriction = options.friction;
  10401. this._physicRestitution = options.restitution;
  10402. return physicsEngine._registerMesh(this, impostor, options);
  10403. };
  10404. AbstractMesh.prototype.getPhysicsImpostor = function () {
  10405. if (!this._physicImpostor) {
  10406. return BABYLON.PhysicsEngine.NoImpostor;
  10407. }
  10408. return this._physicImpostor;
  10409. };
  10410. AbstractMesh.prototype.getPhysicsMass = function () {
  10411. if (!this._physicsMass) {
  10412. return 0;
  10413. }
  10414. return this._physicsMass;
  10415. };
  10416. AbstractMesh.prototype.getPhysicsFriction = function () {
  10417. if (!this._physicsFriction) {
  10418. return 0;
  10419. }
  10420. return this._physicsFriction;
  10421. };
  10422. AbstractMesh.prototype.getPhysicsRestitution = function () {
  10423. if (!this._physicRestitution) {
  10424. return 0;
  10425. }
  10426. return this._physicRestitution;
  10427. };
  10428. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  10429. if (!camera) {
  10430. camera = this.getScene().activeCamera;
  10431. }
  10432. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  10433. };
  10434. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  10435. if (!camera) {
  10436. camera = this.getScene().activeCamera;
  10437. }
  10438. return this.absolutePosition.subtract(camera.position).length();
  10439. };
  10440. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  10441. if (!this._physicImpostor) {
  10442. return;
  10443. }
  10444. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  10445. };
  10446. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  10447. if (!this._physicImpostor) {
  10448. return;
  10449. }
  10450. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  10451. };
  10452. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  10453. if (!this._physicImpostor) {
  10454. return;
  10455. }
  10456. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  10457. };
  10458. // Collisions
  10459. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  10460. var globalPosition = this.getAbsolutePosition();
  10461. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  10462. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  10463. this._collider.radius = this.ellipsoid;
  10464. this.getScene()._getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this._newPositionForCollisions, this);
  10465. this._newPositionForCollisions.subtractToRef(this._oldPositionForCollisions, this._diffPositionForCollisions);
  10466. if (this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  10467. this.position.addInPlace(this._diffPositionForCollisions);
  10468. }
  10469. };
  10470. // Submeshes octree
  10471. /**
  10472. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  10473. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  10474. */
  10475. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  10476. if (maxCapacity === void 0) { maxCapacity = 64; }
  10477. if (maxDepth === void 0) { maxDepth = 2; }
  10478. if (!this._submeshesOctree) {
  10479. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  10480. }
  10481. this.computeWorldMatrix(true);
  10482. // Update octree
  10483. var bbox = this.getBoundingInfo().boundingBox;
  10484. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  10485. return this._submeshesOctree;
  10486. };
  10487. // Collisions
  10488. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  10489. this._generatePointsArray();
  10490. // Transformation
  10491. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  10492. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  10493. subMesh._lastColliderWorldVertices = [];
  10494. subMesh._trianglePlanes = [];
  10495. var start = subMesh.verticesStart;
  10496. var end = (subMesh.verticesStart + subMesh.verticesCount);
  10497. for (var i = start; i < end; i++) {
  10498. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  10499. }
  10500. }
  10501. // Collide
  10502. collider._collide(subMesh, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart);
  10503. };
  10504. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  10505. var subMeshes;
  10506. var len;
  10507. // Octrees
  10508. if (this._submeshesOctree && this.useOctreeForCollisions) {
  10509. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  10510. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  10511. len = intersections.length;
  10512. subMeshes = intersections.data;
  10513. }
  10514. else {
  10515. subMeshes = this.subMeshes;
  10516. len = subMeshes.length;
  10517. }
  10518. for (var index = 0; index < len; index++) {
  10519. var subMesh = subMeshes[index];
  10520. // Bounding test
  10521. if (len > 1 && !subMesh._checkCollision(collider))
  10522. continue;
  10523. this._collideForSubMesh(subMesh, transformMatrix, collider);
  10524. }
  10525. };
  10526. AbstractMesh.prototype._checkCollision = function (collider) {
  10527. // Bounding box test
  10528. if (!this._boundingInfo._checkCollision(collider))
  10529. return;
  10530. // Transformation matrix
  10531. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  10532. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  10533. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  10534. };
  10535. // Picking
  10536. AbstractMesh.prototype._generatePointsArray = function () {
  10537. return false;
  10538. };
  10539. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  10540. var pickingInfo = new BABYLON.PickingInfo();
  10541. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  10542. return pickingInfo;
  10543. }
  10544. if (!this._generatePointsArray()) {
  10545. return pickingInfo;
  10546. }
  10547. var intersectInfo = null;
  10548. // Octrees
  10549. var subMeshes;
  10550. var len;
  10551. if (this._submeshesOctree && this.useOctreeForPicking) {
  10552. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  10553. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  10554. len = intersections.length;
  10555. subMeshes = intersections.data;
  10556. }
  10557. else {
  10558. subMeshes = this.subMeshes;
  10559. len = subMeshes.length;
  10560. }
  10561. for (var index = 0; index < len; index++) {
  10562. var subMesh = subMeshes[index];
  10563. // Bounding test
  10564. if (len > 1 && !subMesh.canIntersects(ray))
  10565. continue;
  10566. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  10567. if (currentIntersectInfo) {
  10568. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  10569. intersectInfo = currentIntersectInfo;
  10570. intersectInfo.subMeshId = index;
  10571. if (fastCheck) {
  10572. break;
  10573. }
  10574. }
  10575. }
  10576. }
  10577. if (intersectInfo) {
  10578. // Get picked point
  10579. var world = this.getWorldMatrix();
  10580. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  10581. var direction = ray.direction.clone();
  10582. direction = direction.scale(intersectInfo.distance);
  10583. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  10584. var pickedPoint = worldOrigin.add(worldDirection);
  10585. // Return result
  10586. pickingInfo.hit = true;
  10587. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  10588. pickingInfo.pickedPoint = pickedPoint;
  10589. pickingInfo.pickedMesh = this;
  10590. pickingInfo.bu = intersectInfo.bu;
  10591. pickingInfo.bv = intersectInfo.bv;
  10592. pickingInfo.faceId = intersectInfo.faceId;
  10593. pickingInfo.subMeshId = intersectInfo.subMeshId;
  10594. return pickingInfo;
  10595. }
  10596. return pickingInfo;
  10597. };
  10598. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  10599. return null;
  10600. };
  10601. AbstractMesh.prototype.releaseSubMeshes = function () {
  10602. if (this.subMeshes) {
  10603. while (this.subMeshes.length) {
  10604. this.subMeshes[0].dispose();
  10605. }
  10606. }
  10607. else {
  10608. this.subMeshes = new Array();
  10609. }
  10610. };
  10611. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  10612. var index;
  10613. // Physics
  10614. if (this.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  10615. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  10616. }
  10617. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  10618. var other = this._intersectionsInProgress[index];
  10619. var pos = other._intersectionsInProgress.indexOf(this);
  10620. other._intersectionsInProgress.splice(pos, 1);
  10621. }
  10622. this._intersectionsInProgress = [];
  10623. // SubMeshes
  10624. this.releaseSubMeshes();
  10625. // Remove from scene
  10626. this.getScene().removeMesh(this);
  10627. if (!doNotRecurse) {
  10628. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  10629. if (this.getScene().particleSystems[index].emitter === this) {
  10630. this.getScene().particleSystems[index].dispose();
  10631. index--;
  10632. }
  10633. }
  10634. // Children
  10635. var objects = this.getScene().meshes.slice(0);
  10636. for (index = 0; index < objects.length; index++) {
  10637. if (objects[index].parent === this) {
  10638. objects[index].dispose();
  10639. }
  10640. }
  10641. }
  10642. else {
  10643. for (index = 0; index < this.getScene().meshes.length; index++) {
  10644. var obj = this.getScene().meshes[index];
  10645. if (obj.parent === this) {
  10646. obj.parent = null;
  10647. obj.computeWorldMatrix(true);
  10648. }
  10649. }
  10650. }
  10651. this._onAfterWorldMatrixUpdate = [];
  10652. this._isDisposed = true;
  10653. // Callback
  10654. if (this.onDispose) {
  10655. this.onDispose();
  10656. }
  10657. };
  10658. // Statics
  10659. AbstractMesh._BILLBOARDMODE_NONE = 0;
  10660. AbstractMesh._BILLBOARDMODE_X = 1;
  10661. AbstractMesh._BILLBOARDMODE_Y = 2;
  10662. AbstractMesh._BILLBOARDMODE_Z = 4;
  10663. AbstractMesh._BILLBOARDMODE_ALL = 7;
  10664. return AbstractMesh;
  10665. })(BABYLON.Node);
  10666. BABYLON.AbstractMesh = AbstractMesh;
  10667. })(BABYLON || (BABYLON = {}));
  10668. //# sourceMappingURL=babylon.abstractMesh.js.map
  10669. var BABYLON;
  10670. (function (BABYLON) {
  10671. var _InstancesBatch = (function () {
  10672. function _InstancesBatch() {
  10673. this.mustReturn = false;
  10674. this.visibleInstances = new Array();
  10675. this.renderSelf = new Array();
  10676. }
  10677. return _InstancesBatch;
  10678. })();
  10679. BABYLON._InstancesBatch = _InstancesBatch;
  10680. var Mesh = (function (_super) {
  10681. __extends(Mesh, _super);
  10682. /**
  10683. * @constructor
  10684. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  10685. * @param {Scene} scene - The scene to add this mesh to.
  10686. * @param {Node} parent - The parent of this mesh, if it has one
  10687. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  10688. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  10689. * When false, achieved by calling a clone(), also passing False.
  10690. * This will make creation of children, recursive.
  10691. */
  10692. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  10693. if (parent === void 0) { parent = null; }
  10694. _super.call(this, name, scene);
  10695. // Members
  10696. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  10697. this.instances = new Array();
  10698. this._LODLevels = new Array();
  10699. this._onBeforeRenderCallbacks = new Array();
  10700. this._onAfterRenderCallbacks = new Array();
  10701. this._visibleInstances = {};
  10702. this._renderIdForInstances = new Array();
  10703. this._batchCache = new _InstancesBatch();
  10704. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  10705. if (source) {
  10706. // Geometry
  10707. if (source._geometry) {
  10708. source._geometry.applyToMesh(this);
  10709. }
  10710. // Deep copy
  10711. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton"], []);
  10712. // Material
  10713. this.material = source.material;
  10714. if (!doNotCloneChildren) {
  10715. for (var index = 0; index < scene.meshes.length; index++) {
  10716. var mesh = scene.meshes[index];
  10717. if (mesh.parent === source) {
  10718. // doNotCloneChildren is always going to be False
  10719. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  10720. }
  10721. }
  10722. }
  10723. for (index = 0; index < scene.particleSystems.length; index++) {
  10724. var system = scene.particleSystems[index];
  10725. if (system.emitter === source) {
  10726. system.clone(system.name, this);
  10727. }
  10728. }
  10729. this.computeWorldMatrix(true);
  10730. }
  10731. // Parent
  10732. if (parent !== null) {
  10733. this.parent = parent;
  10734. }
  10735. }
  10736. Object.defineProperty(Mesh, "FRONTSIDE", {
  10737. get: function () {
  10738. return Mesh._FRONTSIDE;
  10739. },
  10740. enumerable: true,
  10741. configurable: true
  10742. });
  10743. Object.defineProperty(Mesh, "BACKSIDE", {
  10744. get: function () {
  10745. return Mesh._BACKSIDE;
  10746. },
  10747. enumerable: true,
  10748. configurable: true
  10749. });
  10750. Object.defineProperty(Mesh, "DOUBLESIDE", {
  10751. get: function () {
  10752. return Mesh._DOUBLESIDE;
  10753. },
  10754. enumerable: true,
  10755. configurable: true
  10756. });
  10757. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  10758. get: function () {
  10759. return Mesh._DEFAULTSIDE;
  10760. },
  10761. enumerable: true,
  10762. configurable: true
  10763. });
  10764. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  10765. // Methods
  10766. get: function () {
  10767. return this._LODLevels.length > 0;
  10768. },
  10769. enumerable: true,
  10770. configurable: true
  10771. });
  10772. Mesh.prototype._sortLODLevels = function () {
  10773. this._LODLevels.sort(function (a, b) {
  10774. if (a.distance < b.distance) {
  10775. return 1;
  10776. }
  10777. if (a.distance > b.distance) {
  10778. return -1;
  10779. }
  10780. return 0;
  10781. });
  10782. };
  10783. /**
  10784. * Add a mesh as LOD level triggered at the given distance.
  10785. * @param {number} distance - the distance from the center of the object to show this level
  10786. * @param {BABYLON.Mesh} mesh - the mesh to be added as LOD level
  10787. * @return {BABYLON.Mesh} this mesh (for chaining)
  10788. */
  10789. Mesh.prototype.addLODLevel = function (distance, mesh) {
  10790. if (mesh && mesh._masterMesh) {
  10791. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  10792. return this;
  10793. }
  10794. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  10795. this._LODLevels.push(level);
  10796. if (mesh) {
  10797. mesh._masterMesh = this;
  10798. }
  10799. this._sortLODLevels();
  10800. return this;
  10801. };
  10802. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  10803. for (var index = 0; index < this._LODLevels.length; index++) {
  10804. var level = this._LODLevels[index];
  10805. if (level.distance === distance) {
  10806. return level.mesh;
  10807. }
  10808. }
  10809. return null;
  10810. };
  10811. /**
  10812. * Remove a mesh from the LOD array
  10813. * @param {BABYLON.Mesh} mesh - the mesh to be removed.
  10814. * @return {BABYLON.Mesh} this mesh (for chaining)
  10815. */
  10816. Mesh.prototype.removeLODLevel = function (mesh) {
  10817. for (var index = 0; index < this._LODLevels.length; index++) {
  10818. if (this._LODLevels[index].mesh === mesh) {
  10819. this._LODLevels.splice(index, 1);
  10820. if (mesh) {
  10821. mesh._masterMesh = null;
  10822. }
  10823. }
  10824. }
  10825. this._sortLODLevels();
  10826. return this;
  10827. };
  10828. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  10829. if (!this._LODLevels || this._LODLevels.length === 0) {
  10830. return this;
  10831. }
  10832. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  10833. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  10834. return this;
  10835. }
  10836. for (var index = 0; index < this._LODLevels.length; index++) {
  10837. var level = this._LODLevels[index];
  10838. if (level.distance < distanceToCamera) {
  10839. if (level.mesh) {
  10840. level.mesh._preActivate();
  10841. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  10842. }
  10843. return level.mesh;
  10844. }
  10845. }
  10846. return this;
  10847. };
  10848. Object.defineProperty(Mesh.prototype, "geometry", {
  10849. get: function () {
  10850. return this._geometry;
  10851. },
  10852. enumerable: true,
  10853. configurable: true
  10854. });
  10855. Mesh.prototype.getTotalVertices = function () {
  10856. if (!this._geometry) {
  10857. return 0;
  10858. }
  10859. return this._geometry.getTotalVertices();
  10860. };
  10861. Mesh.prototype.getVerticesData = function (kind) {
  10862. if (!this._geometry) {
  10863. return null;
  10864. }
  10865. return this._geometry.getVerticesData(kind);
  10866. };
  10867. Mesh.prototype.getVertexBuffer = function (kind) {
  10868. if (!this._geometry) {
  10869. return undefined;
  10870. }
  10871. return this._geometry.getVertexBuffer(kind);
  10872. };
  10873. Mesh.prototype.isVerticesDataPresent = function (kind) {
  10874. if (!this._geometry) {
  10875. if (this._delayInfo) {
  10876. return this._delayInfo.indexOf(kind) !== -1;
  10877. }
  10878. return false;
  10879. }
  10880. return this._geometry.isVerticesDataPresent(kind);
  10881. };
  10882. Mesh.prototype.getVerticesDataKinds = function () {
  10883. if (!this._geometry) {
  10884. var result = [];
  10885. if (this._delayInfo) {
  10886. for (var kind in this._delayInfo) {
  10887. result.push(kind);
  10888. }
  10889. }
  10890. return result;
  10891. }
  10892. return this._geometry.getVerticesDataKinds();
  10893. };
  10894. Mesh.prototype.getTotalIndices = function () {
  10895. if (!this._geometry) {
  10896. return 0;
  10897. }
  10898. return this._geometry.getTotalIndices();
  10899. };
  10900. Mesh.prototype.getIndices = function () {
  10901. if (!this._geometry) {
  10902. return [];
  10903. }
  10904. return this._geometry.getIndices();
  10905. };
  10906. Object.defineProperty(Mesh.prototype, "isBlocked", {
  10907. get: function () {
  10908. return this._masterMesh !== null && this._masterMesh !== undefined;
  10909. },
  10910. enumerable: true,
  10911. configurable: true
  10912. });
  10913. Mesh.prototype.isReady = function () {
  10914. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  10915. return false;
  10916. }
  10917. return _super.prototype.isReady.call(this);
  10918. };
  10919. Mesh.prototype.isDisposed = function () {
  10920. return this._isDisposed;
  10921. };
  10922. // Methods
  10923. Mesh.prototype._preActivate = function () {
  10924. var sceneRenderId = this.getScene().getRenderId();
  10925. if (this._preActivateId === sceneRenderId) {
  10926. return;
  10927. }
  10928. this._preActivateId = sceneRenderId;
  10929. this._visibleInstances = null;
  10930. };
  10931. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  10932. if (!this._visibleInstances) {
  10933. this._visibleInstances = {};
  10934. this._visibleInstances.defaultRenderId = renderId;
  10935. this._visibleInstances.selfDefaultRenderId = this._renderId;
  10936. }
  10937. if (!this._visibleInstances[renderId]) {
  10938. this._visibleInstances[renderId] = new Array();
  10939. }
  10940. this._visibleInstances[renderId].push(instance);
  10941. };
  10942. Mesh.prototype.refreshBoundingInfo = function () {
  10943. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  10944. if (data) {
  10945. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  10946. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  10947. }
  10948. if (this.subMeshes) {
  10949. for (var index = 0; index < this.subMeshes.length; index++) {
  10950. this.subMeshes[index].refreshBoundingInfo();
  10951. }
  10952. }
  10953. this._updateBoundingInfo();
  10954. };
  10955. Mesh.prototype._createGlobalSubMesh = function () {
  10956. var totalVertices = this.getTotalVertices();
  10957. if (!totalVertices || !this.getIndices()) {
  10958. return null;
  10959. }
  10960. this.releaseSubMeshes();
  10961. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  10962. };
  10963. Mesh.prototype.subdivide = function (count) {
  10964. if (count < 1) {
  10965. return;
  10966. }
  10967. var totalIndices = this.getTotalIndices();
  10968. var subdivisionSize = (totalIndices / count) | 0;
  10969. var offset = 0;
  10970. while (subdivisionSize % 3 !== 0) {
  10971. subdivisionSize++;
  10972. }
  10973. this.releaseSubMeshes();
  10974. for (var index = 0; index < count; index++) {
  10975. if (offset >= totalIndices) {
  10976. break;
  10977. }
  10978. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  10979. offset += subdivisionSize;
  10980. }
  10981. this.synchronizeInstances();
  10982. };
  10983. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  10984. if (kind instanceof Array) {
  10985. var temp = data;
  10986. data = kind;
  10987. kind = temp;
  10988. BABYLON.Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  10989. }
  10990. if (!this._geometry) {
  10991. var vertexData = new BABYLON.VertexData();
  10992. vertexData.set(data, kind);
  10993. var scene = this.getScene();
  10994. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  10995. }
  10996. else {
  10997. this._geometry.setVerticesData(kind, data, updatable, stride);
  10998. }
  10999. };
  11000. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  11001. if (!this._geometry) {
  11002. return;
  11003. }
  11004. if (!makeItUnique) {
  11005. this._geometry.updateVerticesData(kind, data, updateExtends);
  11006. }
  11007. else {
  11008. this.makeGeometryUnique();
  11009. this.updateVerticesData(kind, data, updateExtends, false);
  11010. }
  11011. };
  11012. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  11013. if (!this._geometry) {
  11014. return;
  11015. }
  11016. if (!makeItUnique) {
  11017. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  11018. }
  11019. else {
  11020. this.makeGeometryUnique();
  11021. this.updateVerticesDataDirectly(kind, data, offset, false);
  11022. }
  11023. };
  11024. Mesh.prototype.makeGeometryUnique = function () {
  11025. if (!this._geometry) {
  11026. return;
  11027. }
  11028. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  11029. geometry.applyToMesh(this);
  11030. };
  11031. Mesh.prototype.setIndices = function (indices, totalVertices) {
  11032. if (!this._geometry) {
  11033. var vertexData = new BABYLON.VertexData();
  11034. vertexData.indices = indices;
  11035. var scene = this.getScene();
  11036. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  11037. }
  11038. else {
  11039. this._geometry.setIndices(indices, totalVertices);
  11040. }
  11041. };
  11042. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  11043. var engine = this.getScene().getEngine();
  11044. // Wireframe
  11045. var indexToBind;
  11046. switch (fillMode) {
  11047. case BABYLON.Material.PointFillMode:
  11048. indexToBind = null;
  11049. break;
  11050. case BABYLON.Material.WireFrameFillMode:
  11051. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  11052. break;
  11053. default:
  11054. case BABYLON.Material.TriangleFillMode:
  11055. indexToBind = this._geometry.getIndexBuffer();
  11056. break;
  11057. }
  11058. // VBOs
  11059. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  11060. };
  11061. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  11062. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  11063. return;
  11064. }
  11065. var engine = this.getScene().getEngine();
  11066. switch (fillMode) {
  11067. case BABYLON.Material.PointFillMode:
  11068. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  11069. break;
  11070. case BABYLON.Material.WireFrameFillMode:
  11071. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  11072. break;
  11073. default:
  11074. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  11075. }
  11076. };
  11077. Mesh.prototype.registerBeforeRender = function (func) {
  11078. this._onBeforeRenderCallbacks.push(func);
  11079. };
  11080. Mesh.prototype.unregisterBeforeRender = function (func) {
  11081. var index = this._onBeforeRenderCallbacks.indexOf(func);
  11082. if (index > -1) {
  11083. this._onBeforeRenderCallbacks.splice(index, 1);
  11084. }
  11085. };
  11086. Mesh.prototype.registerAfterRender = function (func) {
  11087. this._onAfterRenderCallbacks.push(func);
  11088. };
  11089. Mesh.prototype.unregisterAfterRender = function (func) {
  11090. var index = this._onAfterRenderCallbacks.indexOf(func);
  11091. if (index > -1) {
  11092. this._onAfterRenderCallbacks.splice(index, 1);
  11093. }
  11094. };
  11095. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  11096. var scene = this.getScene();
  11097. this._batchCache.mustReturn = false;
  11098. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  11099. this._batchCache.visibleInstances[subMeshId] = null;
  11100. if (this._visibleInstances) {
  11101. var currentRenderId = scene.getRenderId();
  11102. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  11103. var selfRenderId = this._renderId;
  11104. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  11105. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  11106. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  11107. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  11108. }
  11109. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  11110. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  11111. this._batchCache.mustReturn = true;
  11112. return this._batchCache;
  11113. }
  11114. if (currentRenderId !== selfRenderId) {
  11115. this._batchCache.renderSelf[subMeshId] = false;
  11116. }
  11117. }
  11118. this._renderIdForInstances[subMeshId] = currentRenderId;
  11119. }
  11120. return this._batchCache;
  11121. };
  11122. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  11123. var visibleInstances = batch.visibleInstances[subMesh._id];
  11124. var matricesCount = visibleInstances.length + 1;
  11125. var bufferSize = matricesCount * 16 * 4;
  11126. while (this._instancesBufferSize < bufferSize) {
  11127. this._instancesBufferSize *= 2;
  11128. }
  11129. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  11130. if (this._worldMatricesInstancesBuffer) {
  11131. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  11132. }
  11133. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  11134. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  11135. }
  11136. var offset = 0;
  11137. var instancesCount = 0;
  11138. var world = this.getWorldMatrix();
  11139. if (batch.renderSelf[subMesh._id]) {
  11140. world.copyToArray(this._worldMatricesInstancesArray, offset);
  11141. offset += 16;
  11142. instancesCount++;
  11143. }
  11144. if (visibleInstances) {
  11145. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  11146. var instance = visibleInstances[instanceIndex];
  11147. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  11148. offset += 16;
  11149. instancesCount++;
  11150. }
  11151. }
  11152. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  11153. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  11154. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  11155. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  11156. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  11157. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  11158. this._draw(subMesh, fillMode, instancesCount);
  11159. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  11160. };
  11161. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  11162. var scene = this.getScene();
  11163. var engine = scene.getEngine();
  11164. if (hardwareInstancedRendering) {
  11165. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  11166. }
  11167. else {
  11168. if (batch.renderSelf[subMesh._id]) {
  11169. // Draw
  11170. if (onBeforeDraw) {
  11171. onBeforeDraw(false, this.getWorldMatrix());
  11172. }
  11173. this._draw(subMesh, fillMode);
  11174. }
  11175. if (batch.visibleInstances[subMesh._id]) {
  11176. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  11177. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  11178. // World
  11179. var world = instance.getWorldMatrix();
  11180. if (onBeforeDraw) {
  11181. onBeforeDraw(true, world);
  11182. }
  11183. // Draw
  11184. this._draw(subMesh, fillMode);
  11185. }
  11186. }
  11187. }
  11188. };
  11189. Mesh.prototype.render = function (subMesh) {
  11190. var scene = this.getScene();
  11191. // Managing instances
  11192. var batch = this._getInstancesRenderList(subMesh._id);
  11193. if (batch.mustReturn) {
  11194. return;
  11195. }
  11196. // Checking geometry state
  11197. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  11198. return;
  11199. }
  11200. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  11201. this._onBeforeRenderCallbacks[callbackIndex](this);
  11202. }
  11203. var engine = scene.getEngine();
  11204. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  11205. // Material
  11206. var effectiveMaterial = subMesh.getMaterial();
  11207. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  11208. return;
  11209. }
  11210. // Outline - step 1
  11211. var savedDepthWrite = engine.getDepthWrite();
  11212. if (this.renderOutline) {
  11213. engine.setDepthWrite(false);
  11214. scene.getOutlineRenderer().render(subMesh, batch);
  11215. engine.setDepthWrite(savedDepthWrite);
  11216. }
  11217. effectiveMaterial._preBind();
  11218. var effect = effectiveMaterial.getEffect();
  11219. // Bind
  11220. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  11221. this._bind(subMesh, effect, fillMode);
  11222. var world = this.getWorldMatrix();
  11223. effectiveMaterial.bind(world, this);
  11224. // Draw
  11225. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  11226. if (isInstance) {
  11227. effectiveMaterial.bindOnlyWorldMatrix(world);
  11228. }
  11229. });
  11230. // Unbind
  11231. effectiveMaterial.unbind();
  11232. // Outline - step 2
  11233. if (this.renderOutline && savedDepthWrite) {
  11234. engine.setDepthWrite(true);
  11235. engine.setColorWrite(false);
  11236. scene.getOutlineRenderer().render(subMesh, batch);
  11237. engine.setColorWrite(true);
  11238. }
  11239. // Overlay
  11240. if (this.renderOverlay) {
  11241. var currentMode = engine.getAlphaMode();
  11242. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  11243. scene.getOutlineRenderer().render(subMesh, batch, true);
  11244. engine.setAlphaMode(currentMode);
  11245. }
  11246. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  11247. this._onAfterRenderCallbacks[callbackIndex](this);
  11248. }
  11249. };
  11250. Mesh.prototype.getEmittedParticleSystems = function () {
  11251. var results = new Array();
  11252. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  11253. var particleSystem = this.getScene().particleSystems[index];
  11254. if (particleSystem.emitter === this) {
  11255. results.push(particleSystem);
  11256. }
  11257. }
  11258. return results;
  11259. };
  11260. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  11261. var results = new Array();
  11262. var descendants = this.getDescendants();
  11263. descendants.push(this);
  11264. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  11265. var particleSystem = this.getScene().particleSystems[index];
  11266. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  11267. results.push(particleSystem);
  11268. }
  11269. }
  11270. return results;
  11271. };
  11272. Mesh.prototype.getChildren = function () {
  11273. var results = [];
  11274. for (var index = 0; index < this.getScene().meshes.length; index++) {
  11275. var mesh = this.getScene().meshes[index];
  11276. if (mesh.parent === this) {
  11277. results.push(mesh);
  11278. }
  11279. }
  11280. return results;
  11281. };
  11282. Mesh.prototype._checkDelayState = function () {
  11283. var _this = this;
  11284. var that = this;
  11285. var scene = this.getScene();
  11286. if (this._geometry) {
  11287. this._geometry.load(scene);
  11288. }
  11289. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  11290. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  11291. scene._addPendingData(that);
  11292. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  11293. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  11294. if (data instanceof ArrayBuffer) {
  11295. _this._delayLoadingFunction(data, _this);
  11296. }
  11297. else {
  11298. _this._delayLoadingFunction(JSON.parse(data), _this);
  11299. }
  11300. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  11301. scene._removePendingData(_this);
  11302. }, function () {
  11303. }, scene.database, getBinaryData);
  11304. }
  11305. };
  11306. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  11307. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  11308. return false;
  11309. }
  11310. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  11311. return false;
  11312. }
  11313. this._checkDelayState();
  11314. return true;
  11315. };
  11316. Mesh.prototype.setMaterialByID = function (id) {
  11317. var materials = this.getScene().materials;
  11318. for (var index = 0; index < materials.length; index++) {
  11319. if (materials[index].id === id) {
  11320. this.material = materials[index];
  11321. return;
  11322. }
  11323. }
  11324. // Multi
  11325. var multiMaterials = this.getScene().multiMaterials;
  11326. for (index = 0; index < multiMaterials.length; index++) {
  11327. if (multiMaterials[index].id === id) {
  11328. this.material = multiMaterials[index];
  11329. return;
  11330. }
  11331. }
  11332. };
  11333. Mesh.prototype.getAnimatables = function () {
  11334. var results = [];
  11335. if (this.material) {
  11336. results.push(this.material);
  11337. }
  11338. if (this.skeleton) {
  11339. results.push(this.skeleton);
  11340. }
  11341. return results;
  11342. };
  11343. // Geometry
  11344. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  11345. // Position
  11346. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  11347. return;
  11348. }
  11349. this._resetPointsArrayCache();
  11350. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11351. var temp = [];
  11352. for (var index = 0; index < data.length; index += 3) {
  11353. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  11354. }
  11355. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  11356. // Normals
  11357. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  11358. return;
  11359. }
  11360. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  11361. for (index = 0; index < data.length; index += 3) {
  11362. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  11363. }
  11364. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  11365. };
  11366. // Cache
  11367. Mesh.prototype._resetPointsArrayCache = function () {
  11368. this._positions = null;
  11369. };
  11370. Mesh.prototype._generatePointsArray = function () {
  11371. if (this._positions)
  11372. return true;
  11373. this._positions = [];
  11374. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11375. if (!data) {
  11376. return false;
  11377. }
  11378. for (var index = 0; index < data.length; index += 3) {
  11379. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  11380. }
  11381. return true;
  11382. };
  11383. // Clone
  11384. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  11385. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  11386. };
  11387. // Dispose
  11388. Mesh.prototype.dispose = function (doNotRecurse) {
  11389. if (this._geometry) {
  11390. this._geometry.releaseForMesh(this, true);
  11391. }
  11392. // Instances
  11393. if (this._worldMatricesInstancesBuffer) {
  11394. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  11395. this._worldMatricesInstancesBuffer = null;
  11396. }
  11397. while (this.instances.length) {
  11398. this.instances[0].dispose();
  11399. }
  11400. _super.prototype.dispose.call(this, doNotRecurse);
  11401. };
  11402. // Geometric tools
  11403. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  11404. var _this = this;
  11405. var scene = this.getScene();
  11406. var onload = function (img) {
  11407. // Getting height map data
  11408. var canvas = document.createElement("canvas");
  11409. var context = canvas.getContext("2d");
  11410. var heightMapWidth = img.width;
  11411. var heightMapHeight = img.height;
  11412. canvas.width = heightMapWidth;
  11413. canvas.height = heightMapHeight;
  11414. context.drawImage(img, 0, 0);
  11415. // Create VertexData from map data
  11416. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  11417. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  11418. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  11419. //execute success callback, if set
  11420. if (onSuccess) {
  11421. onSuccess(_this);
  11422. }
  11423. };
  11424. BABYLON.Tools.LoadImage(url, onload, function () {
  11425. }, scene.database);
  11426. };
  11427. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  11428. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  11429. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  11430. return;
  11431. }
  11432. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11433. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  11434. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  11435. var position = BABYLON.Vector3.Zero();
  11436. var normal = BABYLON.Vector3.Zero();
  11437. var uv = BABYLON.Vector2.Zero();
  11438. for (var index = 0; index < positions.length; index += 3) {
  11439. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  11440. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  11441. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  11442. // Compute height
  11443. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  11444. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  11445. var pos = (u + v * heightMapWidth) * 4;
  11446. var r = buffer[pos] / 255.0;
  11447. var g = buffer[pos + 1] / 255.0;
  11448. var b = buffer[pos + 2] / 255.0;
  11449. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  11450. normal.normalize();
  11451. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  11452. position = position.add(normal);
  11453. position.toArray(positions, index);
  11454. }
  11455. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  11456. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  11457. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  11458. };
  11459. Mesh.prototype.convertToFlatShadedMesh = function () {
  11460. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  11461. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  11462. var kinds = this.getVerticesDataKinds();
  11463. var vbs = [];
  11464. var data = [];
  11465. var newdata = [];
  11466. var updatableNormals = false;
  11467. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  11468. var kind = kinds[kindIndex];
  11469. var vertexBuffer = this.getVertexBuffer(kind);
  11470. if (kind === BABYLON.VertexBuffer.NormalKind) {
  11471. updatableNormals = vertexBuffer.isUpdatable();
  11472. kinds.splice(kindIndex, 1);
  11473. kindIndex--;
  11474. continue;
  11475. }
  11476. vbs[kind] = vertexBuffer;
  11477. data[kind] = vbs[kind].getData();
  11478. newdata[kind] = [];
  11479. }
  11480. // Save previous submeshes
  11481. var previousSubmeshes = this.subMeshes.slice(0);
  11482. var indices = this.getIndices();
  11483. var totalIndices = this.getTotalIndices();
  11484. for (var index = 0; index < totalIndices; index++) {
  11485. var vertexIndex = indices[index];
  11486. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  11487. kind = kinds[kindIndex];
  11488. var stride = vbs[kind].getStrideSize();
  11489. for (var offset = 0; offset < stride; offset++) {
  11490. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  11491. }
  11492. }
  11493. }
  11494. // Updating faces & normal
  11495. var normals = [];
  11496. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  11497. for (index = 0; index < totalIndices; index += 3) {
  11498. indices[index] = index;
  11499. indices[index + 1] = index + 1;
  11500. indices[index + 2] = index + 2;
  11501. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  11502. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  11503. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  11504. var p1p2 = p1.subtract(p2);
  11505. var p3p2 = p3.subtract(p2);
  11506. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  11507. for (var localIndex = 0; localIndex < 3; localIndex++) {
  11508. normals.push(normal.x);
  11509. normals.push(normal.y);
  11510. normals.push(normal.z);
  11511. }
  11512. }
  11513. this.setIndices(indices);
  11514. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  11515. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  11516. kind = kinds[kindIndex];
  11517. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  11518. }
  11519. // Updating submeshes
  11520. this.releaseSubMeshes();
  11521. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  11522. var previousOne = previousSubmeshes[submeshIndex];
  11523. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  11524. }
  11525. this.synchronizeInstances();
  11526. };
  11527. // Instances
  11528. Mesh.prototype.createInstance = function (name) {
  11529. return new BABYLON.InstancedMesh(name, this);
  11530. };
  11531. Mesh.prototype.synchronizeInstances = function () {
  11532. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  11533. var instance = this.instances[instanceIndex];
  11534. instance._syncSubMeshes();
  11535. }
  11536. };
  11537. /**
  11538. * Simplify the mesh according to the given array of settings.
  11539. * Function will return immediately and will simplify async.
  11540. * @param settings a collection of simplification settings.
  11541. * @param parallelProcessing should all levels calculate parallel or one after the other.
  11542. * @param type the type of simplification to run.
  11543. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  11544. */
  11545. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  11546. if (parallelProcessing === void 0) { parallelProcessing = true; }
  11547. if (simplificationType === void 0) { simplificationType = 0 /* QUADRATIC */; }
  11548. this.getScene().simplificationQueue.addTask({
  11549. settings: settings,
  11550. parallelProcessing: parallelProcessing,
  11551. mesh: this,
  11552. simplificationType: simplificationType,
  11553. successCallback: successCallback
  11554. });
  11555. };
  11556. /**
  11557. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  11558. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  11559. * This should be used together with the simplification to avoid disappearing triangles.
  11560. * @param successCallback an optional success callback to be called after the optimization finished.
  11561. */
  11562. Mesh.prototype.optimizeIndices = function (successCallback) {
  11563. var _this = this;
  11564. var indices = this.getIndices();
  11565. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11566. var vectorPositions = [];
  11567. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  11568. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  11569. }
  11570. var dupes = [];
  11571. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  11572. var realPos = vectorPositions.length - 1 - iteration;
  11573. var testedPosition = vectorPositions[realPos];
  11574. for (var j = 0; j < realPos; ++j) {
  11575. var againstPosition = vectorPositions[j];
  11576. if (testedPosition.equals(againstPosition)) {
  11577. dupes[realPos] = j;
  11578. break;
  11579. }
  11580. }
  11581. }, function () {
  11582. for (var i = 0; i < indices.length; ++i) {
  11583. indices[i] = dupes[indices[i]] || indices[i];
  11584. }
  11585. //indices are now reordered
  11586. var originalSubMeshes = _this.subMeshes.slice(0);
  11587. _this.setIndices(indices);
  11588. _this.subMeshes = originalSubMeshes;
  11589. if (successCallback) {
  11590. successCallback(_this);
  11591. }
  11592. });
  11593. };
  11594. // Statics
  11595. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation) {
  11596. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11597. var ribbon = new Mesh(name, scene);
  11598. var vertexData = BABYLON.VertexData.CreateRibbon(pathArray, closeArray, closePath, offset, sideOrientation);
  11599. vertexData.applyToMesh(ribbon, updatable);
  11600. return ribbon;
  11601. };
  11602. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  11603. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11604. var box = new Mesh(name, scene);
  11605. var vertexData = BABYLON.VertexData.CreateBox(size, sideOrientation);
  11606. vertexData.applyToMesh(box, updatable);
  11607. return box;
  11608. };
  11609. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  11610. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11611. var sphere = new Mesh(name, scene);
  11612. var vertexData = BABYLON.VertexData.CreateSphere(segments, diameter, sideOrientation);
  11613. vertexData.applyToMesh(sphere, updatable);
  11614. return sphere;
  11615. };
  11616. // Cylinder and cone (Code inspired by SharpDX.org)
  11617. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  11618. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11619. // subdivisions is a new parameter, we need to support old signature
  11620. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  11621. if (scene !== undefined) {
  11622. updatable = scene;
  11623. }
  11624. scene = subdivisions;
  11625. subdivisions = 1;
  11626. }
  11627. var cylinder = new Mesh(name, scene);
  11628. var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions);
  11629. vertexData.applyToMesh(cylinder, updatable);
  11630. return cylinder;
  11631. };
  11632. // Torus (Code from SharpDX.org)
  11633. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  11634. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11635. var torus = new Mesh(name, scene);
  11636. var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation, sideOrientation);
  11637. vertexData.applyToMesh(torus, updatable);
  11638. return torus;
  11639. };
  11640. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  11641. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11642. var torusKnot = new Mesh(name, scene);
  11643. var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q, sideOrientation);
  11644. vertexData.applyToMesh(torusKnot, updatable);
  11645. return torusKnot;
  11646. };
  11647. // Lines
  11648. Mesh.CreateLines = function (name, points, scene, updatable) {
  11649. var lines = new BABYLON.LinesMesh(name, scene, updatable);
  11650. var vertexData = BABYLON.VertexData.CreateLines(points);
  11651. vertexData.applyToMesh(lines, updatable);
  11652. return lines;
  11653. };
  11654. // Extrusion
  11655. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, scene, updatable, sideOrientation) {
  11656. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11657. scale = scale || 1;
  11658. rotation = rotation || 0;
  11659. var extruded = Mesh._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, false, scene, updatable, sideOrientation);
  11660. return extruded;
  11661. };
  11662. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, scene, updatable, sideOrientation) {
  11663. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11664. var extrudedCustom = Mesh._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, true, scene, updatable, sideOrientation);
  11665. return extrudedCustom;
  11666. };
  11667. Mesh._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, custom, scene, updtbl, side) {
  11668. var path3D = new BABYLON.Path3D(curve);
  11669. var tangents = path3D.getTangents();
  11670. var normals = path3D.getNormals();
  11671. var binormals = path3D.getBinormals();
  11672. var distances = path3D.getDistances();
  11673. var shapePaths = new Array();
  11674. var angle = 0;
  11675. var returnScale = function (i, distance) {
  11676. return scale;
  11677. };
  11678. var returnRotation = function (i, distance) {
  11679. return rotation;
  11680. };
  11681. var rotate = custom ? rotateFunction : returnRotation;
  11682. var scl = custom ? scaleFunction : returnScale;
  11683. for (var i = 0; i < curve.length; i++) {
  11684. var shapePath = new Array();
  11685. var angleStep = rotate(i, distances[i]);
  11686. var scaleRatio = scl(i, distances[i]);
  11687. for (var p = 0; p < shape.length; p++) {
  11688. var rotationMatrix = BABYLON.Matrix.RotationAxis(tangents[i], angle);
  11689. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  11690. var rotated = BABYLON.Vector3.TransformCoordinates(planed, rotationMatrix).scaleInPlace(scaleRatio).add(curve[i]);
  11691. shapePath.push(rotated);
  11692. }
  11693. shapePaths.push(shapePath);
  11694. angle += angleStep;
  11695. }
  11696. var extrudedGeneric = Mesh.CreateRibbon(name, shapePaths, rbCA, rbCP, 0, scene, updtbl, side);
  11697. return extrudedGeneric;
  11698. };
  11699. // Plane & ground
  11700. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  11701. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11702. var plane = new Mesh(name, scene);
  11703. var vertexData = BABYLON.VertexData.CreatePlane(size, sideOrientation);
  11704. vertexData.applyToMesh(plane, updatable);
  11705. return plane;
  11706. };
  11707. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  11708. var ground = new BABYLON.GroundMesh(name, scene);
  11709. ground._setReady(false);
  11710. ground._subdivisions = subdivisions;
  11711. var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
  11712. vertexData.applyToMesh(ground, updatable);
  11713. ground._setReady(true);
  11714. return ground;
  11715. };
  11716. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  11717. var tiledGround = new Mesh(name, scene);
  11718. var vertexData = BABYLON.VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  11719. vertexData.applyToMesh(tiledGround, updatable);
  11720. return tiledGround;
  11721. };
  11722. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  11723. var ground = new BABYLON.GroundMesh(name, scene);
  11724. ground._subdivisions = subdivisions;
  11725. ground._setReady(false);
  11726. var onload = function (img) {
  11727. // Getting height map data
  11728. var canvas = document.createElement("canvas");
  11729. var context = canvas.getContext("2d");
  11730. var heightMapWidth = img.width;
  11731. var heightMapHeight = img.height;
  11732. canvas.width = heightMapWidth;
  11733. canvas.height = heightMapHeight;
  11734. context.drawImage(img, 0, 0);
  11735. // Create VertexData from map data
  11736. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  11737. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  11738. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  11739. vertexData.applyToMesh(ground, updatable);
  11740. ground._setReady(true);
  11741. //execute ready callback, if set
  11742. if (onReady) {
  11743. onReady(ground);
  11744. }
  11745. };
  11746. BABYLON.Tools.LoadImage(url, onload, function () {
  11747. }, scene.database);
  11748. return ground;
  11749. };
  11750. Mesh.CreateTube = function (name, path, radius, tesselation, radiusFunction, scene, updatable, sideOrientation) {
  11751. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11752. var path3D = new BABYLON.Path3D(path);
  11753. var tangents = path3D.getTangents();
  11754. var normals = path3D.getNormals();
  11755. var distances = path3D.getDistances();
  11756. var pi2 = Math.PI * 2;
  11757. var step = pi2 / tesselation;
  11758. var returnRadius = function (i, distance) { return radius; };
  11759. var radiusFunctionFinal = radiusFunction || returnRadius;
  11760. var circlePaths = new Array();
  11761. var circlePath;
  11762. var rad;
  11763. var normal;
  11764. var rotated;
  11765. var rotationMatrix;
  11766. for (var i = 0; i < path.length; i++) {
  11767. rad = radiusFunctionFinal(i, distances[i]); // current radius
  11768. circlePath = Array(); // current circle array
  11769. normal = normals[i]; // current normal
  11770. for (var ang = 0; ang < pi2; ang += step) {
  11771. rotationMatrix = BABYLON.Matrix.RotationAxis(tangents[i], ang);
  11772. rotated = BABYLON.Vector3.TransformCoordinates(normal, rotationMatrix).scaleInPlace(rad).add(path[i]);
  11773. circlePath.push(rotated);
  11774. }
  11775. circlePaths.push(circlePath);
  11776. }
  11777. var tube = Mesh.CreateRibbon(name, circlePaths, false, true, 0, scene, updatable, sideOrientation);
  11778. return tube;
  11779. };
  11780. // Tools
  11781. Mesh.MinMax = function (meshes) {
  11782. var minVector = null;
  11783. var maxVector = null;
  11784. for (var i in meshes) {
  11785. var mesh = meshes[i];
  11786. var boundingBox = mesh.getBoundingInfo().boundingBox;
  11787. if (!minVector) {
  11788. minVector = boundingBox.minimumWorld;
  11789. maxVector = boundingBox.maximumWorld;
  11790. continue;
  11791. }
  11792. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  11793. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  11794. }
  11795. return {
  11796. min: minVector,
  11797. max: maxVector
  11798. };
  11799. };
  11800. Mesh.Center = function (meshesOrMinMaxVector) {
  11801. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  11802. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  11803. };
  11804. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices) {
  11805. if (disposeSource === void 0) { disposeSource = true; }
  11806. var source = meshes[0];
  11807. var material = source.material;
  11808. var scene = source.getScene();
  11809. if (!allow32BitsIndices) {
  11810. var totalVertices = 0;
  11811. for (var index = 0; index < meshes.length; index++) {
  11812. totalVertices += meshes[index].getTotalVertices();
  11813. if (totalVertices > 65536) {
  11814. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  11815. return null;
  11816. }
  11817. }
  11818. }
  11819. // Merge
  11820. var vertexData = BABYLON.VertexData.ExtractFromMesh(source);
  11821. vertexData.transform(source.getWorldMatrix());
  11822. for (index = 1; index < meshes.length; index++) {
  11823. var otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index]);
  11824. otherVertexData.transform(meshes[index].getWorldMatrix());
  11825. vertexData.merge(otherVertexData);
  11826. }
  11827. var newMesh = new Mesh(source.name + "_merged", scene);
  11828. vertexData.applyToMesh(newMesh);
  11829. // Setting properties
  11830. newMesh.material = material;
  11831. newMesh.checkCollisions = source.checkCollisions;
  11832. // Cleaning
  11833. if (disposeSource) {
  11834. for (index = 0; index < meshes.length; index++) {
  11835. meshes[index].dispose();
  11836. }
  11837. }
  11838. return newMesh;
  11839. };
  11840. // Consts
  11841. Mesh._FRONTSIDE = 0;
  11842. Mesh._BACKSIDE = 1;
  11843. Mesh._DOUBLESIDE = 2;
  11844. Mesh._DEFAULTSIDE = 0;
  11845. return Mesh;
  11846. })(BABYLON.AbstractMesh);
  11847. BABYLON.Mesh = Mesh;
  11848. })(BABYLON || (BABYLON = {}));
  11849. //# sourceMappingURL=babylon.mesh.js.map
  11850. var BABYLON;
  11851. (function (BABYLON) {
  11852. var GroundMesh = (function (_super) {
  11853. __extends(GroundMesh, _super);
  11854. function GroundMesh(name, scene) {
  11855. _super.call(this, name, scene);
  11856. this.generateOctree = false;
  11857. this._worldInverse = new BABYLON.Matrix();
  11858. }
  11859. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  11860. get: function () {
  11861. return this._subdivisions;
  11862. },
  11863. enumerable: true,
  11864. configurable: true
  11865. });
  11866. GroundMesh.prototype.optimize = function (chunksCount) {
  11867. this.subdivide(this._subdivisions);
  11868. this.createOrUpdateSubmeshesOctree(32);
  11869. };
  11870. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  11871. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  11872. this.getWorldMatrix().invertToRef(this._worldInverse);
  11873. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  11874. var pickInfo = this.intersects(ray);
  11875. if (pickInfo.hit) {
  11876. return pickInfo.pickedPoint.y;
  11877. }
  11878. return 0;
  11879. };
  11880. return GroundMesh;
  11881. })(BABYLON.Mesh);
  11882. BABYLON.GroundMesh = GroundMesh;
  11883. })(BABYLON || (BABYLON = {}));
  11884. //# sourceMappingURL=babylon.groundMesh.js.map
  11885. var BABYLON;
  11886. (function (BABYLON) {
  11887. /**
  11888. * Creates an instance based on a source mesh.
  11889. */
  11890. var InstancedMesh = (function (_super) {
  11891. __extends(InstancedMesh, _super);
  11892. function InstancedMesh(name, source) {
  11893. _super.call(this, name, source.getScene());
  11894. source.instances.push(this);
  11895. this._sourceMesh = source;
  11896. this.position.copyFrom(source.position);
  11897. this.rotation.copyFrom(source.rotation);
  11898. this.scaling.copyFrom(source.scaling);
  11899. if (source.rotationQuaternion) {
  11900. this.rotationQuaternion = source.rotationQuaternion.clone();
  11901. }
  11902. this.infiniteDistance = source.infiniteDistance;
  11903. this.setPivotMatrix(source.getPivotMatrix());
  11904. this.refreshBoundingInfo();
  11905. this._syncSubMeshes();
  11906. }
  11907. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  11908. // Methods
  11909. get: function () {
  11910. return this._sourceMesh.receiveShadows;
  11911. },
  11912. enumerable: true,
  11913. configurable: true
  11914. });
  11915. Object.defineProperty(InstancedMesh.prototype, "material", {
  11916. get: function () {
  11917. return this._sourceMesh.material;
  11918. },
  11919. enumerable: true,
  11920. configurable: true
  11921. });
  11922. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  11923. get: function () {
  11924. return this._sourceMesh.visibility;
  11925. },
  11926. enumerable: true,
  11927. configurable: true
  11928. });
  11929. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  11930. get: function () {
  11931. return this._sourceMesh.skeleton;
  11932. },
  11933. enumerable: true,
  11934. configurable: true
  11935. });
  11936. InstancedMesh.prototype.getTotalVertices = function () {
  11937. return this._sourceMesh.getTotalVertices();
  11938. };
  11939. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  11940. get: function () {
  11941. return this._sourceMesh;
  11942. },
  11943. enumerable: true,
  11944. configurable: true
  11945. });
  11946. InstancedMesh.prototype.getVerticesData = function (kind) {
  11947. return this._sourceMesh.getVerticesData(kind);
  11948. };
  11949. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  11950. return this._sourceMesh.isVerticesDataPresent(kind);
  11951. };
  11952. InstancedMesh.prototype.getIndices = function () {
  11953. return this._sourceMesh.getIndices();
  11954. };
  11955. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  11956. get: function () {
  11957. return this._sourceMesh._positions;
  11958. },
  11959. enumerable: true,
  11960. configurable: true
  11961. });
  11962. InstancedMesh.prototype.refreshBoundingInfo = function () {
  11963. var data = this._sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11964. if (data) {
  11965. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._sourceMesh.getTotalVertices());
  11966. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  11967. }
  11968. this._updateBoundingInfo();
  11969. };
  11970. InstancedMesh.prototype._preActivate = function () {
  11971. if (this._currentLOD) {
  11972. this._currentLOD._preActivate();
  11973. }
  11974. };
  11975. InstancedMesh.prototype._activate = function (renderId) {
  11976. if (this._currentLOD) {
  11977. this._currentLOD._registerInstanceForRenderId(this, renderId);
  11978. }
  11979. };
  11980. InstancedMesh.prototype.getLOD = function (camera) {
  11981. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  11982. if (this._currentLOD === this.sourceMesh) {
  11983. return this;
  11984. }
  11985. return this._currentLOD;
  11986. };
  11987. InstancedMesh.prototype._syncSubMeshes = function () {
  11988. this.releaseSubMeshes();
  11989. if (this._sourceMesh.subMeshes) {
  11990. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  11991. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  11992. }
  11993. }
  11994. };
  11995. InstancedMesh.prototype._generatePointsArray = function () {
  11996. return this._sourceMesh._generatePointsArray();
  11997. };
  11998. // Clone
  11999. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  12000. var result = this._sourceMesh.createInstance(name);
  12001. // Deep copy
  12002. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  12003. // Bounding info
  12004. this.refreshBoundingInfo();
  12005. // Parent
  12006. if (newParent) {
  12007. result.parent = newParent;
  12008. }
  12009. if (!doNotCloneChildren) {
  12010. for (var index = 0; index < this.getScene().meshes.length; index++) {
  12011. var mesh = this.getScene().meshes[index];
  12012. if (mesh.parent === this) {
  12013. mesh.clone(mesh.name, result);
  12014. }
  12015. }
  12016. }
  12017. result.computeWorldMatrix(true);
  12018. return result;
  12019. };
  12020. // Dispoe
  12021. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  12022. // Remove from mesh
  12023. var index = this._sourceMesh.instances.indexOf(this);
  12024. this._sourceMesh.instances.splice(index, 1);
  12025. _super.prototype.dispose.call(this, doNotRecurse);
  12026. };
  12027. return InstancedMesh;
  12028. })(BABYLON.AbstractMesh);
  12029. BABYLON.InstancedMesh = InstancedMesh;
  12030. })(BABYLON || (BABYLON = {}));
  12031. //# sourceMappingURL=babylon.instancedMesh.js.mapvar BABYLON;
  12032. (function (BABYLON) {
  12033. var SubMesh = (function () {
  12034. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  12035. if (createBoundingBox === void 0) { createBoundingBox = true; }
  12036. this.materialIndex = materialIndex;
  12037. this.verticesStart = verticesStart;
  12038. this.verticesCount = verticesCount;
  12039. this.indexStart = indexStart;
  12040. this.indexCount = indexCount;
  12041. this._renderId = 0;
  12042. this._mesh = mesh;
  12043. this._renderingMesh = renderingMesh || mesh;
  12044. mesh.subMeshes.push(this);
  12045. this._id = mesh.subMeshes.length - 1;
  12046. if (createBoundingBox) {
  12047. this.refreshBoundingInfo();
  12048. mesh.computeWorldMatrix(true);
  12049. }
  12050. }
  12051. SubMesh.prototype.getBoundingInfo = function () {
  12052. return this._boundingInfo;
  12053. };
  12054. SubMesh.prototype.getMesh = function () {
  12055. return this._mesh;
  12056. };
  12057. SubMesh.prototype.getRenderingMesh = function () {
  12058. return this._renderingMesh;
  12059. };
  12060. SubMesh.prototype.getMaterial = function () {
  12061. var rootMaterial = this._renderingMesh.material;
  12062. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  12063. var multiMaterial = rootMaterial;
  12064. return multiMaterial.getSubMaterial(this.materialIndex);
  12065. }
  12066. if (!rootMaterial) {
  12067. return this._mesh.getScene().defaultMaterial;
  12068. }
  12069. return rootMaterial;
  12070. };
  12071. // Methods
  12072. SubMesh.prototype.refreshBoundingInfo = function () {
  12073. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  12074. if (!data) {
  12075. this._boundingInfo = this._mesh._boundingInfo;
  12076. return;
  12077. }
  12078. var indices = this._renderingMesh.getIndices();
  12079. var extend;
  12080. if (this.indexStart === 0 && this.indexCount === indices.length) {
  12081. extend = BABYLON.Tools.ExtractMinAndMax(data, this.verticesStart, this.verticesCount);
  12082. }
  12083. else {
  12084. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  12085. }
  12086. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  12087. };
  12088. SubMesh.prototype._checkCollision = function (collider) {
  12089. return this._boundingInfo._checkCollision(collider);
  12090. };
  12091. SubMesh.prototype.updateBoundingInfo = function (world) {
  12092. if (!this._boundingInfo) {
  12093. this.refreshBoundingInfo();
  12094. }
  12095. this._boundingInfo._update(world);
  12096. };
  12097. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  12098. return this._boundingInfo.isInFrustum(frustumPlanes);
  12099. };
  12100. SubMesh.prototype.render = function () {
  12101. this._renderingMesh.render(this);
  12102. };
  12103. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  12104. if (!this._linesIndexBuffer) {
  12105. var linesIndices = [];
  12106. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  12107. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  12108. }
  12109. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  12110. this.linesIndexCount = linesIndices.length;
  12111. }
  12112. return this._linesIndexBuffer;
  12113. };
  12114. SubMesh.prototype.canIntersects = function (ray) {
  12115. return ray.intersectsBox(this._boundingInfo.boundingBox);
  12116. };
  12117. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  12118. var intersectInfo = null;
  12119. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  12120. var p0 = positions[indices[index]];
  12121. var p1 = positions[indices[index + 1]];
  12122. var p2 = positions[indices[index + 2]];
  12123. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  12124. if (currentIntersectInfo) {
  12125. if (currentIntersectInfo.distance < 0) {
  12126. continue;
  12127. }
  12128. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  12129. intersectInfo = currentIntersectInfo;
  12130. intersectInfo.faceId = index / 3;
  12131. if (fastCheck) {
  12132. break;
  12133. }
  12134. }
  12135. }
  12136. }
  12137. return intersectInfo;
  12138. };
  12139. // Clone
  12140. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  12141. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  12142. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  12143. return result;
  12144. };
  12145. // Dispose
  12146. SubMesh.prototype.dispose = function () {
  12147. if (this._linesIndexBuffer) {
  12148. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  12149. this._linesIndexBuffer = null;
  12150. }
  12151. // Remove from mesh
  12152. var index = this._mesh.subMeshes.indexOf(this);
  12153. this._mesh.subMeshes.splice(index, 1);
  12154. };
  12155. // Statics
  12156. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  12157. var minVertexIndex = Number.MAX_VALUE;
  12158. var maxVertexIndex = -Number.MAX_VALUE;
  12159. renderingMesh = renderingMesh || mesh;
  12160. var indices = renderingMesh.getIndices();
  12161. for (var index = startIndex; index < startIndex + indexCount; index++) {
  12162. var vertexIndex = indices[index];
  12163. if (vertexIndex < minVertexIndex)
  12164. minVertexIndex = vertexIndex;
  12165. if (vertexIndex > maxVertexIndex)
  12166. maxVertexIndex = vertexIndex;
  12167. }
  12168. return new BABYLON.SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  12169. };
  12170. return SubMesh;
  12171. })();
  12172. BABYLON.SubMesh = SubMesh;
  12173. })(BABYLON || (BABYLON = {}));
  12174. //# sourceMappingURL=babylon.subMesh.js.mapvar BABYLON;
  12175. (function (BABYLON) {
  12176. var BaseTexture = (function () {
  12177. function BaseTexture(scene) {
  12178. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  12179. this.hasAlpha = false;
  12180. this.getAlphaFromRGB = false;
  12181. this.level = 1;
  12182. this.isCube = false;
  12183. this.isRenderTarget = false;
  12184. this.animations = new Array();
  12185. this.coordinatesIndex = 0;
  12186. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  12187. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  12188. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  12189. this.anisotropicFilteringLevel = 4;
  12190. this._scene = scene;
  12191. this._scene.textures.push(this);
  12192. }
  12193. BaseTexture.prototype.getScene = function () {
  12194. return this._scene;
  12195. };
  12196. BaseTexture.prototype.getTextureMatrix = function () {
  12197. return null;
  12198. };
  12199. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  12200. return null;
  12201. };
  12202. BaseTexture.prototype.getInternalTexture = function () {
  12203. return this._texture;
  12204. };
  12205. BaseTexture.prototype.isReady = function () {
  12206. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  12207. return true;
  12208. }
  12209. if (this._texture) {
  12210. return this._texture.isReady;
  12211. }
  12212. return false;
  12213. };
  12214. BaseTexture.prototype.getSize = function () {
  12215. if (this._texture._width) {
  12216. return { width: this._texture._width, height: this._texture._height };
  12217. }
  12218. if (this._texture._size) {
  12219. return { width: this._texture._size, height: this._texture._size };
  12220. }
  12221. return { width: 0, height: 0 };
  12222. };
  12223. BaseTexture.prototype.getBaseSize = function () {
  12224. if (!this.isReady())
  12225. return { width: 0, height: 0 };
  12226. if (this._texture._size) {
  12227. return { width: this._texture._size, height: this._texture._size };
  12228. }
  12229. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  12230. };
  12231. BaseTexture.prototype.scale = function (ratio) {
  12232. };
  12233. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  12234. get: function () {
  12235. return false;
  12236. },
  12237. enumerable: true,
  12238. configurable: true
  12239. });
  12240. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  12241. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  12242. for (var index = 0; index < texturesCache.length; index++) {
  12243. var texturesCacheEntry = texturesCache[index];
  12244. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  12245. texturesCache.splice(index, 1);
  12246. return;
  12247. }
  12248. }
  12249. };
  12250. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  12251. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  12252. for (var index = 0; index < texturesCache.length; index++) {
  12253. var texturesCacheEntry = texturesCache[index];
  12254. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  12255. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  12256. texturesCacheEntry.references++;
  12257. return texturesCacheEntry;
  12258. }
  12259. }
  12260. }
  12261. return null;
  12262. };
  12263. BaseTexture.prototype.delayLoad = function () {
  12264. };
  12265. BaseTexture.prototype.releaseInternalTexture = function () {
  12266. if (!this._texture) {
  12267. return;
  12268. }
  12269. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  12270. this._texture.references--;
  12271. // Final reference ?
  12272. if (this._texture.references === 0) {
  12273. var index = texturesCache.indexOf(this._texture);
  12274. texturesCache.splice(index, 1);
  12275. this._scene.getEngine()._releaseTexture(this._texture);
  12276. delete this._texture;
  12277. }
  12278. };
  12279. BaseTexture.prototype.clone = function () {
  12280. return null;
  12281. };
  12282. BaseTexture.prototype.dispose = function () {
  12283. // Remove from scene
  12284. var index = this._scene.textures.indexOf(this);
  12285. if (index >= 0) {
  12286. this._scene.textures.splice(index, 1);
  12287. }
  12288. if (this._texture === undefined) {
  12289. return;
  12290. }
  12291. this.releaseInternalTexture();
  12292. // Callback
  12293. if (this.onDispose) {
  12294. this.onDispose();
  12295. }
  12296. };
  12297. return BaseTexture;
  12298. })();
  12299. BABYLON.BaseTexture = BaseTexture;
  12300. })(BABYLON || (BABYLON = {}));
  12301. //# sourceMappingURL=babylon.baseTexture.js.mapvar BABYLON;
  12302. (function (BABYLON) {
  12303. var RenderingGroup = (function () {
  12304. function RenderingGroup(index, scene) {
  12305. this.index = index;
  12306. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  12307. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  12308. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  12309. this._scene = scene;
  12310. }
  12311. RenderingGroup.prototype.render = function (customRenderFunction) {
  12312. if (customRenderFunction) {
  12313. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  12314. return true;
  12315. }
  12316. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  12317. return false;
  12318. }
  12319. var engine = this._scene.getEngine();
  12320. // Opaque
  12321. var subIndex;
  12322. var submesh;
  12323. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  12324. submesh = this._opaqueSubMeshes.data[subIndex];
  12325. submesh.render();
  12326. }
  12327. // Alpha test
  12328. engine.setAlphaTesting(true);
  12329. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  12330. submesh = this._alphaTestSubMeshes.data[subIndex];
  12331. submesh.render();
  12332. }
  12333. engine.setAlphaTesting(false);
  12334. // Transparent
  12335. if (this._transparentSubMeshes.length) {
  12336. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  12337. submesh = this._transparentSubMeshes.data[subIndex];
  12338. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  12339. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.position).length();
  12340. }
  12341. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  12342. sortedArray.sort(function (a, b) {
  12343. // Alpha index first
  12344. if (a._alphaIndex > b._alphaIndex) {
  12345. return 1;
  12346. }
  12347. if (a._alphaIndex < b._alphaIndex) {
  12348. return -1;
  12349. }
  12350. // Then distance to camera
  12351. if (a._distanceToCamera < b._distanceToCamera) {
  12352. return 1;
  12353. }
  12354. if (a._distanceToCamera > b._distanceToCamera) {
  12355. return -1;
  12356. }
  12357. return 0;
  12358. });
  12359. // Rendering
  12360. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  12361. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  12362. submesh = sortedArray[subIndex];
  12363. submesh.render();
  12364. }
  12365. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  12366. }
  12367. return true;
  12368. };
  12369. RenderingGroup.prototype.prepare = function () {
  12370. this._opaqueSubMeshes.reset();
  12371. this._transparentSubMeshes.reset();
  12372. this._alphaTestSubMeshes.reset();
  12373. };
  12374. RenderingGroup.prototype.dispatch = function (subMesh) {
  12375. var material = subMesh.getMaterial();
  12376. var mesh = subMesh.getMesh();
  12377. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  12378. this._transparentSubMeshes.push(subMesh);
  12379. }
  12380. else if (material.needAlphaTesting()) {
  12381. this._alphaTestSubMeshes.push(subMesh);
  12382. }
  12383. else {
  12384. this._opaqueSubMeshes.push(subMesh); // Opaque
  12385. }
  12386. };
  12387. return RenderingGroup;
  12388. })();
  12389. BABYLON.RenderingGroup = RenderingGroup;
  12390. })(BABYLON || (BABYLON = {}));
  12391. //# sourceMappingURL=babylon.renderingGroup.js.mapvar BABYLON;
  12392. (function (BABYLON) {
  12393. var RenderingManager = (function () {
  12394. function RenderingManager(scene) {
  12395. this._renderingGroups = new Array();
  12396. this._scene = scene;
  12397. }
  12398. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  12399. if (this._scene._activeParticleSystems.length === 0) {
  12400. return;
  12401. }
  12402. // Particles
  12403. var beforeParticlesDate = BABYLON.Tools.Now;
  12404. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  12405. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  12406. if (particleSystem.renderingGroupId !== index) {
  12407. continue;
  12408. }
  12409. this._clearDepthBuffer();
  12410. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  12411. this._scene._activeParticles += particleSystem.render();
  12412. }
  12413. }
  12414. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  12415. };
  12416. RenderingManager.prototype._renderSprites = function (index) {
  12417. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  12418. return;
  12419. }
  12420. // Sprites
  12421. var beforeSpritessDate = BABYLON.Tools.Now;
  12422. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  12423. var spriteManager = this._scene.spriteManagers[id];
  12424. if (spriteManager.renderingGroupId === index) {
  12425. this._clearDepthBuffer();
  12426. spriteManager.render();
  12427. }
  12428. }
  12429. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  12430. };
  12431. RenderingManager.prototype._clearDepthBuffer = function () {
  12432. if (this._depthBufferAlreadyCleaned) {
  12433. return;
  12434. }
  12435. this._scene.getEngine().clear(0, false, true);
  12436. this._depthBufferAlreadyCleaned = true;
  12437. };
  12438. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  12439. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  12440. this._depthBufferAlreadyCleaned = false;
  12441. var renderingGroup = this._renderingGroups[index];
  12442. var needToStepBack = false;
  12443. if (renderingGroup) {
  12444. this._clearDepthBuffer();
  12445. if (!renderingGroup.render(customRenderFunction)) {
  12446. this._renderingGroups.splice(index, 1);
  12447. needToStepBack = true;
  12448. }
  12449. }
  12450. if (renderSprites) {
  12451. this._renderSprites(index);
  12452. }
  12453. if (renderParticles) {
  12454. this._renderParticles(index, activeMeshes);
  12455. }
  12456. if (needToStepBack) {
  12457. index--;
  12458. }
  12459. }
  12460. };
  12461. RenderingManager.prototype.reset = function () {
  12462. for (var index in this._renderingGroups) {
  12463. var renderingGroup = this._renderingGroups[index];
  12464. renderingGroup.prepare();
  12465. }
  12466. };
  12467. RenderingManager.prototype.dispatch = function (subMesh) {
  12468. var mesh = subMesh.getMesh();
  12469. var renderingGroupId = mesh.renderingGroupId || 0;
  12470. if (!this._renderingGroups[renderingGroupId]) {
  12471. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  12472. }
  12473. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  12474. };
  12475. RenderingManager.MAX_RENDERINGGROUPS = 4;
  12476. return RenderingManager;
  12477. })();
  12478. BABYLON.RenderingManager = RenderingManager;
  12479. })(BABYLON || (BABYLON = {}));
  12480. //# sourceMappingURL=babylon.renderingManager.js.map
  12481. var BABYLON;
  12482. (function (BABYLON) {
  12483. var Texture = (function (_super) {
  12484. __extends(Texture, _super);
  12485. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  12486. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  12487. if (onLoad === void 0) { onLoad = null; }
  12488. if (onError === void 0) { onError = null; }
  12489. if (buffer === void 0) { buffer = null; }
  12490. if (deleteBuffer === void 0) { deleteBuffer = false; }
  12491. _super.call(this, scene);
  12492. this.uOffset = 0;
  12493. this.vOffset = 0;
  12494. this.uScale = 1.0;
  12495. this.vScale = 1.0;
  12496. this.uAng = 0;
  12497. this.vAng = 0;
  12498. this.wAng = 0;
  12499. this.name = url;
  12500. this.url = url;
  12501. this._noMipmap = noMipmap;
  12502. this._invertY = invertY;
  12503. this._samplingMode = samplingMode;
  12504. this._buffer = buffer;
  12505. this._deleteBuffer = deleteBuffer;
  12506. if (!url) {
  12507. return;
  12508. }
  12509. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  12510. if (!this._texture) {
  12511. if (!scene.useDelayedTextureLoading) {
  12512. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  12513. if (deleteBuffer) {
  12514. delete this._buffer;
  12515. }
  12516. }
  12517. else {
  12518. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  12519. }
  12520. }
  12521. }
  12522. Texture.prototype.delayLoad = function () {
  12523. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  12524. return;
  12525. }
  12526. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  12527. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  12528. if (!this._texture) {
  12529. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  12530. if (this._deleteBuffer) {
  12531. delete this._buffer;
  12532. }
  12533. }
  12534. };
  12535. Texture.prototype.updateSamplingMode = function (samplingMode) {
  12536. if (!this._texture) {
  12537. return;
  12538. }
  12539. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  12540. };
  12541. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  12542. x -= this.uOffset + 0.5;
  12543. y -= this.vOffset + 0.5;
  12544. z -= 0.5;
  12545. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  12546. t.x *= this.uScale;
  12547. t.y *= this.vScale;
  12548. t.x += 0.5;
  12549. t.y += 0.5;
  12550. t.z += 0.5;
  12551. };
  12552. Texture.prototype.getTextureMatrix = function () {
  12553. 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) {
  12554. return this._cachedTextureMatrix;
  12555. }
  12556. this._cachedUOffset = this.uOffset;
  12557. this._cachedVOffset = this.vOffset;
  12558. this._cachedUScale = this.uScale;
  12559. this._cachedVScale = this.vScale;
  12560. this._cachedUAng = this.uAng;
  12561. this._cachedVAng = this.vAng;
  12562. this._cachedWAng = this.wAng;
  12563. if (!this._cachedTextureMatrix) {
  12564. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  12565. this._rowGenerationMatrix = new BABYLON.Matrix();
  12566. this._t0 = BABYLON.Vector3.Zero();
  12567. this._t1 = BABYLON.Vector3.Zero();
  12568. this._t2 = BABYLON.Vector3.Zero();
  12569. }
  12570. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  12571. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  12572. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  12573. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  12574. this._t1.subtractInPlace(this._t0);
  12575. this._t2.subtractInPlace(this._t0);
  12576. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  12577. this._cachedTextureMatrix.m[0] = this._t1.x;
  12578. this._cachedTextureMatrix.m[1] = this._t1.y;
  12579. this._cachedTextureMatrix.m[2] = this._t1.z;
  12580. this._cachedTextureMatrix.m[4] = this._t2.x;
  12581. this._cachedTextureMatrix.m[5] = this._t2.y;
  12582. this._cachedTextureMatrix.m[6] = this._t2.z;
  12583. this._cachedTextureMatrix.m[8] = this._t0.x;
  12584. this._cachedTextureMatrix.m[9] = this._t0.y;
  12585. this._cachedTextureMatrix.m[10] = this._t0.z;
  12586. return this._cachedTextureMatrix;
  12587. };
  12588. Texture.prototype.getReflectionTextureMatrix = function () {
  12589. if (this.uOffset === this._cachedUOffset && this.vOffset === this._cachedVOffset && this.uScale === this._cachedUScale && this.vScale === this._cachedVScale && this.coordinatesMode === this._cachedCoordinatesMode) {
  12590. return this._cachedTextureMatrix;
  12591. }
  12592. if (!this._cachedTextureMatrix) {
  12593. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  12594. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  12595. }
  12596. this._cachedCoordinatesMode = this.coordinatesMode;
  12597. switch (this.coordinatesMode) {
  12598. case Texture.SPHERICAL_MODE:
  12599. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  12600. this._cachedTextureMatrix[0] = -0.5 * this.uScale;
  12601. this._cachedTextureMatrix[5] = -0.5 * this.vScale;
  12602. this._cachedTextureMatrix[12] = 0.5 + this.uOffset;
  12603. this._cachedTextureMatrix[13] = 0.5 + this.vOffset;
  12604. break;
  12605. case Texture.PLANAR_MODE:
  12606. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  12607. this._cachedTextureMatrix[0] = this.uScale;
  12608. this._cachedTextureMatrix[5] = this.vScale;
  12609. this._cachedTextureMatrix[12] = this.uOffset;
  12610. this._cachedTextureMatrix[13] = this.vOffset;
  12611. break;
  12612. case Texture.PROJECTION_MODE:
  12613. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  12614. this._projectionModeMatrix.m[0] = 0.5;
  12615. this._projectionModeMatrix.m[5] = -0.5;
  12616. this._projectionModeMatrix.m[10] = 0.0;
  12617. this._projectionModeMatrix.m[12] = 0.5;
  12618. this._projectionModeMatrix.m[13] = 0.5;
  12619. this._projectionModeMatrix.m[14] = 1.0;
  12620. this._projectionModeMatrix.m[15] = 1.0;
  12621. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  12622. break;
  12623. default:
  12624. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  12625. break;
  12626. }
  12627. return this._cachedTextureMatrix;
  12628. };
  12629. Texture.prototype.clone = function () {
  12630. var newTexture = new Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY, this._samplingMode);
  12631. // Base texture
  12632. newTexture.hasAlpha = this.hasAlpha;
  12633. newTexture.level = this.level;
  12634. newTexture.wrapU = this.wrapU;
  12635. newTexture.wrapV = this.wrapV;
  12636. newTexture.coordinatesIndex = this.coordinatesIndex;
  12637. newTexture.coordinatesMode = this.coordinatesMode;
  12638. // Texture
  12639. newTexture.uOffset = this.uOffset;
  12640. newTexture.vOffset = this.vOffset;
  12641. newTexture.uScale = this.uScale;
  12642. newTexture.vScale = this.vScale;
  12643. newTexture.uAng = this.uAng;
  12644. newTexture.vAng = this.vAng;
  12645. newTexture.wAng = this.wAng;
  12646. return newTexture;
  12647. };
  12648. // Statics
  12649. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  12650. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  12651. if (onLoad === void 0) { onLoad = null; }
  12652. if (onError === void 0) { onError = null; }
  12653. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  12654. };
  12655. // Constants
  12656. Texture.NEAREST_SAMPLINGMODE = 1;
  12657. Texture.BILINEAR_SAMPLINGMODE = 2;
  12658. Texture.TRILINEAR_SAMPLINGMODE = 3;
  12659. Texture.EXPLICIT_MODE = 0;
  12660. Texture.SPHERICAL_MODE = 1;
  12661. Texture.PLANAR_MODE = 2;
  12662. Texture.CUBIC_MODE = 3;
  12663. Texture.PROJECTION_MODE = 4;
  12664. Texture.SKYBOX_MODE = 5;
  12665. Texture.CLAMP_ADDRESSMODE = 0;
  12666. Texture.WRAP_ADDRESSMODE = 1;
  12667. Texture.MIRROR_ADDRESSMODE = 2;
  12668. return Texture;
  12669. })(BABYLON.BaseTexture);
  12670. BABYLON.Texture = Texture;
  12671. })(BABYLON || (BABYLON = {}));
  12672. //# sourceMappingURL=babylon.texture.js.map
  12673. var BABYLON;
  12674. (function (BABYLON) {
  12675. var CubeTexture = (function (_super) {
  12676. __extends(CubeTexture, _super);
  12677. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  12678. _super.call(this, scene);
  12679. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  12680. this.name = rootUrl;
  12681. this.url = rootUrl;
  12682. this._noMipmap = noMipmap;
  12683. this.hasAlpha = false;
  12684. this._texture = this._getFromCache(rootUrl, noMipmap);
  12685. if (!extensions) {
  12686. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  12687. }
  12688. this._extensions = extensions;
  12689. if (!this._texture) {
  12690. if (!scene.useDelayedTextureLoading) {
  12691. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  12692. }
  12693. else {
  12694. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  12695. }
  12696. }
  12697. this.isCube = true;
  12698. this._textureMatrix = BABYLON.Matrix.Identity();
  12699. }
  12700. CubeTexture.prototype.clone = function () {
  12701. var newTexture = new CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  12702. // Base texture
  12703. newTexture.level = this.level;
  12704. newTexture.wrapU = this.wrapU;
  12705. newTexture.wrapV = this.wrapV;
  12706. newTexture.coordinatesIndex = this.coordinatesIndex;
  12707. newTexture.coordinatesMode = this.coordinatesMode;
  12708. return newTexture;
  12709. };
  12710. // Methods
  12711. CubeTexture.prototype.delayLoad = function () {
  12712. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  12713. return;
  12714. }
  12715. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  12716. this._texture = this._getFromCache(this.url, this._noMipmap);
  12717. if (!this._texture) {
  12718. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  12719. }
  12720. };
  12721. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  12722. return this._textureMatrix;
  12723. };
  12724. return CubeTexture;
  12725. })(BABYLON.BaseTexture);
  12726. BABYLON.CubeTexture = CubeTexture;
  12727. })(BABYLON || (BABYLON = {}));
  12728. //# sourceMappingURL=babylon.cubeTexture.js.map
  12729. var BABYLON;
  12730. (function (BABYLON) {
  12731. var RenderTargetTexture = (function (_super) {
  12732. __extends(RenderTargetTexture, _super);
  12733. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type) {
  12734. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  12735. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  12736. _super.call(this, null, scene, !generateMipMaps);
  12737. this.renderList = new Array();
  12738. this.renderParticles = true;
  12739. this.renderSprites = false;
  12740. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  12741. this._currentRefreshId = -1;
  12742. this._refreshRate = 1;
  12743. this.name = name;
  12744. this.isRenderTarget = true;
  12745. this._size = size;
  12746. this._generateMipMaps = generateMipMaps;
  12747. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  12748. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  12749. // Rendering groups
  12750. this._renderingManager = new BABYLON.RenderingManager(scene);
  12751. }
  12752. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  12753. this._currentRefreshId = -1;
  12754. };
  12755. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  12756. get: function () {
  12757. return this._refreshRate;
  12758. },
  12759. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  12760. set: function (value) {
  12761. this._refreshRate = value;
  12762. this.resetRefreshCounter();
  12763. },
  12764. enumerable: true,
  12765. configurable: true
  12766. });
  12767. RenderTargetTexture.prototype._shouldRender = function () {
  12768. if (this._currentRefreshId === -1) {
  12769. this._currentRefreshId = 1;
  12770. return true;
  12771. }
  12772. if (this.refreshRate === this._currentRefreshId) {
  12773. this._currentRefreshId = 1;
  12774. return true;
  12775. }
  12776. this._currentRefreshId++;
  12777. return false;
  12778. };
  12779. RenderTargetTexture.prototype.isReady = function () {
  12780. if (!this.getScene().renderTargetsEnabled) {
  12781. return false;
  12782. }
  12783. return _super.prototype.isReady.call(this);
  12784. };
  12785. RenderTargetTexture.prototype.getRenderSize = function () {
  12786. return this._size;
  12787. };
  12788. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  12789. get: function () {
  12790. return true;
  12791. },
  12792. enumerable: true,
  12793. configurable: true
  12794. });
  12795. RenderTargetTexture.prototype.scale = function (ratio) {
  12796. var newSize = this._size * ratio;
  12797. this.resize(newSize, this._generateMipMaps);
  12798. };
  12799. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  12800. this.releaseInternalTexture();
  12801. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  12802. };
  12803. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  12804. var scene = this.getScene();
  12805. var engine = scene.getEngine();
  12806. if (this._waitingRenderList) {
  12807. this.renderList = [];
  12808. for (var index = 0; index < this._waitingRenderList.length; index++) {
  12809. var id = this._waitingRenderList[index];
  12810. this.renderList.push(scene.getMeshByID(id));
  12811. }
  12812. delete this._waitingRenderList;
  12813. }
  12814. if (this.renderList && this.renderList.length === 0) {
  12815. return;
  12816. }
  12817. // Bind
  12818. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  12819. engine.bindFramebuffer(this._texture);
  12820. }
  12821. this._renderingManager.reset();
  12822. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  12823. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  12824. var mesh = currentRenderList[meshIndex];
  12825. if (mesh) {
  12826. if (!mesh.isReady()) {
  12827. // Reset _currentRefreshId
  12828. this.resetRefreshCounter();
  12829. continue;
  12830. }
  12831. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  12832. mesh._activate(scene.getRenderId());
  12833. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  12834. var subMesh = mesh.subMeshes[subIndex];
  12835. scene._activeVertices += subMesh.indexCount;
  12836. this._renderingManager.dispatch(subMesh);
  12837. }
  12838. }
  12839. }
  12840. }
  12841. if (this.onBeforeRender) {
  12842. this.onBeforeRender();
  12843. }
  12844. // Clear
  12845. if (this.onClear) {
  12846. this.onClear(engine);
  12847. }
  12848. else {
  12849. engine.clear(scene.clearColor, true, true);
  12850. }
  12851. if (!this._doNotChangeAspectRatio) {
  12852. scene.updateTransformMatrix(true);
  12853. }
  12854. // Render
  12855. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  12856. if (useCameraPostProcess) {
  12857. scene.postProcessManager._finalizeFrame(false, this._texture);
  12858. }
  12859. if (!this._doNotChangeAspectRatio) {
  12860. scene.updateTransformMatrix(true);
  12861. }
  12862. if (this.onAfterRender) {
  12863. this.onAfterRender();
  12864. }
  12865. // Dump ?
  12866. if (dumpForDebug) {
  12867. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  12868. }
  12869. // Unbind
  12870. engine.unBindFramebuffer(this._texture);
  12871. if (this.onAfterUnbind) {
  12872. this.onAfterUnbind();
  12873. }
  12874. };
  12875. RenderTargetTexture.prototype.clone = function () {
  12876. var textureSize = this.getSize();
  12877. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  12878. // Base texture
  12879. newTexture.hasAlpha = this.hasAlpha;
  12880. newTexture.level = this.level;
  12881. // RenderTarget Texture
  12882. newTexture.coordinatesMode = this.coordinatesMode;
  12883. newTexture.renderList = this.renderList.slice(0);
  12884. return newTexture;
  12885. };
  12886. return RenderTargetTexture;
  12887. })(BABYLON.Texture);
  12888. BABYLON.RenderTargetTexture = RenderTargetTexture;
  12889. })(BABYLON || (BABYLON = {}));
  12890. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  12891. var BABYLON;
  12892. (function (BABYLON) {
  12893. var ProceduralTexture = (function (_super) {
  12894. __extends(ProceduralTexture, _super);
  12895. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps) {
  12896. if (generateMipMaps === void 0) { generateMipMaps = true; }
  12897. _super.call(this, null, scene, !generateMipMaps);
  12898. this._currentRefreshId = -1;
  12899. this._refreshRate = 1;
  12900. this._vertexDeclaration = [2];
  12901. this._vertexStrideSize = 2 * 4;
  12902. this._uniforms = new Array();
  12903. this._samplers = new Array();
  12904. this._textures = new Array();
  12905. this._floats = new Array();
  12906. this._floatsArrays = {};
  12907. this._colors3 = new Array();
  12908. this._colors4 = new Array();
  12909. this._vectors2 = new Array();
  12910. this._vectors3 = new Array();
  12911. this._matrices = new Array();
  12912. this._fallbackTextureUsed = false;
  12913. scene._proceduralTextures.push(this);
  12914. this.name = name;
  12915. this.isRenderTarget = true;
  12916. this._size = size;
  12917. this._generateMipMaps = generateMipMaps;
  12918. this.setFragment(fragment);
  12919. this._fallbackTexture = fallbackTexture;
  12920. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  12921. // VBO
  12922. var vertices = [];
  12923. vertices.push(1, 1);
  12924. vertices.push(-1, 1);
  12925. vertices.push(-1, -1);
  12926. vertices.push(1, -1);
  12927. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  12928. // Indices
  12929. var indices = [];
  12930. indices.push(0);
  12931. indices.push(1);
  12932. indices.push(2);
  12933. indices.push(0);
  12934. indices.push(2);
  12935. indices.push(3);
  12936. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  12937. }
  12938. ProceduralTexture.prototype.reset = function () {
  12939. if (this._effect === undefined) {
  12940. return;
  12941. }
  12942. var engine = this.getScene().getEngine();
  12943. engine._releaseEffect(this._effect);
  12944. };
  12945. ProceduralTexture.prototype.isReady = function () {
  12946. var _this = this;
  12947. var engine = this.getScene().getEngine();
  12948. var shaders;
  12949. if (!this._fragment) {
  12950. return false;
  12951. }
  12952. if (this._fallbackTextureUsed) {
  12953. return true;
  12954. }
  12955. if (this._fragment.fragmentElement !== undefined) {
  12956. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  12957. }
  12958. else {
  12959. shaders = { vertex: "procedural", fragment: this._fragment };
  12960. }
  12961. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  12962. _this.releaseInternalTexture();
  12963. if (_this._fallbackTexture) {
  12964. _this._texture = _this._fallbackTexture._texture;
  12965. _this._texture.references++;
  12966. }
  12967. _this._fallbackTextureUsed = true;
  12968. });
  12969. return this._effect.isReady();
  12970. };
  12971. ProceduralTexture.prototype.resetRefreshCounter = function () {
  12972. this._currentRefreshId = -1;
  12973. };
  12974. ProceduralTexture.prototype.setFragment = function (fragment) {
  12975. this._fragment = fragment;
  12976. };
  12977. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  12978. get: function () {
  12979. return this._refreshRate;
  12980. },
  12981. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  12982. set: function (value) {
  12983. this._refreshRate = value;
  12984. this.resetRefreshCounter();
  12985. },
  12986. enumerable: true,
  12987. configurable: true
  12988. });
  12989. ProceduralTexture.prototype._shouldRender = function () {
  12990. if (!this.isReady() || !this._texture) {
  12991. return false;
  12992. }
  12993. if (this._fallbackTextureUsed) {
  12994. return false;
  12995. }
  12996. if (this._currentRefreshId === -1) {
  12997. this._currentRefreshId = 1;
  12998. return true;
  12999. }
  13000. if (this.refreshRate === this._currentRefreshId) {
  13001. this._currentRefreshId = 1;
  13002. return true;
  13003. }
  13004. this._currentRefreshId++;
  13005. return false;
  13006. };
  13007. ProceduralTexture.prototype.getRenderSize = function () {
  13008. return this._size;
  13009. };
  13010. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  13011. if (this._fallbackTextureUsed) {
  13012. return;
  13013. }
  13014. this.releaseInternalTexture();
  13015. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  13016. };
  13017. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  13018. if (this._uniforms.indexOf(uniformName) === -1) {
  13019. this._uniforms.push(uniformName);
  13020. }
  13021. };
  13022. ProceduralTexture.prototype.setTexture = function (name, texture) {
  13023. if (this._samplers.indexOf(name) === -1) {
  13024. this._samplers.push(name);
  13025. }
  13026. this._textures[name] = texture;
  13027. return this;
  13028. };
  13029. ProceduralTexture.prototype.setFloat = function (name, value) {
  13030. this._checkUniform(name);
  13031. this._floats[name] = value;
  13032. return this;
  13033. };
  13034. ProceduralTexture.prototype.setFloats = function (name, value) {
  13035. this._checkUniform(name);
  13036. this._floatsArrays[name] = value;
  13037. return this;
  13038. };
  13039. ProceduralTexture.prototype.setColor3 = function (name, value) {
  13040. this._checkUniform(name);
  13041. this._colors3[name] = value;
  13042. return this;
  13043. };
  13044. ProceduralTexture.prototype.setColor4 = function (name, value) {
  13045. this._checkUniform(name);
  13046. this._colors4[name] = value;
  13047. return this;
  13048. };
  13049. ProceduralTexture.prototype.setVector2 = function (name, value) {
  13050. this._checkUniform(name);
  13051. this._vectors2[name] = value;
  13052. return this;
  13053. };
  13054. ProceduralTexture.prototype.setVector3 = function (name, value) {
  13055. this._checkUniform(name);
  13056. this._vectors3[name] = value;
  13057. return this;
  13058. };
  13059. ProceduralTexture.prototype.setMatrix = function (name, value) {
  13060. this._checkUniform(name);
  13061. this._matrices[name] = value;
  13062. return this;
  13063. };
  13064. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  13065. var scene = this.getScene();
  13066. var engine = scene.getEngine();
  13067. engine.bindFramebuffer(this._texture);
  13068. // Clear
  13069. engine.clear(scene.clearColor, true, true);
  13070. // Render
  13071. engine.enableEffect(this._effect);
  13072. engine.setState(false);
  13073. for (var name in this._textures) {
  13074. this._effect.setTexture(name, this._textures[name]);
  13075. }
  13076. for (name in this._floats) {
  13077. this._effect.setFloat(name, this._floats[name]);
  13078. }
  13079. for (name in this._floatsArrays) {
  13080. this._effect.setArray(name, this._floatsArrays[name]);
  13081. }
  13082. for (name in this._colors3) {
  13083. this._effect.setColor3(name, this._colors3[name]);
  13084. }
  13085. for (name in this._colors4) {
  13086. var color = this._colors4[name];
  13087. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  13088. }
  13089. for (name in this._vectors2) {
  13090. this._effect.setVector2(name, this._vectors2[name]);
  13091. }
  13092. for (name in this._vectors3) {
  13093. this._effect.setVector3(name, this._vectors3[name]);
  13094. }
  13095. for (name in this._matrices) {
  13096. this._effect.setMatrix(name, this._matrices[name]);
  13097. }
  13098. // VBOs
  13099. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  13100. // Draw order
  13101. engine.draw(true, 0, 6);
  13102. // Unbind
  13103. engine.unBindFramebuffer(this._texture);
  13104. };
  13105. ProceduralTexture.prototype.clone = function () {
  13106. var textureSize = this.getSize();
  13107. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  13108. // Base texture
  13109. newTexture.hasAlpha = this.hasAlpha;
  13110. newTexture.level = this.level;
  13111. // RenderTarget Texture
  13112. newTexture.coordinatesMode = this.coordinatesMode;
  13113. return newTexture;
  13114. };
  13115. ProceduralTexture.prototype.dispose = function () {
  13116. var index = this.getScene()._proceduralTextures.indexOf(this);
  13117. if (index >= 0) {
  13118. this.getScene()._proceduralTextures.splice(index, 1);
  13119. }
  13120. _super.prototype.dispose.call(this);
  13121. };
  13122. return ProceduralTexture;
  13123. })(BABYLON.Texture);
  13124. BABYLON.ProceduralTexture = ProceduralTexture;
  13125. })(BABYLON || (BABYLON = {}));
  13126. //# sourceMappingURL=babylon.proceduralTexture.js.map
  13127. var BABYLON;
  13128. (function (BABYLON) {
  13129. var WoodProceduralTexture = (function (_super) {
  13130. __extends(WoodProceduralTexture, _super);
  13131. function WoodProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13132. _super.call(this, name, size, "wood", scene, fallbackTexture, generateMipMaps);
  13133. this._ampScale = 100.0;
  13134. this._woodColor = new BABYLON.Color3(0.32, 0.17, 0.09);
  13135. this.updateShaderUniforms();
  13136. this.refreshRate = 0;
  13137. }
  13138. WoodProceduralTexture.prototype.updateShaderUniforms = function () {
  13139. this.setFloat("ampScale", this._ampScale);
  13140. this.setColor3("woodColor", this._woodColor);
  13141. };
  13142. Object.defineProperty(WoodProceduralTexture.prototype, "ampScale", {
  13143. get: function () {
  13144. return this._ampScale;
  13145. },
  13146. set: function (value) {
  13147. this._ampScale = value;
  13148. this.updateShaderUniforms();
  13149. },
  13150. enumerable: true,
  13151. configurable: true
  13152. });
  13153. Object.defineProperty(WoodProceduralTexture.prototype, "woodColor", {
  13154. get: function () {
  13155. return this._woodColor;
  13156. },
  13157. set: function (value) {
  13158. this._woodColor = value;
  13159. this.updateShaderUniforms();
  13160. },
  13161. enumerable: true,
  13162. configurable: true
  13163. });
  13164. return WoodProceduralTexture;
  13165. })(BABYLON.ProceduralTexture);
  13166. BABYLON.WoodProceduralTexture = WoodProceduralTexture;
  13167. var FireProceduralTexture = (function (_super) {
  13168. __extends(FireProceduralTexture, _super);
  13169. function FireProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13170. _super.call(this, name, size, "fire", scene, fallbackTexture, generateMipMaps);
  13171. this._time = 0.0;
  13172. this._speed = new BABYLON.Vector2(0.5, 0.3);
  13173. this._shift = 1.6;
  13174. this._autoGenerateTime = true;
  13175. this._alphaThreshold = 0.5;
  13176. this._fireColors = FireProceduralTexture.RedFireColors;
  13177. this.updateShaderUniforms();
  13178. this.refreshRate = 1;
  13179. }
  13180. FireProceduralTexture.prototype.updateShaderUniforms = function () {
  13181. this.setFloat("time", this._time);
  13182. this.setVector2("speed", this._speed);
  13183. this.setFloat("shift", this._shift);
  13184. this.setColor3("c1", this._fireColors[0]);
  13185. this.setColor3("c2", this._fireColors[1]);
  13186. this.setColor3("c3", this._fireColors[2]);
  13187. this.setColor3("c4", this._fireColors[3]);
  13188. this.setColor3("c5", this._fireColors[4]);
  13189. this.setColor3("c6", this._fireColors[5]);
  13190. this.setFloat("alphaThreshold", this._alphaThreshold);
  13191. };
  13192. FireProceduralTexture.prototype.render = function (useCameraPostProcess) {
  13193. if (this._autoGenerateTime) {
  13194. this._time += this.getScene().getAnimationRatio() * 0.03;
  13195. this.updateShaderUniforms();
  13196. }
  13197. _super.prototype.render.call(this, useCameraPostProcess);
  13198. };
  13199. Object.defineProperty(FireProceduralTexture, "PurpleFireColors", {
  13200. get: function () {
  13201. return [
  13202. new BABYLON.Color3(0.5, 0.0, 1.0),
  13203. new BABYLON.Color3(0.9, 0.0, 1.0),
  13204. new BABYLON.Color3(0.2, 0.0, 1.0),
  13205. new BABYLON.Color3(1.0, 0.9, 1.0),
  13206. new BABYLON.Color3(0.1, 0.1, 1.0),
  13207. new BABYLON.Color3(0.9, 0.9, 1.0)
  13208. ];
  13209. },
  13210. enumerable: true,
  13211. configurable: true
  13212. });
  13213. Object.defineProperty(FireProceduralTexture, "GreenFireColors", {
  13214. get: function () {
  13215. return [
  13216. new BABYLON.Color3(0.5, 1.0, 0.0),
  13217. new BABYLON.Color3(0.5, 1.0, 0.0),
  13218. new BABYLON.Color3(0.3, 0.4, 0.0),
  13219. new BABYLON.Color3(0.5, 1.0, 0.0),
  13220. new BABYLON.Color3(0.2, 0.0, 0.0),
  13221. new BABYLON.Color3(0.5, 1.0, 0.0)
  13222. ];
  13223. },
  13224. enumerable: true,
  13225. configurable: true
  13226. });
  13227. Object.defineProperty(FireProceduralTexture, "RedFireColors", {
  13228. get: function () {
  13229. return [
  13230. new BABYLON.Color3(0.5, 0.0, 0.1),
  13231. new BABYLON.Color3(0.9, 0.0, 0.0),
  13232. new BABYLON.Color3(0.2, 0.0, 0.0),
  13233. new BABYLON.Color3(1.0, 0.9, 0.0),
  13234. new BABYLON.Color3(0.1, 0.1, 0.1),
  13235. new BABYLON.Color3(0.9, 0.9, 0.9)
  13236. ];
  13237. },
  13238. enumerable: true,
  13239. configurable: true
  13240. });
  13241. Object.defineProperty(FireProceduralTexture, "BlueFireColors", {
  13242. get: function () {
  13243. return [
  13244. new BABYLON.Color3(0.1, 0.0, 0.5),
  13245. new BABYLON.Color3(0.0, 0.0, 0.5),
  13246. new BABYLON.Color3(0.1, 0.0, 0.2),
  13247. new BABYLON.Color3(0.0, 0.0, 1.0),
  13248. new BABYLON.Color3(0.1, 0.2, 0.3),
  13249. new BABYLON.Color3(0.0, 0.2, 0.9)
  13250. ];
  13251. },
  13252. enumerable: true,
  13253. configurable: true
  13254. });
  13255. Object.defineProperty(FireProceduralTexture.prototype, "fireColors", {
  13256. get: function () {
  13257. return this._fireColors;
  13258. },
  13259. set: function (value) {
  13260. this._fireColors = value;
  13261. this.updateShaderUniforms();
  13262. },
  13263. enumerable: true,
  13264. configurable: true
  13265. });
  13266. Object.defineProperty(FireProceduralTexture.prototype, "time", {
  13267. get: function () {
  13268. return this._time;
  13269. },
  13270. set: function (value) {
  13271. this._time = value;
  13272. this.updateShaderUniforms();
  13273. },
  13274. enumerable: true,
  13275. configurable: true
  13276. });
  13277. Object.defineProperty(FireProceduralTexture.prototype, "speed", {
  13278. get: function () {
  13279. return this._speed;
  13280. },
  13281. set: function (value) {
  13282. this._speed = value;
  13283. this.updateShaderUniforms();
  13284. },
  13285. enumerable: true,
  13286. configurable: true
  13287. });
  13288. Object.defineProperty(FireProceduralTexture.prototype, "shift", {
  13289. get: function () {
  13290. return this._shift;
  13291. },
  13292. set: function (value) {
  13293. this._shift = value;
  13294. this.updateShaderUniforms();
  13295. },
  13296. enumerable: true,
  13297. configurable: true
  13298. });
  13299. Object.defineProperty(FireProceduralTexture.prototype, "alphaThreshold", {
  13300. get: function () {
  13301. return this._alphaThreshold;
  13302. },
  13303. set: function (value) {
  13304. this._alphaThreshold = value;
  13305. this.updateShaderUniforms();
  13306. },
  13307. enumerable: true,
  13308. configurable: true
  13309. });
  13310. return FireProceduralTexture;
  13311. })(BABYLON.ProceduralTexture);
  13312. BABYLON.FireProceduralTexture = FireProceduralTexture;
  13313. var CloudProceduralTexture = (function (_super) {
  13314. __extends(CloudProceduralTexture, _super);
  13315. function CloudProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13316. _super.call(this, name, size, "cloud", scene, fallbackTexture, generateMipMaps);
  13317. this._skyColor = new BABYLON.Color3(0.15, 0.68, 1.0);
  13318. this._cloudColor = new BABYLON.Color3(1, 1, 1);
  13319. this.updateShaderUniforms();
  13320. this.refreshRate = 0;
  13321. }
  13322. CloudProceduralTexture.prototype.updateShaderUniforms = function () {
  13323. this.setColor3("skyColor", this._skyColor);
  13324. this.setColor3("cloudColor", this._cloudColor);
  13325. };
  13326. Object.defineProperty(CloudProceduralTexture.prototype, "skyColor", {
  13327. get: function () {
  13328. return this._skyColor;
  13329. },
  13330. set: function (value) {
  13331. this._skyColor = value;
  13332. this.updateShaderUniforms();
  13333. },
  13334. enumerable: true,
  13335. configurable: true
  13336. });
  13337. Object.defineProperty(CloudProceduralTexture.prototype, "cloudColor", {
  13338. get: function () {
  13339. return this._cloudColor;
  13340. },
  13341. set: function (value) {
  13342. this._cloudColor = value;
  13343. this.updateShaderUniforms();
  13344. },
  13345. enumerable: true,
  13346. configurable: true
  13347. });
  13348. return CloudProceduralTexture;
  13349. })(BABYLON.ProceduralTexture);
  13350. BABYLON.CloudProceduralTexture = CloudProceduralTexture;
  13351. var GrassProceduralTexture = (function (_super) {
  13352. __extends(GrassProceduralTexture, _super);
  13353. function GrassProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13354. _super.call(this, name, size, "grass", scene, fallbackTexture, generateMipMaps);
  13355. this._herb1 = new BABYLON.Color3(0.29, 0.38, 0.02);
  13356. this._herb2 = new BABYLON.Color3(0.36, 0.49, 0.09);
  13357. this._herb3 = new BABYLON.Color3(0.51, 0.6, 0.28);
  13358. this._groundColor = new BABYLON.Color3(1, 1, 1);
  13359. this._grassColors = [
  13360. new BABYLON.Color3(0.29, 0.38, 0.02),
  13361. new BABYLON.Color3(0.36, 0.49, 0.09),
  13362. new BABYLON.Color3(0.51, 0.6, 0.28)
  13363. ];
  13364. this.updateShaderUniforms();
  13365. this.refreshRate = 0;
  13366. }
  13367. GrassProceduralTexture.prototype.updateShaderUniforms = function () {
  13368. this.setColor3("herb1Color", this._grassColors[0]);
  13369. this.setColor3("herb2Color", this._grassColors[1]);
  13370. this.setColor3("herb3Color", this._grassColors[2]);
  13371. this.setColor3("groundColor", this._groundColor);
  13372. };
  13373. Object.defineProperty(GrassProceduralTexture.prototype, "grassColors", {
  13374. get: function () {
  13375. return this._grassColors;
  13376. },
  13377. set: function (value) {
  13378. this._grassColors = value;
  13379. this.updateShaderUniforms();
  13380. },
  13381. enumerable: true,
  13382. configurable: true
  13383. });
  13384. Object.defineProperty(GrassProceduralTexture.prototype, "groundColor", {
  13385. get: function () {
  13386. return this._groundColor;
  13387. },
  13388. set: function (value) {
  13389. this.groundColor = value;
  13390. this.updateShaderUniforms();
  13391. },
  13392. enumerable: true,
  13393. configurable: true
  13394. });
  13395. return GrassProceduralTexture;
  13396. })(BABYLON.ProceduralTexture);
  13397. BABYLON.GrassProceduralTexture = GrassProceduralTexture;
  13398. var RoadProceduralTexture = (function (_super) {
  13399. __extends(RoadProceduralTexture, _super);
  13400. function RoadProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13401. _super.call(this, name, size, "road", scene, fallbackTexture, generateMipMaps);
  13402. this._roadColor = new BABYLON.Color3(0.53, 0.53, 0.53);
  13403. this.updateShaderUniforms();
  13404. this.refreshRate = 0;
  13405. }
  13406. RoadProceduralTexture.prototype.updateShaderUniforms = function () {
  13407. this.setColor3("roadColor", this._roadColor);
  13408. };
  13409. Object.defineProperty(RoadProceduralTexture.prototype, "roadColor", {
  13410. get: function () {
  13411. return this._roadColor;
  13412. },
  13413. set: function (value) {
  13414. this._roadColor = value;
  13415. this.updateShaderUniforms();
  13416. },
  13417. enumerable: true,
  13418. configurable: true
  13419. });
  13420. return RoadProceduralTexture;
  13421. })(BABYLON.ProceduralTexture);
  13422. BABYLON.RoadProceduralTexture = RoadProceduralTexture;
  13423. var BrickProceduralTexture = (function (_super) {
  13424. __extends(BrickProceduralTexture, _super);
  13425. function BrickProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13426. _super.call(this, name, size, "brick", scene, fallbackTexture, generateMipMaps);
  13427. this._numberOfBricksHeight = 15;
  13428. this._numberOfBricksWidth = 5;
  13429. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  13430. this._brickColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  13431. this.updateShaderUniforms();
  13432. this.refreshRate = 0;
  13433. }
  13434. BrickProceduralTexture.prototype.updateShaderUniforms = function () {
  13435. this.setFloat("numberOfBricksHeight", this._numberOfBricksHeight);
  13436. this.setFloat("numberOfBricksWidth", this._numberOfBricksWidth);
  13437. this.setColor3("brickColor", this._brickColor);
  13438. this.setColor3("jointColor", this._jointColor);
  13439. };
  13440. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksHeight", {
  13441. get: function () {
  13442. return this._numberOfBricksHeight;
  13443. },
  13444. set: function (value) {
  13445. this._numberOfBricksHeight = value;
  13446. this.updateShaderUniforms();
  13447. },
  13448. enumerable: true,
  13449. configurable: true
  13450. });
  13451. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksWidth", {
  13452. get: function () {
  13453. return this._numberOfBricksWidth;
  13454. },
  13455. set: function (value) {
  13456. this._numberOfBricksHeight = value;
  13457. this.updateShaderUniforms();
  13458. },
  13459. enumerable: true,
  13460. configurable: true
  13461. });
  13462. Object.defineProperty(BrickProceduralTexture.prototype, "jointColor", {
  13463. get: function () {
  13464. return this._jointColor;
  13465. },
  13466. set: function (value) {
  13467. this._jointColor = value;
  13468. this.updateShaderUniforms();
  13469. },
  13470. enumerable: true,
  13471. configurable: true
  13472. });
  13473. Object.defineProperty(BrickProceduralTexture.prototype, "brickColor", {
  13474. get: function () {
  13475. return this._brickColor;
  13476. },
  13477. set: function (value) {
  13478. this._brickColor = value;
  13479. this.updateShaderUniforms();
  13480. },
  13481. enumerable: true,
  13482. configurable: true
  13483. });
  13484. return BrickProceduralTexture;
  13485. })(BABYLON.ProceduralTexture);
  13486. BABYLON.BrickProceduralTexture = BrickProceduralTexture;
  13487. var MarbleProceduralTexture = (function (_super) {
  13488. __extends(MarbleProceduralTexture, _super);
  13489. function MarbleProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13490. _super.call(this, name, size, "marble", scene, fallbackTexture, generateMipMaps);
  13491. this._numberOfTilesHeight = 3;
  13492. this._numberOfTilesWidth = 3;
  13493. this._amplitude = 9.0;
  13494. this._marbleColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  13495. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  13496. this.updateShaderUniforms();
  13497. this.refreshRate = 0;
  13498. }
  13499. MarbleProceduralTexture.prototype.updateShaderUniforms = function () {
  13500. this.setFloat("numberOfTilesHeight", this._numberOfTilesHeight);
  13501. this.setFloat("numberOfTilesWidth", this._numberOfTilesWidth);
  13502. this.setFloat("amplitude", this._amplitude);
  13503. this.setColor3("marbleColor", this._marbleColor);
  13504. this.setColor3("jointColor", this._jointColor);
  13505. };
  13506. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesHeight", {
  13507. get: function () {
  13508. return this._numberOfTilesHeight;
  13509. },
  13510. set: function (value) {
  13511. this._numberOfTilesHeight = value;
  13512. this.updateShaderUniforms();
  13513. },
  13514. enumerable: true,
  13515. configurable: true
  13516. });
  13517. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesWidth", {
  13518. get: function () {
  13519. return this._numberOfTilesWidth;
  13520. },
  13521. set: function (value) {
  13522. this._numberOfTilesWidth = value;
  13523. this.updateShaderUniforms();
  13524. },
  13525. enumerable: true,
  13526. configurable: true
  13527. });
  13528. Object.defineProperty(MarbleProceduralTexture.prototype, "jointColor", {
  13529. get: function () {
  13530. return this._jointColor;
  13531. },
  13532. set: function (value) {
  13533. this._jointColor = value;
  13534. this.updateShaderUniforms();
  13535. },
  13536. enumerable: true,
  13537. configurable: true
  13538. });
  13539. Object.defineProperty(MarbleProceduralTexture.prototype, "marbleColor", {
  13540. get: function () {
  13541. return this._marbleColor;
  13542. },
  13543. set: function (value) {
  13544. this._marbleColor = value;
  13545. this.updateShaderUniforms();
  13546. },
  13547. enumerable: true,
  13548. configurable: true
  13549. });
  13550. return MarbleProceduralTexture;
  13551. })(BABYLON.ProceduralTexture);
  13552. BABYLON.MarbleProceduralTexture = MarbleProceduralTexture;
  13553. })(BABYLON || (BABYLON = {}));
  13554. //# sourceMappingURL=babylon.standardProceduralTexture.js.map
  13555. var BABYLON;
  13556. (function (BABYLON) {
  13557. var CustomProceduralTexture = (function (_super) {
  13558. __extends(CustomProceduralTexture, _super);
  13559. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  13560. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  13561. this._animate = true;
  13562. this._time = 0;
  13563. this._texturePath = texturePath;
  13564. //Try to load json
  13565. this.loadJson(texturePath);
  13566. this.refreshRate = 1;
  13567. }
  13568. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  13569. var _this = this;
  13570. var that = this;
  13571. function noConfigFile() {
  13572. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  13573. try {
  13574. that.setFragment(that._texturePath);
  13575. }
  13576. catch (ex) {
  13577. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  13578. }
  13579. }
  13580. var configFileUrl = jsonUrl + "/config.json";
  13581. var xhr = new XMLHttpRequest();
  13582. xhr.open("GET", configFileUrl, true);
  13583. xhr.addEventListener("load", function () {
  13584. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  13585. try {
  13586. _this._config = JSON.parse(xhr.response);
  13587. _this.updateShaderUniforms();
  13588. _this.updateTextures();
  13589. _this.setFragment(_this._texturePath + "/custom");
  13590. _this._animate = _this._config.animate;
  13591. _this.refreshRate = _this._config.refreshrate;
  13592. }
  13593. catch (ex) {
  13594. noConfigFile();
  13595. }
  13596. }
  13597. else {
  13598. noConfigFile();
  13599. }
  13600. }, false);
  13601. xhr.addEventListener("error", function () {
  13602. noConfigFile();
  13603. }, false);
  13604. try {
  13605. xhr.send();
  13606. }
  13607. catch (ex) {
  13608. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  13609. }
  13610. };
  13611. CustomProceduralTexture.prototype.isReady = function () {
  13612. if (!_super.prototype.isReady.call(this)) {
  13613. return false;
  13614. }
  13615. for (var name in this._textures) {
  13616. var texture = this._textures[name];
  13617. if (!texture.isReady()) {
  13618. return false;
  13619. }
  13620. }
  13621. return true;
  13622. };
  13623. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  13624. if (this._animate) {
  13625. this._time += this.getScene().getAnimationRatio() * 0.03;
  13626. this.updateShaderUniforms();
  13627. }
  13628. _super.prototype.render.call(this, useCameraPostProcess);
  13629. };
  13630. CustomProceduralTexture.prototype.updateTextures = function () {
  13631. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  13632. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  13633. }
  13634. };
  13635. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  13636. if (this._config) {
  13637. for (var j = 0; j < this._config.uniforms.length; j++) {
  13638. var uniform = this._config.uniforms[j];
  13639. switch (uniform.type) {
  13640. case "float":
  13641. this.setFloat(uniform.name, uniform.value);
  13642. break;
  13643. case "color3":
  13644. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  13645. break;
  13646. case "color4":
  13647. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  13648. break;
  13649. case "vector2":
  13650. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  13651. break;
  13652. case "vector3":
  13653. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  13654. break;
  13655. }
  13656. }
  13657. }
  13658. this.setFloat("time", this._time);
  13659. };
  13660. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  13661. get: function () {
  13662. return this._animate;
  13663. },
  13664. set: function (value) {
  13665. this._animate = value;
  13666. },
  13667. enumerable: true,
  13668. configurable: true
  13669. });
  13670. return CustomProceduralTexture;
  13671. })(BABYLON.ProceduralTexture);
  13672. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  13673. })(BABYLON || (BABYLON = {}));
  13674. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  13675. var BABYLON;
  13676. (function (BABYLON) {
  13677. var MirrorTexture = (function (_super) {
  13678. __extends(MirrorTexture, _super);
  13679. function MirrorTexture(name, size, scene, generateMipMaps) {
  13680. var _this = this;
  13681. _super.call(this, name, size, scene, generateMipMaps, true);
  13682. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  13683. this._transformMatrix = BABYLON.Matrix.Zero();
  13684. this._mirrorMatrix = BABYLON.Matrix.Zero();
  13685. this.onBeforeRender = function () {
  13686. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  13687. _this._savedViewMatrix = scene.getViewMatrix();
  13688. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  13689. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  13690. scene.clipPlane = _this.mirrorPlane;
  13691. scene.getEngine().cullBackFaces = false;
  13692. };
  13693. this.onAfterRender = function () {
  13694. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  13695. scene.getEngine().cullBackFaces = true;
  13696. delete scene.clipPlane;
  13697. };
  13698. }
  13699. MirrorTexture.prototype.clone = function () {
  13700. var textureSize = this.getSize();
  13701. var newTexture = new BABYLON.MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  13702. // Base texture
  13703. newTexture.hasAlpha = this.hasAlpha;
  13704. newTexture.level = this.level;
  13705. // Mirror Texture
  13706. newTexture.mirrorPlane = this.mirrorPlane.clone();
  13707. newTexture.renderList = this.renderList.slice(0);
  13708. return newTexture;
  13709. };
  13710. return MirrorTexture;
  13711. })(BABYLON.RenderTargetTexture);
  13712. BABYLON.MirrorTexture = MirrorTexture;
  13713. })(BABYLON || (BABYLON = {}));
  13714. //# sourceMappingURL=babylon.mirrorTexture.js.map
  13715. var BABYLON;
  13716. (function (BABYLON) {
  13717. var DynamicTexture = (function (_super) {
  13718. __extends(DynamicTexture, _super);
  13719. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  13720. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  13721. _super.call(this, null, scene, !generateMipMaps);
  13722. this.name = name;
  13723. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  13724. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  13725. this._generateMipMaps = generateMipMaps;
  13726. if (options.getContext) {
  13727. this._canvas = options;
  13728. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  13729. }
  13730. else {
  13731. this._canvas = document.createElement("canvas");
  13732. if (options.width) {
  13733. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  13734. }
  13735. else {
  13736. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  13737. }
  13738. }
  13739. var textureSize = this.getSize();
  13740. this._canvas.width = textureSize.width;
  13741. this._canvas.height = textureSize.height;
  13742. this._context = this._canvas.getContext("2d");
  13743. }
  13744. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  13745. get: function () {
  13746. return true;
  13747. },
  13748. enumerable: true,
  13749. configurable: true
  13750. });
  13751. DynamicTexture.prototype.scale = function (ratio) {
  13752. var textureSize = this.getSize();
  13753. textureSize.width *= ratio;
  13754. textureSize.height *= ratio;
  13755. this._canvas.width = textureSize.width;
  13756. this._canvas.height = textureSize.height;
  13757. this.releaseInternalTexture();
  13758. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  13759. };
  13760. DynamicTexture.prototype.getContext = function () {
  13761. return this._context;
  13762. };
  13763. DynamicTexture.prototype.clear = function () {
  13764. var size = this.getSize();
  13765. this._context.fillRect(0, 0, size.width, size.height);
  13766. };
  13767. DynamicTexture.prototype.update = function (invertY) {
  13768. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  13769. };
  13770. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  13771. if (update === void 0) { update = true; }
  13772. var size = this.getSize();
  13773. if (clearColor) {
  13774. this._context.fillStyle = clearColor;
  13775. this._context.fillRect(0, 0, size.width, size.height);
  13776. }
  13777. this._context.font = font;
  13778. if (x === null) {
  13779. var textSize = this._context.measureText(text);
  13780. x = (size.width - textSize.width) / 2;
  13781. }
  13782. this._context.fillStyle = color;
  13783. this._context.fillText(text, x, y);
  13784. if (update) {
  13785. this.update(invertY);
  13786. }
  13787. };
  13788. DynamicTexture.prototype.clone = function () {
  13789. var textureSize = this.getSize();
  13790. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  13791. // Base texture
  13792. newTexture.hasAlpha = this.hasAlpha;
  13793. newTexture.level = this.level;
  13794. // Dynamic Texture
  13795. newTexture.wrapU = this.wrapU;
  13796. newTexture.wrapV = this.wrapV;
  13797. return newTexture;
  13798. };
  13799. return DynamicTexture;
  13800. })(BABYLON.Texture);
  13801. BABYLON.DynamicTexture = DynamicTexture;
  13802. })(BABYLON || (BABYLON = {}));
  13803. //# sourceMappingURL=babylon.dynamicTexture.js.map
  13804. var BABYLON;
  13805. (function (BABYLON) {
  13806. var VideoTexture = (function (_super) {
  13807. __extends(VideoTexture, _super);
  13808. function VideoTexture(name, urls, size, scene, generateMipMaps, invertY, samplingMode) {
  13809. var _this = this;
  13810. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  13811. _super.call(this, null, scene, !generateMipMaps, invertY);
  13812. this._autoLaunch = true;
  13813. this.name = name;
  13814. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  13815. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  13816. var requiredWidth = size.width || size;
  13817. var requiredHeight = size.height || size;
  13818. this._texture = scene.getEngine().createDynamicTexture(requiredWidth, requiredHeight, generateMipMaps, samplingMode);
  13819. var textureSize = this.getSize();
  13820. this.video = document.createElement("video");
  13821. this.video.width = textureSize.width;
  13822. this.video.height = textureSize.height;
  13823. this.video.autoplay = false;
  13824. this.video.loop = true;
  13825. this.video.addEventListener("canplaythrough", function () {
  13826. if (_this._texture) {
  13827. _this._texture.isReady = true;
  13828. }
  13829. });
  13830. urls.forEach(function (url) {
  13831. //Backwards-compatibility for typescript 1. from 1.3 it should say "SOURCE". see here - https://github.com/Microsoft/TypeScript/issues/1850
  13832. var source = document.createElement("source");
  13833. source.src = url;
  13834. _this.video.appendChild(source);
  13835. });
  13836. this._lastUpdate = BABYLON.Tools.Now;
  13837. }
  13838. VideoTexture.prototype.update = function () {
  13839. if (this._autoLaunch) {
  13840. this._autoLaunch = false;
  13841. this.video.play();
  13842. }
  13843. var now = BABYLON.Tools.Now;
  13844. if (now - this._lastUpdate < 15) {
  13845. return false;
  13846. }
  13847. this._lastUpdate = now;
  13848. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  13849. return true;
  13850. };
  13851. return VideoTexture;
  13852. })(BABYLON.Texture);
  13853. BABYLON.VideoTexture = VideoTexture;
  13854. })(BABYLON || (BABYLON = {}));
  13855. //# sourceMappingURL=babylon.videoTexture.js.mapvar BABYLON;
  13856. (function (BABYLON) {
  13857. var EffectFallbacks = (function () {
  13858. function EffectFallbacks() {
  13859. this._defines = {};
  13860. this._currentRank = 32;
  13861. this._maxRank = -1;
  13862. }
  13863. EffectFallbacks.prototype.addFallback = function (rank, define) {
  13864. if (!this._defines[rank]) {
  13865. if (rank < this._currentRank) {
  13866. this._currentRank = rank;
  13867. }
  13868. if (rank > this._maxRank) {
  13869. this._maxRank = rank;
  13870. }
  13871. this._defines[rank] = new Array();
  13872. }
  13873. this._defines[rank].push(define);
  13874. };
  13875. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  13876. get: function () {
  13877. return this._currentRank <= this._maxRank;
  13878. },
  13879. enumerable: true,
  13880. configurable: true
  13881. });
  13882. EffectFallbacks.prototype.reduce = function (currentDefines) {
  13883. var currentFallbacks = this._defines[this._currentRank];
  13884. for (var index = 0; index < currentFallbacks.length; index++) {
  13885. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  13886. }
  13887. this._currentRank++;
  13888. return currentDefines;
  13889. };
  13890. return EffectFallbacks;
  13891. })();
  13892. BABYLON.EffectFallbacks = EffectFallbacks;
  13893. var Effect = (function () {
  13894. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  13895. var _this = this;
  13896. this._isReady = false;
  13897. this._compilationError = "";
  13898. this._valueCache = [];
  13899. this._engine = engine;
  13900. this.name = baseName;
  13901. this.defines = defines;
  13902. this._uniformsNames = uniformsNames.concat(samplers);
  13903. this._samplers = samplers;
  13904. this._attributesNames = attributesNames;
  13905. this.onError = onError;
  13906. this.onCompiled = onCompiled;
  13907. var vertexSource;
  13908. var fragmentSource;
  13909. if (baseName.vertexElement) {
  13910. vertexSource = document.getElementById(baseName.vertexElement);
  13911. if (!vertexSource) {
  13912. vertexSource = baseName.vertexElement;
  13913. }
  13914. }
  13915. else {
  13916. vertexSource = baseName.vertex || baseName;
  13917. }
  13918. if (baseName.fragmentElement) {
  13919. fragmentSource = document.getElementById(baseName.fragmentElement);
  13920. if (!fragmentSource) {
  13921. fragmentSource = baseName.fragmentElement;
  13922. }
  13923. }
  13924. else {
  13925. fragmentSource = baseName.fragment || baseName;
  13926. }
  13927. this._loadVertexShader(vertexSource, function (vertexCode) {
  13928. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  13929. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  13930. });
  13931. });
  13932. }
  13933. // Properties
  13934. Effect.prototype.isReady = function () {
  13935. return this._isReady;
  13936. };
  13937. Effect.prototype.getProgram = function () {
  13938. return this._program;
  13939. };
  13940. Effect.prototype.getAttributesNames = function () {
  13941. return this._attributesNames;
  13942. };
  13943. Effect.prototype.getAttributeLocation = function (index) {
  13944. return this._attributes[index];
  13945. };
  13946. Effect.prototype.getAttributeLocationByName = function (name) {
  13947. var index = this._attributesNames.indexOf(name);
  13948. return this._attributes[index];
  13949. };
  13950. Effect.prototype.getAttributesCount = function () {
  13951. return this._attributes.length;
  13952. };
  13953. Effect.prototype.getUniformIndex = function (uniformName) {
  13954. return this._uniformsNames.indexOf(uniformName);
  13955. };
  13956. Effect.prototype.getUniform = function (uniformName) {
  13957. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  13958. };
  13959. Effect.prototype.getSamplers = function () {
  13960. return this._samplers;
  13961. };
  13962. Effect.prototype.getCompilationError = function () {
  13963. return this._compilationError;
  13964. };
  13965. // Methods
  13966. Effect.prototype._loadVertexShader = function (vertex, callback) {
  13967. // DOM element ?
  13968. if (vertex instanceof HTMLElement) {
  13969. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  13970. callback(vertexCode);
  13971. return;
  13972. }
  13973. // Is in local store ?
  13974. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  13975. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  13976. return;
  13977. }
  13978. var vertexShaderUrl;
  13979. if (vertex[0] === ".") {
  13980. vertexShaderUrl = vertex;
  13981. }
  13982. else {
  13983. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  13984. }
  13985. // Vertex shader
  13986. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  13987. };
  13988. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  13989. // DOM element ?
  13990. if (fragment instanceof HTMLElement) {
  13991. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  13992. callback(fragmentCode);
  13993. return;
  13994. }
  13995. // Is in local store ?
  13996. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  13997. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  13998. return;
  13999. }
  14000. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  14001. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  14002. return;
  14003. }
  14004. var fragmentShaderUrl;
  14005. if (fragment[0] === ".") {
  14006. fragmentShaderUrl = fragment;
  14007. }
  14008. else {
  14009. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  14010. }
  14011. // Fragment shader
  14012. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  14013. };
  14014. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  14015. try {
  14016. var engine = this._engine;
  14017. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  14018. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  14019. this._attributes = engine.getAttributes(this._program, attributesNames);
  14020. for (var index = 0; index < this._samplers.length; index++) {
  14021. var sampler = this.getUniform(this._samplers[index]);
  14022. if (sampler == null) {
  14023. this._samplers.splice(index, 1);
  14024. index--;
  14025. }
  14026. }
  14027. engine.bindSamplers(this);
  14028. this._isReady = true;
  14029. if (this.onCompiled) {
  14030. this.onCompiled(this);
  14031. }
  14032. }
  14033. catch (e) {
  14034. // Is it a problem with precision?
  14035. if (e.message.indexOf("highp") !== -1) {
  14036. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  14037. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  14038. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  14039. return;
  14040. }
  14041. // Let's go through fallbacks then
  14042. if (fallbacks && fallbacks.isMoreFallbacks) {
  14043. defines = fallbacks.reduce(defines);
  14044. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  14045. }
  14046. else {
  14047. BABYLON.Tools.Error("Unable to compile effect: " + this.name);
  14048. BABYLON.Tools.Error("Defines: " + defines);
  14049. BABYLON.Tools.Error("Error: " + e.message);
  14050. this._compilationError = e.message;
  14051. if (this.onError) {
  14052. this.onError(this, this._compilationError);
  14053. }
  14054. }
  14055. }
  14056. };
  14057. Effect.prototype._bindTexture = function (channel, texture) {
  14058. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  14059. };
  14060. Effect.prototype.setTexture = function (channel, texture) {
  14061. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  14062. };
  14063. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  14064. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  14065. };
  14066. //public _cacheMatrix(uniformName, matrix) {
  14067. // if (!this._valueCache[uniformName]) {
  14068. // this._valueCache[uniformName] = new BABYLON.Matrix();
  14069. // }
  14070. // for (var index = 0; index < 16; index++) {
  14071. // this._valueCache[uniformName].m[index] = matrix.m[index];
  14072. // }
  14073. //};
  14074. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  14075. if (!this._valueCache[uniformName]) {
  14076. this._valueCache[uniformName] = [x, y];
  14077. return;
  14078. }
  14079. this._valueCache[uniformName][0] = x;
  14080. this._valueCache[uniformName][1] = y;
  14081. };
  14082. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  14083. if (!this._valueCache[uniformName]) {
  14084. this._valueCache[uniformName] = [x, y, z];
  14085. return;
  14086. }
  14087. this._valueCache[uniformName][0] = x;
  14088. this._valueCache[uniformName][1] = y;
  14089. this._valueCache[uniformName][2] = z;
  14090. };
  14091. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  14092. if (!this._valueCache[uniformName]) {
  14093. this._valueCache[uniformName] = [x, y, z, w];
  14094. return;
  14095. }
  14096. this._valueCache[uniformName][0] = x;
  14097. this._valueCache[uniformName][1] = y;
  14098. this._valueCache[uniformName][2] = z;
  14099. this._valueCache[uniformName][3] = w;
  14100. };
  14101. Effect.prototype.setArray = function (uniformName, array) {
  14102. this._engine.setArray(this.getUniform(uniformName), array);
  14103. return this;
  14104. };
  14105. Effect.prototype.setArray2 = function (uniformName, array) {
  14106. this._engine.setArray2(this.getUniform(uniformName), array);
  14107. return this;
  14108. };
  14109. Effect.prototype.setArray3 = function (uniformName, array) {
  14110. this._engine.setArray3(this.getUniform(uniformName), array);
  14111. return this;
  14112. };
  14113. Effect.prototype.setArray4 = function (uniformName, array) {
  14114. this._engine.setArray4(this.getUniform(uniformName), array);
  14115. return this;
  14116. };
  14117. Effect.prototype.setMatrices = function (uniformName, matrices) {
  14118. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  14119. return this;
  14120. };
  14121. Effect.prototype.setMatrix = function (uniformName, matrix) {
  14122. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  14123. // return;
  14124. //this._cacheMatrix(uniformName, matrix);
  14125. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  14126. return this;
  14127. };
  14128. Effect.prototype.setFloat = function (uniformName, value) {
  14129. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  14130. return this;
  14131. this._valueCache[uniformName] = value;
  14132. this._engine.setFloat(this.getUniform(uniformName), value);
  14133. return this;
  14134. };
  14135. Effect.prototype.setBool = function (uniformName, bool) {
  14136. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  14137. return this;
  14138. this._valueCache[uniformName] = bool;
  14139. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  14140. return this;
  14141. };
  14142. Effect.prototype.setVector2 = function (uniformName, vector2) {
  14143. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  14144. return this;
  14145. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  14146. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  14147. return this;
  14148. };
  14149. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  14150. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  14151. return this;
  14152. this._cacheFloat2(uniformName, x, y);
  14153. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  14154. return this;
  14155. };
  14156. Effect.prototype.setVector3 = function (uniformName, vector3) {
  14157. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  14158. return this;
  14159. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  14160. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  14161. return this;
  14162. };
  14163. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  14164. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  14165. return this;
  14166. this._cacheFloat3(uniformName, x, y, z);
  14167. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  14168. return this;
  14169. };
  14170. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  14171. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  14172. return this;
  14173. this._cacheFloat4(uniformName, x, y, z, w);
  14174. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  14175. return this;
  14176. };
  14177. Effect.prototype.setColor3 = function (uniformName, color3) {
  14178. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  14179. return this;
  14180. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  14181. this._engine.setColor3(this.getUniform(uniformName), color3);
  14182. return this;
  14183. };
  14184. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  14185. 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)
  14186. return this;
  14187. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  14188. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  14189. return this;
  14190. };
  14191. // Statics
  14192. 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}",
  14193. 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}",
  14194. 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}",
  14195. 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}",
  14196. 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}",
  14197. 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}",
  14198. colorPixelShader:"precision highp float;\n\nuniform vec4 color;\n\nvoid main(void) {\n gl_FragColor = color;\n}",
  14199. 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}",
  14200. colorCorrectionPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// samplers\nuniform sampler2D textureSampler; // screen render\nuniform sampler2D colorTable; // color table with modified colors\n\n// varyings\nvarying vec2 vUV;\n\n// constants\nconst float SLICE_COUNT = 16.0; // how many slices in the color cube; 1 slice = 1 pixel\n// it means the image is 256x16 pixels\n\nvec4 sampleAs3DTexture(sampler2D texture, vec3 uv, float width) {\n float sliceSize = 1.0 / width; // space of 1 slice\n float slicePixelSize = sliceSize / width; // space of 1 pixel\n float sliceInnerSize = slicePixelSize * (width - 1.0); // space of width pixels\n float zSlice0 = min(floor(uv.z * width), width - 1.0);\n float zSlice1 = min(zSlice0 + 1.0, width - 1.0);\n float xOffset = slicePixelSize * 0.5 + uv.x * sliceInnerSize;\n float s0 = xOffset + (zSlice0 * sliceSize);\n float s1 = xOffset + (zSlice1 * sliceSize);\n vec4 slice0Color = texture2D(texture, vec2(s0, uv.y));\n vec4 slice1Color = texture2D(texture, vec2(s1, uv.y));\n float zOffset = mod(uv.z * width, 1.0);\n vec4 result = mix(slice0Color, slice1Color, zOffset);\n return result;\n}\n\nvoid main(void)\n{\n vec4 screen_color = texture2D(textureSampler, vUV);\n gl_FragColor = sampleAs3DTexture(colorTable, screen_color.rgb, SLICE_COUNT);\n\n}",
  14201. 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}",
  14202. 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 vec3 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 vec3 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 vec3 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 vec3 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 depth = 0.5 * depth + vec3(0.5);\n vec2 uv = depth.xy;\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 depth = 0.5 * depth + vec3(0.5);\n vec2 uv = depth.xy;\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 float biasedDepth = depth.z - bias;\n\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[0] / mapSize)) < biasedDepth) visibility -= 0.25;\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[1] / mapSize)) < biasedDepth) visibility -= 0.25;\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[2] / mapSize)) < biasedDepth) visibility -= 0.25;\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[3] / mapSize)) < biasedDepth) visibility -= 0.25;\n\n return visibility;\n}\n\n// Thanks to http://devmaster.net/\nfloat linstep(float low, float high, float v) {\n return clamp((v - low) / (high - low), 0.0, 1.0);\n}\n\nfloat ChebychevInequality(vec2 moments, float compare, float bias)\n{\n float p = smoothstep(compare - bias, compare, moments.x);\n float variance = max(moments.y - moments.x * moments.x, 0.02);\n float d = compare - moments.x;\n float p_max = linstep(0.2, 1.0, variance / (variance + d * d));\n\n return clamp(max(p, p_max), 0.0, 1.0);\n}\n\nfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler, float bias)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n depth = 0.5 * depth + vec3(0.5);\n vec2 uv = depth.xy;\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, bias);\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.z);\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.z);\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.z);\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.z);\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}",
  14203. 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}",
  14204. 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}",
  14205. 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#if defined(ALPHATEST) || defined(NEED_UV)\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#if defined(ALPHATEST) || defined(BASIC_RENDER)\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}",
  14206. depthBoxBlurPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\n// Parameters\nuniform vec2 screenSize;\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}",
  14207. 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}",
  14208. 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}",
  14209. 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}",
  14210. 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}",
  14211. 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}",
  14212. 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}",
  14213. 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}",
  14214. 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}",
  14215. 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}",
  14216. 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}",
  14217. 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}",
  14218. 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}",
  14219. 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}",
  14220. 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}",
  14221. 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}",
  14222. 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}",
  14223. 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}",
  14224. 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}",
  14225. 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}",
  14226. 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}",
  14227. 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}",
  14228. 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}",
  14229. 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}",
  14230. 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\nvarying vec4 vPosition;\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 float depth = vPosition.z / vPosition.w;\n depth = depth * 0.5 + 0.5;\n\n#ifdef VSM\n float moment1 = depth;\n float moment2 = moment1 * moment1;\n\n gl_FragColor = vec4(packHalf(moment1), packHalf(moment2));\n#else\n gl_FragColor = pack(depth);\n#endif\n}",
  14231. 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\nvarying vec4 vPosition;\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 vPosition = viewProjection * finalWorld * vec4(position, 1.0);\n gl_Position = vPosition;\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}",
  14232. 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}",
  14233. spritesVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attributes\nattribute vec4 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.xyz, 1.0)).xyz; \n vec2 cornerPos;\n \n float angle = position.w;\n vec2 size = vec2(options.x, options.y);\n vec2 offset = options.zw;\n vec2 uvScale = textureInfos.xy;\n\n cornerPos = vec2(offset.x - 0.5, offset.y - 0.5) * 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}",
  14234. 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\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\n\nvarying vec2 vUV;\n\nconst vec2 offset1 = vec2(0.0, 0.001);\nconst vec2 offset2 = vec2(0.001, 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 base = 0.2;\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 + sign(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}",
  14235. 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}",
  14236. 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}",
  14237. 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;\nuniform float opacityLevel;\n#endif\n\nvoid main(void)\n{\n#if defined(ALPHATEST) || 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 OPACITY\n vec4 opacityColor = texture2D(opacitySampler, vUV);\n float alpha = 1.0;\n\n #ifdef OPACITYRGB\n opacityColor.rgb = opacityColor.rgb * vec3(0.3, 0.59, 0.11);\n alpha *= (opacityColor.x + opacityColor.y + opacityColor.z) * opacityLevel;\n #else\n alpha *= opacityColor.a * opacityLevel;\n #endif\n\n #if defined(BASIC_RENDER)\n gl_FragColor = vec4(diffuseColor.rgb, alpha);\n #else\n gl_FragColor = vec4(0.0, 0.0, 0.0, alpha);\n #endif\n\n gl_FragColor.a = alpha;\n#else\n #ifndef BASIC_RENDER\n gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\n #else\n gl_FragColor = diffuseColor;\n #endif\n#endif\n\n}",
  14238. 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}",
  14239. };
  14240. return Effect;
  14241. })();
  14242. BABYLON.Effect = Effect;
  14243. })(BABYLON || (BABYLON = {}));
  14244. //# sourceMappingURL=babylon.effect.js.mapvar BABYLON;
  14245. (function (BABYLON) {
  14246. var Material = (function () {
  14247. function Material(name, scene, doNotAdd) {
  14248. this.name = name;
  14249. this.checkReadyOnEveryCall = true;
  14250. this.checkReadyOnlyOnce = false;
  14251. this.state = "";
  14252. this.alpha = 1.0;
  14253. this.backFaceCulling = true;
  14254. this._wasPreviouslyReady = false;
  14255. this._fillMode = Material.TriangleFillMode;
  14256. this.pointSize = 1.0;
  14257. this.id = name;
  14258. this._scene = scene;
  14259. if (!doNotAdd) {
  14260. scene.materials.push(this);
  14261. }
  14262. }
  14263. Object.defineProperty(Material, "TriangleFillMode", {
  14264. get: function () {
  14265. return Material._TriangleFillMode;
  14266. },
  14267. enumerable: true,
  14268. configurable: true
  14269. });
  14270. Object.defineProperty(Material, "WireFrameFillMode", {
  14271. get: function () {
  14272. return Material._WireFrameFillMode;
  14273. },
  14274. enumerable: true,
  14275. configurable: true
  14276. });
  14277. Object.defineProperty(Material, "PointFillMode", {
  14278. get: function () {
  14279. return Material._PointFillMode;
  14280. },
  14281. enumerable: true,
  14282. configurable: true
  14283. });
  14284. Object.defineProperty(Material.prototype, "wireframe", {
  14285. get: function () {
  14286. return this._fillMode === Material.WireFrameFillMode;
  14287. },
  14288. set: function (value) {
  14289. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  14290. },
  14291. enumerable: true,
  14292. configurable: true
  14293. });
  14294. Object.defineProperty(Material.prototype, "pointsCloud", {
  14295. get: function () {
  14296. return this._fillMode === Material.PointFillMode;
  14297. },
  14298. set: function (value) {
  14299. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  14300. },
  14301. enumerable: true,
  14302. configurable: true
  14303. });
  14304. Object.defineProperty(Material.prototype, "fillMode", {
  14305. get: function () {
  14306. return this._fillMode;
  14307. },
  14308. set: function (value) {
  14309. this._fillMode = value;
  14310. },
  14311. enumerable: true,
  14312. configurable: true
  14313. });
  14314. Material.prototype.isReady = function (mesh, useInstances) {
  14315. return true;
  14316. };
  14317. Material.prototype.getEffect = function () {
  14318. return this._effect;
  14319. };
  14320. Material.prototype.getScene = function () {
  14321. return this._scene;
  14322. };
  14323. Material.prototype.needAlphaBlending = function () {
  14324. return (this.alpha < 1.0);
  14325. };
  14326. Material.prototype.needAlphaTesting = function () {
  14327. return false;
  14328. };
  14329. Material.prototype.getAlphaTestTexture = function () {
  14330. return null;
  14331. };
  14332. Material.prototype.trackCreation = function (onCompiled, onError) {
  14333. };
  14334. Material.prototype._preBind = function () {
  14335. var engine = this._scene.getEngine();
  14336. engine.enableEffect(this._effect);
  14337. engine.setState(this.backFaceCulling);
  14338. };
  14339. Material.prototype.bind = function (world, mesh) {
  14340. this._scene._cachedMaterial = this;
  14341. if (this.onBind) {
  14342. this.onBind(this);
  14343. }
  14344. };
  14345. Material.prototype.bindOnlyWorldMatrix = function (world) {
  14346. };
  14347. Material.prototype.unbind = function () {
  14348. };
  14349. Material.prototype.dispose = function (forceDisposeEffect) {
  14350. // Remove from scene
  14351. var index = this._scene.materials.indexOf(this);
  14352. this._scene.materials.splice(index, 1);
  14353. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  14354. if (forceDisposeEffect && this._effect) {
  14355. this._scene.getEngine()._releaseEffect(this._effect);
  14356. this._effect = null;
  14357. }
  14358. // Callback
  14359. if (this.onDispose) {
  14360. this.onDispose();
  14361. }
  14362. };
  14363. Material._TriangleFillMode = 0;
  14364. Material._WireFrameFillMode = 1;
  14365. Material._PointFillMode = 2;
  14366. return Material;
  14367. })();
  14368. BABYLON.Material = Material;
  14369. })(BABYLON || (BABYLON = {}));
  14370. //# sourceMappingURL=babylon.material.js.map
  14371. var BABYLON;
  14372. (function (BABYLON) {
  14373. var maxSimultaneousLights = 4;
  14374. var FresnelParameters = (function () {
  14375. function FresnelParameters() {
  14376. this.isEnabled = true;
  14377. this.leftColor = BABYLON.Color3.White();
  14378. this.rightColor = BABYLON.Color3.Black();
  14379. this.bias = 0;
  14380. this.power = 1;
  14381. }
  14382. return FresnelParameters;
  14383. })();
  14384. BABYLON.FresnelParameters = FresnelParameters;
  14385. var StandardMaterial = (function (_super) {
  14386. __extends(StandardMaterial, _super);
  14387. function StandardMaterial(name, scene) {
  14388. var _this = this;
  14389. _super.call(this, name, scene);
  14390. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  14391. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  14392. this.specularColor = new BABYLON.Color3(1, 1, 1);
  14393. this.specularPower = 64;
  14394. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  14395. this.useAlphaFromDiffuseTexture = false;
  14396. this.useSpecularOverAlpha = true;
  14397. this.fogEnabled = true;
  14398. this._cachedDefines = null;
  14399. this._renderTargets = new BABYLON.SmartArray(16);
  14400. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  14401. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  14402. this._scaledDiffuse = new BABYLON.Color3();
  14403. this._scaledSpecular = new BABYLON.Color3();
  14404. this.getRenderTargetTextures = function () {
  14405. _this._renderTargets.reset();
  14406. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  14407. _this._renderTargets.push(_this.reflectionTexture);
  14408. }
  14409. return _this._renderTargets;
  14410. };
  14411. }
  14412. StandardMaterial.prototype.needAlphaBlending = function () {
  14413. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  14414. };
  14415. StandardMaterial.prototype.needAlphaTesting = function () {
  14416. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && !this.diffuseTexture.getAlphaFromRGB;
  14417. };
  14418. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  14419. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  14420. };
  14421. StandardMaterial.prototype.getAlphaTestTexture = function () {
  14422. return this.diffuseTexture;
  14423. };
  14424. // Methods
  14425. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  14426. if (this.checkReadyOnlyOnce) {
  14427. if (this._wasPreviouslyReady) {
  14428. }
  14429. }
  14430. var scene = this.getScene();
  14431. if (!this.checkReadyOnEveryCall) {
  14432. if (this._renderId === scene.getRenderId()) {
  14433. }
  14434. }
  14435. var engine = scene.getEngine();
  14436. var defines = [];
  14437. var fallbacks = new BABYLON.EffectFallbacks();
  14438. var needNormals = false;
  14439. var needUVs = false;
  14440. // Textures
  14441. if (scene.texturesEnabled) {
  14442. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  14443. if (!this.diffuseTexture.isReady()) {
  14444. return false;
  14445. }
  14446. else {
  14447. needUVs = true;
  14448. defines.push("#define DIFFUSE");
  14449. }
  14450. }
  14451. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  14452. if (!this.ambientTexture.isReady()) {
  14453. return false;
  14454. }
  14455. else {
  14456. needUVs = true;
  14457. defines.push("#define AMBIENT");
  14458. }
  14459. }
  14460. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  14461. if (!this.opacityTexture.isReady()) {
  14462. return false;
  14463. }
  14464. else {
  14465. needUVs = true;
  14466. defines.push("#define OPACITY");
  14467. if (this.opacityTexture.getAlphaFromRGB) {
  14468. defines.push("#define OPACITYRGB");
  14469. }
  14470. }
  14471. }
  14472. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  14473. if (!this.reflectionTexture.isReady()) {
  14474. return false;
  14475. }
  14476. else {
  14477. needNormals = true;
  14478. needUVs = true;
  14479. defines.push("#define REFLECTION");
  14480. fallbacks.addFallback(0, "REFLECTION");
  14481. }
  14482. }
  14483. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  14484. if (!this.emissiveTexture.isReady()) {
  14485. return false;
  14486. }
  14487. else {
  14488. needUVs = true;
  14489. defines.push("#define EMISSIVE");
  14490. }
  14491. }
  14492. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  14493. if (!this.specularTexture.isReady()) {
  14494. return false;
  14495. }
  14496. else {
  14497. needUVs = true;
  14498. defines.push("#define SPECULAR");
  14499. fallbacks.addFallback(0, "SPECULAR");
  14500. }
  14501. }
  14502. }
  14503. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  14504. if (!this.bumpTexture.isReady()) {
  14505. return false;
  14506. }
  14507. else {
  14508. needUVs = true;
  14509. defines.push("#define BUMP");
  14510. fallbacks.addFallback(0, "BUMP");
  14511. }
  14512. }
  14513. // Effect
  14514. if (this.useSpecularOverAlpha) {
  14515. defines.push("#define SPECULAROVERALPHA");
  14516. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  14517. }
  14518. if (scene.clipPlane) {
  14519. defines.push("#define CLIPPLANE");
  14520. }
  14521. if (engine.getAlphaTesting()) {
  14522. defines.push("#define ALPHATEST");
  14523. }
  14524. if (this._shouldUseAlphaFromDiffuseTexture()) {
  14525. defines.push("#define ALPHAFROMDIFFUSE");
  14526. }
  14527. // Point size
  14528. if (this.pointsCloud || scene.forcePointsCloud) {
  14529. defines.push("#define POINTSIZE");
  14530. }
  14531. // Fog
  14532. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  14533. defines.push("#define FOG");
  14534. fallbacks.addFallback(1, "FOG");
  14535. }
  14536. var shadowsActivated = false;
  14537. var lightIndex = 0;
  14538. if (scene.lightsEnabled) {
  14539. for (var index = 0; index < scene.lights.length; index++) {
  14540. var light = scene.lights[index];
  14541. if (!light.isEnabled()) {
  14542. continue;
  14543. }
  14544. // Excluded check
  14545. if (light._excludedMeshesIds.length > 0) {
  14546. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  14547. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  14548. if (excludedMesh) {
  14549. light.excludedMeshes.push(excludedMesh);
  14550. }
  14551. }
  14552. light._excludedMeshesIds = [];
  14553. }
  14554. // Included check
  14555. if (light._includedOnlyMeshesIds.length > 0) {
  14556. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  14557. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  14558. if (includedOnlyMesh) {
  14559. light.includedOnlyMeshes.push(includedOnlyMesh);
  14560. }
  14561. }
  14562. light._includedOnlyMeshesIds = [];
  14563. }
  14564. if (!light.canAffectMesh(mesh)) {
  14565. continue;
  14566. }
  14567. needNormals = true;
  14568. defines.push("#define LIGHT" + lightIndex);
  14569. if (lightIndex > 0) {
  14570. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  14571. }
  14572. var type;
  14573. if (light instanceof BABYLON.SpotLight) {
  14574. type = "#define SPOTLIGHT" + lightIndex;
  14575. }
  14576. else if (light instanceof BABYLON.HemisphericLight) {
  14577. type = "#define HEMILIGHT" + lightIndex;
  14578. }
  14579. else {
  14580. type = "#define POINTDIRLIGHT" + lightIndex;
  14581. }
  14582. defines.push(type);
  14583. if (lightIndex > 0) {
  14584. fallbacks.addFallback(lightIndex, type.replace("#define ", ""));
  14585. }
  14586. // Shadows
  14587. if (scene.shadowsEnabled) {
  14588. var shadowGenerator = light.getShadowGenerator();
  14589. if (mesh && mesh.receiveShadows && shadowGenerator) {
  14590. defines.push("#define SHADOW" + lightIndex);
  14591. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  14592. if (!shadowsActivated) {
  14593. defines.push("#define SHADOWS");
  14594. shadowsActivated = true;
  14595. }
  14596. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  14597. defines.push("#define SHADOWVSM" + lightIndex);
  14598. if (lightIndex > 0) {
  14599. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  14600. }
  14601. }
  14602. if (shadowGenerator.usePoissonSampling) {
  14603. defines.push("#define SHADOWPCF" + lightIndex);
  14604. if (lightIndex > 0) {
  14605. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  14606. }
  14607. }
  14608. }
  14609. }
  14610. lightIndex++;
  14611. if (lightIndex === maxSimultaneousLights)
  14612. break;
  14613. }
  14614. }
  14615. if (StandardMaterial.FresnelEnabled) {
  14616. // Fresnel
  14617. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled || this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled || this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  14618. var fresnelRank = 1;
  14619. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  14620. defines.push("#define DIFFUSEFRESNEL");
  14621. fallbacks.addFallback(fresnelRank, "DIFFUSEFRESNEL");
  14622. fresnelRank++;
  14623. }
  14624. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  14625. defines.push("#define OPACITYFRESNEL");
  14626. fallbacks.addFallback(fresnelRank, "OPACITYFRESNEL");
  14627. fresnelRank++;
  14628. }
  14629. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  14630. defines.push("#define REFLECTIONFRESNEL");
  14631. fallbacks.addFallback(fresnelRank, "REFLECTIONFRESNEL");
  14632. fresnelRank++;
  14633. }
  14634. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  14635. defines.push("#define EMISSIVEFRESNEL");
  14636. fallbacks.addFallback(fresnelRank, "EMISSIVEFRESNEL");
  14637. fresnelRank++;
  14638. }
  14639. needNormals = true;
  14640. defines.push("#define FRESNEL");
  14641. fallbacks.addFallback(fresnelRank - 1, "FRESNEL");
  14642. }
  14643. }
  14644. // Attribs
  14645. var attribs = [BABYLON.VertexBuffer.PositionKind];
  14646. if (mesh) {
  14647. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  14648. attribs.push(BABYLON.VertexBuffer.NormalKind);
  14649. defines.push("#define NORMAL");
  14650. }
  14651. if (needUVs) {
  14652. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  14653. attribs.push(BABYLON.VertexBuffer.UVKind);
  14654. defines.push("#define UV1");
  14655. }
  14656. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  14657. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  14658. defines.push("#define UV2");
  14659. }
  14660. }
  14661. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  14662. attribs.push(BABYLON.VertexBuffer.ColorKind);
  14663. defines.push("#define VERTEXCOLOR");
  14664. if (mesh.hasVertexAlpha) {
  14665. defines.push("#define VERTEXALPHA");
  14666. }
  14667. }
  14668. if (mesh.useBones) {
  14669. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  14670. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  14671. defines.push("#define BONES");
  14672. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  14673. defines.push("#define BONES4");
  14674. fallbacks.addFallback(0, "BONES4");
  14675. }
  14676. // Instances
  14677. if (useInstances) {
  14678. defines.push("#define INSTANCES");
  14679. attribs.push("world0");
  14680. attribs.push("world1");
  14681. attribs.push("world2");
  14682. attribs.push("world3");
  14683. }
  14684. }
  14685. // Get correct effect
  14686. var join = defines.join("\n");
  14687. if (this._cachedDefines !== join) {
  14688. this._cachedDefines = join;
  14689. scene.resetCachedMaterial();
  14690. // Legacy browser patch
  14691. var shaderName = "default";
  14692. if (!scene.getEngine().getCaps().standardDerivatives) {
  14693. shaderName = "legacydefault";
  14694. }
  14695. 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);
  14696. }
  14697. if (!this._effect.isReady()) {
  14698. return false;
  14699. }
  14700. this._renderId = scene.getRenderId();
  14701. this._wasPreviouslyReady = true;
  14702. return true;
  14703. };
  14704. StandardMaterial.prototype.unbind = function () {
  14705. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  14706. this._effect.setTexture("reflection2DSampler", null);
  14707. }
  14708. };
  14709. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  14710. this._effect.setMatrix("world", world);
  14711. };
  14712. StandardMaterial.prototype.bind = function (world, mesh) {
  14713. var scene = this.getScene();
  14714. // Matrices
  14715. this.bindOnlyWorldMatrix(world);
  14716. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  14717. // Bones
  14718. if (mesh.useBones) {
  14719. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  14720. }
  14721. if (scene.getCachedMaterial() !== this) {
  14722. if (StandardMaterial.FresnelEnabled) {
  14723. // Fresnel
  14724. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  14725. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  14726. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  14727. }
  14728. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  14729. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  14730. }
  14731. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  14732. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  14733. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  14734. }
  14735. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  14736. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  14737. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  14738. }
  14739. }
  14740. // Textures
  14741. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  14742. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  14743. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  14744. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  14745. }
  14746. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  14747. this._effect.setTexture("ambientSampler", this.ambientTexture);
  14748. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  14749. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  14750. }
  14751. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  14752. this._effect.setTexture("opacitySampler", this.opacityTexture);
  14753. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  14754. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  14755. }
  14756. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  14757. if (this.reflectionTexture.isCube) {
  14758. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  14759. }
  14760. else {
  14761. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  14762. }
  14763. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  14764. this._effect.setFloat3("vReflectionInfos", this.reflectionTexture.coordinatesMode, this.reflectionTexture.level, this.reflectionTexture.isCube ? 1 : 0);
  14765. }
  14766. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  14767. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  14768. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  14769. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  14770. }
  14771. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  14772. this._effect.setTexture("specularSampler", this.specularTexture);
  14773. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  14774. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  14775. }
  14776. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  14777. this._effect.setTexture("bumpSampler", this.bumpTexture);
  14778. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level);
  14779. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  14780. }
  14781. // Clip plane
  14782. if (scene.clipPlane) {
  14783. var clipPlane = scene.clipPlane;
  14784. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  14785. }
  14786. // Point size
  14787. if (this.pointsCloud) {
  14788. this._effect.setFloat("pointSize", this.pointSize);
  14789. }
  14790. // Colors
  14791. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  14792. // Scaling down color according to emissive
  14793. this._scaledSpecular.r = this.specularColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  14794. this._scaledSpecular.g = this.specularColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  14795. this._scaledSpecular.b = this.specularColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  14796. this._effect.setVector3("vEyePosition", scene.activeCamera.position);
  14797. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  14798. this._effect.setColor4("vSpecularColor", this._scaledSpecular, this.specularPower);
  14799. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  14800. }
  14801. // Scaling down color according to emissive
  14802. this._scaledDiffuse.r = this.diffuseColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  14803. this._scaledDiffuse.g = this.diffuseColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  14804. this._scaledDiffuse.b = this.diffuseColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  14805. this._effect.setColor4("vDiffuseColor", this._scaledDiffuse, this.alpha * mesh.visibility);
  14806. if (scene.lightsEnabled) {
  14807. var lightIndex = 0;
  14808. for (var index = 0; index < scene.lights.length; index++) {
  14809. var light = scene.lights[index];
  14810. if (!light.isEnabled()) {
  14811. continue;
  14812. }
  14813. if (!light.canAffectMesh(mesh)) {
  14814. continue;
  14815. }
  14816. if (light instanceof BABYLON.PointLight) {
  14817. // Point Light
  14818. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  14819. }
  14820. else if (light instanceof BABYLON.DirectionalLight) {
  14821. // Directional Light
  14822. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  14823. }
  14824. else if (light instanceof BABYLON.SpotLight) {
  14825. // Spot Light
  14826. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  14827. }
  14828. else if (light instanceof BABYLON.HemisphericLight) {
  14829. // Hemispheric Light
  14830. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  14831. }
  14832. light.diffuse.scaleToRef(light.intensity, this._scaledDiffuse);
  14833. light.specular.scaleToRef(light.intensity, this._scaledSpecular);
  14834. this._effect.setColor4("vLightDiffuse" + lightIndex, this._scaledDiffuse, light.range);
  14835. this._effect.setColor3("vLightSpecular" + lightIndex, this._scaledSpecular);
  14836. // Shadows
  14837. if (scene.shadowsEnabled) {
  14838. var shadowGenerator = light.getShadowGenerator();
  14839. if (mesh.receiveShadows && shadowGenerator) {
  14840. this._effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  14841. this._effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  14842. this._effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  14843. }
  14844. }
  14845. lightIndex++;
  14846. if (lightIndex === maxSimultaneousLights)
  14847. break;
  14848. }
  14849. }
  14850. // View
  14851. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  14852. this._effect.setMatrix("view", scene.getViewMatrix());
  14853. }
  14854. // Fog
  14855. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  14856. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  14857. this._effect.setColor3("vFogColor", scene.fogColor);
  14858. }
  14859. _super.prototype.bind.call(this, world, mesh);
  14860. };
  14861. StandardMaterial.prototype.getAnimatables = function () {
  14862. var results = [];
  14863. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  14864. results.push(this.diffuseTexture);
  14865. }
  14866. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  14867. results.push(this.ambientTexture);
  14868. }
  14869. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  14870. results.push(this.opacityTexture);
  14871. }
  14872. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  14873. results.push(this.reflectionTexture);
  14874. }
  14875. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  14876. results.push(this.emissiveTexture);
  14877. }
  14878. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  14879. results.push(this.specularTexture);
  14880. }
  14881. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  14882. results.push(this.bumpTexture);
  14883. }
  14884. return results;
  14885. };
  14886. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  14887. if (this.diffuseTexture) {
  14888. this.diffuseTexture.dispose();
  14889. }
  14890. if (this.ambientTexture) {
  14891. this.ambientTexture.dispose();
  14892. }
  14893. if (this.opacityTexture) {
  14894. this.opacityTexture.dispose();
  14895. }
  14896. if (this.reflectionTexture) {
  14897. this.reflectionTexture.dispose();
  14898. }
  14899. if (this.emissiveTexture) {
  14900. this.emissiveTexture.dispose();
  14901. }
  14902. if (this.specularTexture) {
  14903. this.specularTexture.dispose();
  14904. }
  14905. if (this.bumpTexture) {
  14906. this.bumpTexture.dispose();
  14907. }
  14908. _super.prototype.dispose.call(this, forceDisposeEffect);
  14909. };
  14910. StandardMaterial.prototype.clone = function (name) {
  14911. var newStandardMaterial = new StandardMaterial(name, this.getScene());
  14912. // Base material
  14913. newStandardMaterial.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  14914. newStandardMaterial.alpha = this.alpha;
  14915. newStandardMaterial.fillMode = this.fillMode;
  14916. newStandardMaterial.backFaceCulling = this.backFaceCulling;
  14917. // Standard material
  14918. if (this.diffuseTexture && this.diffuseTexture.clone) {
  14919. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  14920. }
  14921. if (this.ambientTexture && this.ambientTexture.clone) {
  14922. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  14923. }
  14924. if (this.opacityTexture && this.opacityTexture.clone) {
  14925. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  14926. }
  14927. if (this.reflectionTexture && this.reflectionTexture.clone) {
  14928. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  14929. }
  14930. if (this.emissiveTexture && this.emissiveTexture.clone) {
  14931. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  14932. }
  14933. if (this.specularTexture && this.specularTexture.clone) {
  14934. newStandardMaterial.specularTexture = this.specularTexture.clone();
  14935. }
  14936. if (this.bumpTexture && this.bumpTexture.clone) {
  14937. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  14938. }
  14939. newStandardMaterial.ambientColor = this.ambientColor.clone();
  14940. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  14941. newStandardMaterial.specularColor = this.specularColor.clone();
  14942. newStandardMaterial.specularPower = this.specularPower;
  14943. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  14944. return newStandardMaterial;
  14945. };
  14946. // Statics
  14947. // Flags used to enable or disable a type of texture for all Standard Materials
  14948. StandardMaterial.DiffuseTextureEnabled = true;
  14949. StandardMaterial.AmbientTextureEnabled = true;
  14950. StandardMaterial.OpacityTextureEnabled = true;
  14951. StandardMaterial.ReflectionTextureEnabled = true;
  14952. StandardMaterial.EmissiveTextureEnabled = true;
  14953. StandardMaterial.SpecularTextureEnabled = true;
  14954. StandardMaterial.BumpTextureEnabled = true;
  14955. StandardMaterial.FresnelEnabled = true;
  14956. return StandardMaterial;
  14957. })(BABYLON.Material);
  14958. BABYLON.StandardMaterial = StandardMaterial;
  14959. })(BABYLON || (BABYLON = {}));
  14960. //# sourceMappingURL=babylon.standardMaterial.js.map
  14961. var BABYLON;
  14962. (function (BABYLON) {
  14963. var MultiMaterial = (function (_super) {
  14964. __extends(MultiMaterial, _super);
  14965. function MultiMaterial(name, scene) {
  14966. _super.call(this, name, scene, true);
  14967. this.subMaterials = new Array();
  14968. scene.multiMaterials.push(this);
  14969. }
  14970. // Properties
  14971. MultiMaterial.prototype.getSubMaterial = function (index) {
  14972. if (index < 0 || index >= this.subMaterials.length) {
  14973. return this.getScene().defaultMaterial;
  14974. }
  14975. return this.subMaterials[index];
  14976. };
  14977. // Methods
  14978. MultiMaterial.prototype.isReady = function (mesh) {
  14979. for (var index = 0; index < this.subMaterials.length; index++) {
  14980. var subMaterial = this.subMaterials[index];
  14981. if (subMaterial) {
  14982. if (!this.subMaterials[index].isReady(mesh)) {
  14983. return false;
  14984. }
  14985. }
  14986. }
  14987. return true;
  14988. };
  14989. return MultiMaterial;
  14990. })(BABYLON.Material);
  14991. BABYLON.MultiMaterial = MultiMaterial;
  14992. })(BABYLON || (BABYLON = {}));
  14993. //# sourceMappingURL=babylon.multiMaterial.js.mapvar BABYLON;
  14994. (function (BABYLON) {
  14995. var Database = (function () {
  14996. function Database(urlToScene, callbackManifestChecked) {
  14997. // Handling various flavors of prefixed version of IndexedDB
  14998. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  14999. this.callbackManifestChecked = callbackManifestChecked;
  15000. this.currentSceneUrl = BABYLON.Database.ReturnFullUrlLocation(urlToScene);
  15001. this.db = null;
  15002. this.enableSceneOffline = false;
  15003. this.enableTexturesOffline = false;
  15004. this.manifestVersionFound = 0;
  15005. this.mustUpdateRessources = false;
  15006. this.hasReachedQuota = false;
  15007. this.checkManifestFile();
  15008. }
  15009. Database.prototype.checkManifestFile = function () {
  15010. var _this = this;
  15011. function noManifestFile() {
  15012. //BABYLON.Tools.Log("Valid manifest file not found. Scene & textures will be loaded directly from the web server.");
  15013. that.enableSceneOffline = false;
  15014. that.enableTexturesOffline = false;
  15015. that.callbackManifestChecked(false);
  15016. }
  15017. var that = this;
  15018. var manifestURL = this.currentSceneUrl + ".manifest";
  15019. var xhr = new XMLHttpRequest();
  15020. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  15021. xhr.open("GET", manifestURLTimeStamped, true);
  15022. xhr.addEventListener("load", function () {
  15023. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  15024. try {
  15025. var manifestFile = JSON.parse(xhr.response);
  15026. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  15027. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  15028. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  15029. _this.manifestVersionFound = manifestFile.version;
  15030. }
  15031. if (_this.callbackManifestChecked) {
  15032. _this.callbackManifestChecked(true);
  15033. }
  15034. }
  15035. catch (ex) {
  15036. noManifestFile();
  15037. }
  15038. }
  15039. else {
  15040. noManifestFile();
  15041. }
  15042. }, false);
  15043. xhr.addEventListener("error", function (event) {
  15044. noManifestFile();
  15045. }, false);
  15046. try {
  15047. xhr.send();
  15048. }
  15049. catch (ex) {
  15050. BABYLON.Tools.Error("Error on XHR send request.");
  15051. that.callbackManifestChecked(false);
  15052. }
  15053. };
  15054. Database.prototype.openAsync = function (successCallback, errorCallback) {
  15055. var _this = this;
  15056. function handleError() {
  15057. that.isSupported = false;
  15058. if (errorCallback)
  15059. errorCallback();
  15060. }
  15061. var that = this;
  15062. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  15063. // Your browser doesn't support IndexedDB
  15064. this.isSupported = false;
  15065. if (errorCallback)
  15066. errorCallback();
  15067. }
  15068. else {
  15069. // If the DB hasn't been opened or created yet
  15070. if (!this.db) {
  15071. this.hasReachedQuota = false;
  15072. this.isSupported = true;
  15073. var request = this.idbFactory.open("babylonjs", 1);
  15074. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  15075. request.onerror = function (event) {
  15076. handleError();
  15077. };
  15078. // executes when a version change transaction cannot complete due to other active transactions
  15079. request.onblocked = function (event) {
  15080. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  15081. handleError();
  15082. };
  15083. // DB has been opened successfully
  15084. request.onsuccess = function (event) {
  15085. _this.db = request.result;
  15086. successCallback();
  15087. };
  15088. // Initialization of the DB. Creating Scenes & Textures stores
  15089. request.onupgradeneeded = function (event) {
  15090. _this.db = (event.target).result;
  15091. try {
  15092. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  15093. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  15094. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  15095. }
  15096. catch (ex) {
  15097. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  15098. handleError();
  15099. }
  15100. };
  15101. }
  15102. else {
  15103. if (successCallback)
  15104. successCallback();
  15105. }
  15106. }
  15107. };
  15108. Database.prototype.loadImageFromDB = function (url, image) {
  15109. var _this = this;
  15110. var completeURL = Database.ReturnFullUrlLocation(url);
  15111. var saveAndLoadImage = function () {
  15112. if (!_this.hasReachedQuota && _this.db !== null) {
  15113. // the texture is not yet in the DB, let's try to save it
  15114. _this._saveImageIntoDBAsync(completeURL, image);
  15115. }
  15116. else {
  15117. image.src = url;
  15118. }
  15119. };
  15120. if (!this.mustUpdateRessources) {
  15121. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  15122. }
  15123. else {
  15124. saveAndLoadImage();
  15125. }
  15126. };
  15127. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  15128. if (this.isSupported && this.db !== null) {
  15129. var texture;
  15130. var transaction = this.db.transaction(["textures"]);
  15131. transaction.onabort = function (event) {
  15132. image.src = url;
  15133. };
  15134. transaction.oncomplete = function (event) {
  15135. var blobTextureURL;
  15136. if (texture) {
  15137. var URL = window.URL || window.webkitURL;
  15138. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  15139. image.onerror = function () {
  15140. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  15141. image.src = url;
  15142. };
  15143. image.src = blobTextureURL;
  15144. }
  15145. else {
  15146. notInDBCallback();
  15147. }
  15148. };
  15149. var getRequest = transaction.objectStore("textures").get(url);
  15150. getRequest.onsuccess = function (event) {
  15151. texture = (event.target).result;
  15152. };
  15153. getRequest.onerror = function (event) {
  15154. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  15155. image.src = url;
  15156. };
  15157. }
  15158. else {
  15159. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  15160. image.src = url;
  15161. }
  15162. };
  15163. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  15164. var _this = this;
  15165. if (this.isSupported) {
  15166. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  15167. var generateBlobUrl = function () {
  15168. var blobTextureURL;
  15169. if (blob) {
  15170. var URL = window.URL || window.webkitURL;
  15171. try {
  15172. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  15173. }
  15174. catch (ex) {
  15175. blobTextureURL = URL.createObjectURL(blob);
  15176. }
  15177. }
  15178. image.src = blobTextureURL;
  15179. };
  15180. if (Database.isUASupportingBlobStorage) {
  15181. var xhr = new XMLHttpRequest(), blob;
  15182. xhr.open("GET", url, true);
  15183. xhr.responseType = "blob";
  15184. xhr.addEventListener("load", function () {
  15185. if (xhr.status === 200) {
  15186. // Blob as response (XHR2)
  15187. blob = xhr.response;
  15188. var transaction = _this.db.transaction(["textures"], "readwrite");
  15189. // the transaction could abort because of a QuotaExceededError error
  15190. transaction.onabort = function (event) {
  15191. try {
  15192. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  15193. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  15194. this.hasReachedQuota = true;
  15195. }
  15196. }
  15197. catch (ex) {
  15198. }
  15199. generateBlobUrl();
  15200. };
  15201. transaction.oncomplete = function (event) {
  15202. generateBlobUrl();
  15203. };
  15204. var newTexture = { textureUrl: url, data: blob };
  15205. try {
  15206. // Put the blob into the dabase
  15207. var addRequest = transaction.objectStore("textures").put(newTexture);
  15208. addRequest.onsuccess = function (event) {
  15209. };
  15210. addRequest.onerror = function (event) {
  15211. generateBlobUrl();
  15212. };
  15213. }
  15214. catch (ex) {
  15215. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  15216. if (ex.code === 25) {
  15217. Database.isUASupportingBlobStorage = false;
  15218. }
  15219. image.src = url;
  15220. }
  15221. }
  15222. else {
  15223. image.src = url;
  15224. }
  15225. }, false);
  15226. xhr.addEventListener("error", function (event) {
  15227. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  15228. image.src = url;
  15229. }, false);
  15230. xhr.send();
  15231. }
  15232. else {
  15233. image.src = url;
  15234. }
  15235. }
  15236. else {
  15237. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  15238. image.src = url;
  15239. }
  15240. };
  15241. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  15242. var _this = this;
  15243. var updateVersion = function (event) {
  15244. // the version is not yet in the DB or we need to update it
  15245. _this._saveVersionIntoDBAsync(url, versionLoaded);
  15246. };
  15247. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  15248. };
  15249. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  15250. var _this = this;
  15251. if (this.isSupported) {
  15252. var version;
  15253. try {
  15254. var transaction = this.db.transaction(["versions"]);
  15255. transaction.oncomplete = function (event) {
  15256. if (version) {
  15257. // If the version in the JSON file is > than the version in DB
  15258. if (_this.manifestVersionFound > version.data) {
  15259. _this.mustUpdateRessources = true;
  15260. updateInDBCallback();
  15261. }
  15262. else {
  15263. callback(version.data);
  15264. }
  15265. }
  15266. else {
  15267. _this.mustUpdateRessources = true;
  15268. updateInDBCallback();
  15269. }
  15270. };
  15271. transaction.onabort = function (event) {
  15272. callback(-1);
  15273. };
  15274. var getRequest = transaction.objectStore("versions").get(url);
  15275. getRequest.onsuccess = function (event) {
  15276. version = (event.target).result;
  15277. };
  15278. getRequest.onerror = function (event) {
  15279. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  15280. callback(-1);
  15281. };
  15282. }
  15283. catch (ex) {
  15284. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  15285. callback(-1);
  15286. }
  15287. }
  15288. else {
  15289. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  15290. callback(-1);
  15291. }
  15292. };
  15293. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  15294. var _this = this;
  15295. if (this.isSupported && !this.hasReachedQuota) {
  15296. try {
  15297. // Open a transaction to the database
  15298. var transaction = this.db.transaction(["versions"], "readwrite");
  15299. // the transaction could abort because of a QuotaExceededError error
  15300. transaction.onabort = function (event) {
  15301. try {
  15302. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  15303. _this.hasReachedQuota = true;
  15304. }
  15305. }
  15306. catch (ex) {
  15307. }
  15308. callback(-1);
  15309. };
  15310. transaction.oncomplete = function (event) {
  15311. callback(_this.manifestVersionFound);
  15312. };
  15313. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  15314. // Put the scene into the database
  15315. var addRequest = transaction.objectStore("versions").put(newVersion);
  15316. addRequest.onsuccess = function (event) {
  15317. };
  15318. addRequest.onerror = function (event) {
  15319. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  15320. };
  15321. }
  15322. catch (ex) {
  15323. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  15324. callback(-1);
  15325. }
  15326. }
  15327. else {
  15328. callback(-1);
  15329. }
  15330. };
  15331. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  15332. var _this = this;
  15333. var completeUrl = Database.ReturnFullUrlLocation(url);
  15334. var saveAndLoadFile = function (event) {
  15335. // the scene is not yet in the DB, let's try to save it
  15336. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  15337. };
  15338. this._checkVersionFromDB(completeUrl, function (version) {
  15339. if (version !== -1) {
  15340. if (!_this.mustUpdateRessources) {
  15341. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  15342. }
  15343. else {
  15344. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  15345. }
  15346. }
  15347. else {
  15348. errorCallback();
  15349. }
  15350. });
  15351. };
  15352. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  15353. if (this.isSupported) {
  15354. var targetStore;
  15355. if (url.indexOf(".babylon") !== -1) {
  15356. targetStore = "scenes";
  15357. }
  15358. else {
  15359. targetStore = "textures";
  15360. }
  15361. var file;
  15362. var transaction = this.db.transaction([targetStore]);
  15363. transaction.oncomplete = function (event) {
  15364. if (file) {
  15365. callback(file.data);
  15366. }
  15367. else {
  15368. notInDBCallback();
  15369. }
  15370. };
  15371. transaction.onabort = function (event) {
  15372. notInDBCallback();
  15373. };
  15374. var getRequest = transaction.objectStore(targetStore).get(url);
  15375. getRequest.onsuccess = function (event) {
  15376. file = (event.target).result;
  15377. };
  15378. getRequest.onerror = function (event) {
  15379. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  15380. notInDBCallback();
  15381. };
  15382. }
  15383. else {
  15384. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  15385. callback();
  15386. }
  15387. };
  15388. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  15389. var _this = this;
  15390. if (this.isSupported) {
  15391. var targetStore;
  15392. if (url.indexOf(".babylon") !== -1) {
  15393. targetStore = "scenes";
  15394. }
  15395. else {
  15396. targetStore = "textures";
  15397. }
  15398. // Create XHR
  15399. var xhr = new XMLHttpRequest(), fileData;
  15400. xhr.open("GET", url, true);
  15401. if (useArrayBuffer) {
  15402. xhr.responseType = "arraybuffer";
  15403. }
  15404. xhr.onprogress = progressCallback;
  15405. xhr.addEventListener("load", function () {
  15406. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  15407. // Blob as response (XHR2)
  15408. //fileData = xhr.responseText;
  15409. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  15410. if (!_this.hasReachedQuota) {
  15411. // Open a transaction to the database
  15412. var transaction = _this.db.transaction([targetStore], "readwrite");
  15413. // the transaction could abort because of a QuotaExceededError error
  15414. transaction.onabort = function (event) {
  15415. try {
  15416. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  15417. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  15418. this.hasReachedQuota = true;
  15419. }
  15420. }
  15421. catch (ex) {
  15422. }
  15423. callback(fileData);
  15424. };
  15425. transaction.oncomplete = function (event) {
  15426. callback(fileData);
  15427. };
  15428. var newFile;
  15429. if (targetStore === "scenes") {
  15430. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  15431. }
  15432. else {
  15433. newFile = { textureUrl: url, data: fileData };
  15434. }
  15435. try {
  15436. // Put the scene into the database
  15437. var addRequest = transaction.objectStore(targetStore).put(newFile);
  15438. addRequest.onsuccess = function (event) {
  15439. };
  15440. addRequest.onerror = function (event) {
  15441. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  15442. };
  15443. }
  15444. catch (ex) {
  15445. callback(fileData);
  15446. }
  15447. }
  15448. else {
  15449. callback(fileData);
  15450. }
  15451. }
  15452. else {
  15453. callback();
  15454. }
  15455. }, false);
  15456. xhr.addEventListener("error", function (event) {
  15457. BABYLON.Tools.Error("error on XHR request.");
  15458. callback();
  15459. }, false);
  15460. xhr.send();
  15461. }
  15462. else {
  15463. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  15464. callback();
  15465. }
  15466. };
  15467. Database.isUASupportingBlobStorage = true;
  15468. Database.parseURL = function (url) {
  15469. var a = document.createElement('a');
  15470. a.href = url;
  15471. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  15472. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  15473. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  15474. return absLocation;
  15475. };
  15476. Database.ReturnFullUrlLocation = function (url) {
  15477. if (url.indexOf("http:/") === -1) {
  15478. return (BABYLON.Database.parseURL(window.location.href) + url);
  15479. }
  15480. else {
  15481. return url;
  15482. }
  15483. };
  15484. return Database;
  15485. })();
  15486. BABYLON.Database = Database;
  15487. })(BABYLON || (BABYLON = {}));
  15488. //# sourceMappingURL=babylon.database.js.mapvar BABYLON;
  15489. (function (BABYLON) {
  15490. var SpriteManager = (function () {
  15491. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  15492. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  15493. this.name = name;
  15494. this.cellSize = cellSize;
  15495. this.sprites = new Array();
  15496. this.renderingGroupId = 0;
  15497. this.fogEnabled = true;
  15498. this._vertexDeclaration = [4, 4, 4, 4];
  15499. this._vertexStrideSize = 16 * 4; // 15 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  15500. this._capacity = capacity;
  15501. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  15502. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  15503. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  15504. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  15505. this._scene = scene;
  15506. this._scene.spriteManagers.push(this);
  15507. // VBO
  15508. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  15509. var indices = [];
  15510. var index = 0;
  15511. for (var count = 0; count < capacity; count++) {
  15512. indices.push(index);
  15513. indices.push(index + 1);
  15514. indices.push(index + 2);
  15515. indices.push(index);
  15516. indices.push(index + 2);
  15517. indices.push(index + 3);
  15518. index += 4;
  15519. }
  15520. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  15521. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  15522. // Effects
  15523. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  15524. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  15525. }
  15526. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  15527. var arrayOffset = index * 16;
  15528. if (offsetX === 0)
  15529. offsetX = this._epsilon;
  15530. else if (offsetX === 1)
  15531. offsetX = 1 - this._epsilon;
  15532. if (offsetY === 0)
  15533. offsetY = this._epsilon;
  15534. else if (offsetY === 1)
  15535. offsetY = 1 - this._epsilon;
  15536. this._vertices[arrayOffset] = sprite.position.x;
  15537. this._vertices[arrayOffset + 1] = sprite.position.y;
  15538. this._vertices[arrayOffset + 2] = sprite.position.z;
  15539. this._vertices[arrayOffset + 3] = sprite.angle;
  15540. this._vertices[arrayOffset + 4] = sprite.width;
  15541. this._vertices[arrayOffset + 5] = sprite.height;
  15542. this._vertices[arrayOffset + 6] = offsetX;
  15543. this._vertices[arrayOffset + 7] = offsetY;
  15544. this._vertices[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  15545. this._vertices[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  15546. var offset = (sprite.cellIndex / rowSize) >> 0;
  15547. this._vertices[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  15548. this._vertices[arrayOffset + 11] = offset;
  15549. // Color
  15550. this._vertices[arrayOffset + 12] = sprite.color.r;
  15551. this._vertices[arrayOffset + 13] = sprite.color.g;
  15552. this._vertices[arrayOffset + 14] = sprite.color.b;
  15553. this._vertices[arrayOffset + 15] = sprite.color.a;
  15554. };
  15555. SpriteManager.prototype.render = function () {
  15556. // Check
  15557. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  15558. return;
  15559. var engine = this._scene.getEngine();
  15560. var baseSize = this._spriteTexture.getBaseSize();
  15561. // Sprites
  15562. var deltaTime = engine.getDeltaTime();
  15563. var max = Math.min(this._capacity, this.sprites.length);
  15564. var rowSize = baseSize.width / this.cellSize;
  15565. var offset = 0;
  15566. for (var index = 0; index < max; index++) {
  15567. var sprite = this.sprites[index];
  15568. if (!sprite) {
  15569. continue;
  15570. }
  15571. sprite._animate(deltaTime);
  15572. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  15573. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  15574. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  15575. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  15576. }
  15577. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  15578. // Render
  15579. var effect = this._effectBase;
  15580. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  15581. effect = this._effectFog;
  15582. }
  15583. engine.enableEffect(effect);
  15584. var viewMatrix = this._scene.getViewMatrix();
  15585. effect.setTexture("diffuseSampler", this._spriteTexture);
  15586. effect.setMatrix("view", viewMatrix);
  15587. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  15588. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  15589. // Fog
  15590. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  15591. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  15592. effect.setColor3("vFogColor", this._scene.fogColor);
  15593. }
  15594. // VBOs
  15595. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  15596. // Draw order
  15597. effect.setBool("alphaTest", true);
  15598. engine.setColorWrite(false);
  15599. engine.draw(true, 0, max * 6);
  15600. engine.setColorWrite(true);
  15601. effect.setBool("alphaTest", false);
  15602. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  15603. engine.draw(true, 0, max * 6);
  15604. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  15605. };
  15606. SpriteManager.prototype.dispose = function () {
  15607. if (this._vertexBuffer) {
  15608. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  15609. this._vertexBuffer = null;
  15610. }
  15611. if (this._indexBuffer) {
  15612. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  15613. this._indexBuffer = null;
  15614. }
  15615. if (this._spriteTexture) {
  15616. this._spriteTexture.dispose();
  15617. this._spriteTexture = null;
  15618. }
  15619. // Remove from scene
  15620. var index = this._scene.spriteManagers.indexOf(this);
  15621. this._scene.spriteManagers.splice(index, 1);
  15622. // Callback
  15623. if (this.onDispose) {
  15624. this.onDispose();
  15625. }
  15626. };
  15627. return SpriteManager;
  15628. })();
  15629. BABYLON.SpriteManager = SpriteManager;
  15630. })(BABYLON || (BABYLON = {}));
  15631. //# sourceMappingURL=babylon.spriteManager.js.mapvar BABYLON;
  15632. (function (BABYLON) {
  15633. var Sprite = (function () {
  15634. function Sprite(name, manager) {
  15635. this.name = name;
  15636. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  15637. this.width = 1.0;
  15638. this.height = 1.0;
  15639. this.angle = 0;
  15640. this.cellIndex = 0;
  15641. this.invertU = 0;
  15642. this.invertV = 0;
  15643. this.animations = new Array();
  15644. this._animationStarted = false;
  15645. this._loopAnimation = false;
  15646. this._fromIndex = 0;
  15647. this._toIndex = 0;
  15648. this._delay = 0;
  15649. this._direction = 1;
  15650. this._frameCount = 0;
  15651. this._time = 0;
  15652. this._manager = manager;
  15653. this._manager.sprites.push(this);
  15654. this.position = BABYLON.Vector3.Zero();
  15655. }
  15656. Object.defineProperty(Sprite.prototype, "size", {
  15657. get: function () {
  15658. return this.width;
  15659. },
  15660. set: function (value) {
  15661. this.width = value;
  15662. this.height = value;
  15663. },
  15664. enumerable: true,
  15665. configurable: true
  15666. });
  15667. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  15668. this._fromIndex = from;
  15669. this._toIndex = to;
  15670. this._loopAnimation = loop;
  15671. this._delay = delay;
  15672. this._animationStarted = true;
  15673. this._direction = from < to ? 1 : -1;
  15674. this.cellIndex = from;
  15675. this._time = 0;
  15676. };
  15677. Sprite.prototype.stopAnimation = function () {
  15678. this._animationStarted = false;
  15679. };
  15680. Sprite.prototype._animate = function (deltaTime) {
  15681. if (!this._animationStarted)
  15682. return;
  15683. this._time += deltaTime;
  15684. if (this._time > this._delay) {
  15685. this._time = this._time % this._delay;
  15686. this.cellIndex += this._direction;
  15687. if (this.cellIndex == this._toIndex) {
  15688. if (this._loopAnimation) {
  15689. this.cellIndex = this._fromIndex;
  15690. }
  15691. else {
  15692. this._animationStarted = false;
  15693. if (this.disposeWhenFinishedAnimating) {
  15694. this.dispose();
  15695. }
  15696. }
  15697. }
  15698. }
  15699. };
  15700. Sprite.prototype.dispose = function () {
  15701. for (var i = 0; i < this._manager.sprites.length; i++) {
  15702. if (this._manager.sprites[i] == this) {
  15703. this._manager.sprites.splice(i, 1);
  15704. }
  15705. }
  15706. };
  15707. return Sprite;
  15708. })();
  15709. BABYLON.Sprite = Sprite;
  15710. })(BABYLON || (BABYLON = {}));
  15711. //# sourceMappingURL=babylon.sprite.js.mapvar BABYLON;
  15712. (function (BABYLON) {
  15713. var Layer = (function () {
  15714. function Layer(name, imgUrl, scene, isBackground, color) {
  15715. this.name = name;
  15716. this._vertexDeclaration = [2];
  15717. this._vertexStrideSize = 2 * 4;
  15718. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  15719. this.isBackground = isBackground === undefined ? true : isBackground;
  15720. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  15721. this._scene = scene;
  15722. this._scene.layers.push(this);
  15723. // VBO
  15724. var vertices = [];
  15725. vertices.push(1, 1);
  15726. vertices.push(-1, 1);
  15727. vertices.push(-1, -1);
  15728. vertices.push(1, -1);
  15729. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  15730. // Indices
  15731. var indices = [];
  15732. indices.push(0);
  15733. indices.push(1);
  15734. indices.push(2);
  15735. indices.push(0);
  15736. indices.push(2);
  15737. indices.push(3);
  15738. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  15739. // Effects
  15740. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  15741. }
  15742. Layer.prototype.render = function () {
  15743. // Check
  15744. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  15745. return;
  15746. var engine = this._scene.getEngine();
  15747. // Render
  15748. engine.enableEffect(this._effect);
  15749. engine.setState(false);
  15750. // Texture
  15751. this._effect.setTexture("textureSampler", this.texture);
  15752. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  15753. // Color
  15754. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  15755. // VBOs
  15756. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  15757. // Draw order
  15758. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  15759. engine.draw(true, 0, 6);
  15760. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  15761. };
  15762. Layer.prototype.dispose = function () {
  15763. if (this._vertexBuffer) {
  15764. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  15765. this._vertexBuffer = null;
  15766. }
  15767. if (this._indexBuffer) {
  15768. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  15769. this._indexBuffer = null;
  15770. }
  15771. if (this.texture) {
  15772. this.texture.dispose();
  15773. this.texture = null;
  15774. }
  15775. // Remove from scene
  15776. var index = this._scene.layers.indexOf(this);
  15777. this._scene.layers.splice(index, 1);
  15778. // Callback
  15779. if (this.onDispose) {
  15780. this.onDispose();
  15781. }
  15782. };
  15783. return Layer;
  15784. })();
  15785. BABYLON.Layer = Layer;
  15786. })(BABYLON || (BABYLON = {}));
  15787. //# sourceMappingURL=babylon.layer.js.mapvar BABYLON;
  15788. (function (BABYLON) {
  15789. var Particle = (function () {
  15790. function Particle() {
  15791. this.position = BABYLON.Vector3.Zero();
  15792. this.direction = BABYLON.Vector3.Zero();
  15793. this.color = new BABYLON.Color4(0, 0, 0, 0);
  15794. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  15795. this.lifeTime = 1.0;
  15796. this.age = 0;
  15797. this.size = 0;
  15798. this.angle = 0;
  15799. this.angularSpeed = 0;
  15800. }
  15801. Particle.prototype.copyTo = function (other) {
  15802. other.position.copyFrom(this.position);
  15803. other.direction.copyFrom(this.direction);
  15804. other.color.copyFrom(this.color);
  15805. other.colorStep.copyFrom(this.colorStep);
  15806. other.lifeTime = this.lifeTime;
  15807. other.age = this.age;
  15808. other.size = this.size;
  15809. other.angle = this.angle;
  15810. other.angularSpeed = this.angularSpeed;
  15811. };
  15812. return Particle;
  15813. })();
  15814. BABYLON.Particle = Particle;
  15815. })(BABYLON || (BABYLON = {}));
  15816. //# sourceMappingURL=babylon.particle.js.mapvar BABYLON;
  15817. (function (BABYLON) {
  15818. var randomNumber = function (min, max) {
  15819. if (min === max) {
  15820. return (min);
  15821. }
  15822. var random = Math.random();
  15823. return ((random * (max - min)) + min);
  15824. };
  15825. var ParticleSystem = (function () {
  15826. function ParticleSystem(name, capacity, scene, customEffect) {
  15827. var _this = this;
  15828. this.name = name;
  15829. this.renderingGroupId = 0;
  15830. this.emitter = null;
  15831. this.emitRate = 10;
  15832. this.manualEmitCount = -1;
  15833. this.updateSpeed = 0.01;
  15834. this.targetStopDuration = 0;
  15835. this.disposeOnStop = false;
  15836. this.minEmitPower = 1;
  15837. this.maxEmitPower = 1;
  15838. this.minLifeTime = 1;
  15839. this.maxLifeTime = 1;
  15840. this.minSize = 1;
  15841. this.maxSize = 1;
  15842. this.minAngularSpeed = 0;
  15843. this.maxAngularSpeed = 0;
  15844. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  15845. this.forceDepthWrite = false;
  15846. this.gravity = BABYLON.Vector3.Zero();
  15847. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  15848. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  15849. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  15850. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  15851. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  15852. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  15853. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  15854. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  15855. this.particles = new Array();
  15856. this._vertexDeclaration = [3, 4, 4];
  15857. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  15858. this._stockParticles = new Array();
  15859. this._newPartsExcess = 0;
  15860. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  15861. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  15862. this._scaledDirection = BABYLON.Vector3.Zero();
  15863. this._scaledGravity = BABYLON.Vector3.Zero();
  15864. this._currentRenderId = -1;
  15865. this._started = false;
  15866. this._stopped = false;
  15867. this._actualFrame = 0;
  15868. this.id = name;
  15869. this._capacity = capacity;
  15870. this._scene = scene;
  15871. this._customEffect = customEffect;
  15872. scene.particleSystems.push(this);
  15873. // VBO
  15874. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  15875. var indices = [];
  15876. var index = 0;
  15877. for (var count = 0; count < capacity; count++) {
  15878. indices.push(index);
  15879. indices.push(index + 1);
  15880. indices.push(index + 2);
  15881. indices.push(index);
  15882. indices.push(index + 2);
  15883. indices.push(index + 3);
  15884. index += 4;
  15885. }
  15886. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  15887. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  15888. // Default behaviors
  15889. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate) {
  15890. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  15891. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  15892. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  15893. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  15894. };
  15895. this.startPositionFunction = function (worldMatrix, positionToUpdate) {
  15896. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  15897. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  15898. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  15899. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  15900. };
  15901. this.updateFunction = function (particles) {
  15902. for (var index = 0; index < particles.length; index++) {
  15903. var particle = particles[index];
  15904. particle.age += _this._scaledUpdateSpeed;
  15905. if (particle.age >= particle.lifeTime) {
  15906. _this.recycleParticle(particle);
  15907. index--;
  15908. continue;
  15909. }
  15910. else {
  15911. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  15912. particle.color.addInPlace(_this._scaledColorStep);
  15913. if (particle.color.a < 0)
  15914. particle.color.a = 0;
  15915. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  15916. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  15917. particle.position.addInPlace(_this._scaledDirection);
  15918. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  15919. particle.direction.addInPlace(_this._scaledGravity);
  15920. }
  15921. }
  15922. };
  15923. }
  15924. ParticleSystem.prototype.recycleParticle = function (particle) {
  15925. var lastParticle = this.particles.pop();
  15926. if (lastParticle !== particle) {
  15927. lastParticle.copyTo(particle);
  15928. this._stockParticles.push(lastParticle);
  15929. }
  15930. };
  15931. ParticleSystem.prototype.getCapacity = function () {
  15932. return this._capacity;
  15933. };
  15934. ParticleSystem.prototype.isAlive = function () {
  15935. return this._alive;
  15936. };
  15937. ParticleSystem.prototype.isStarted = function () {
  15938. return this._started;
  15939. };
  15940. ParticleSystem.prototype.start = function () {
  15941. this._started = true;
  15942. this._stopped = false;
  15943. this._actualFrame = 0;
  15944. };
  15945. ParticleSystem.prototype.stop = function () {
  15946. this._stopped = true;
  15947. };
  15948. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  15949. var offset = index * 11;
  15950. this._vertices[offset] = particle.position.x;
  15951. this._vertices[offset + 1] = particle.position.y;
  15952. this._vertices[offset + 2] = particle.position.z;
  15953. this._vertices[offset + 3] = particle.color.r;
  15954. this._vertices[offset + 4] = particle.color.g;
  15955. this._vertices[offset + 5] = particle.color.b;
  15956. this._vertices[offset + 6] = particle.color.a;
  15957. this._vertices[offset + 7] = particle.angle;
  15958. this._vertices[offset + 8] = particle.size;
  15959. this._vertices[offset + 9] = offsetX;
  15960. this._vertices[offset + 10] = offsetY;
  15961. };
  15962. ParticleSystem.prototype._update = function (newParticles) {
  15963. // Update current
  15964. this._alive = this.particles.length > 0;
  15965. this.updateFunction(this.particles);
  15966. // Add new ones
  15967. var worldMatrix;
  15968. if (this.emitter.position) {
  15969. worldMatrix = this.emitter.getWorldMatrix();
  15970. }
  15971. else {
  15972. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  15973. }
  15974. for (var index = 0; index < newParticles; index++) {
  15975. if (this.particles.length === this._capacity) {
  15976. break;
  15977. }
  15978. if (this._stockParticles.length !== 0) {
  15979. var particle = this._stockParticles.pop();
  15980. particle.age = 0;
  15981. }
  15982. else {
  15983. particle = new BABYLON.Particle();
  15984. }
  15985. this.particles.push(particle);
  15986. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  15987. this.startDirectionFunction(emitPower, worldMatrix, particle.direction);
  15988. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  15989. particle.size = randomNumber(this.minSize, this.maxSize);
  15990. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  15991. this.startPositionFunction(worldMatrix, particle.position);
  15992. var step = randomNumber(0, 1.0);
  15993. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  15994. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  15995. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  15996. }
  15997. };
  15998. ParticleSystem.prototype._getEffect = function () {
  15999. if (this._customEffect) {
  16000. return this._customEffect;
  16001. }
  16002. ;
  16003. var defines = [];
  16004. if (this._scene.clipPlane) {
  16005. defines.push("#define CLIPPLANE");
  16006. }
  16007. // Effect
  16008. var join = defines.join("\n");
  16009. if (this._cachedDefines !== join) {
  16010. this._cachedDefines = join;
  16011. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  16012. }
  16013. return this._effect;
  16014. };
  16015. ParticleSystem.prototype.animate = function () {
  16016. if (!this._started)
  16017. return;
  16018. var effect = this._getEffect();
  16019. // Check
  16020. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  16021. return;
  16022. if (this._currentRenderId === this._scene.getRenderId()) {
  16023. return;
  16024. }
  16025. this._currentRenderId = this._scene.getRenderId();
  16026. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  16027. // determine the number of particles we need to create
  16028. var emitCout;
  16029. if (this.manualEmitCount > -1) {
  16030. emitCout = this.manualEmitCount;
  16031. this.manualEmitCount = 0;
  16032. }
  16033. else {
  16034. emitCout = this.emitRate;
  16035. }
  16036. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  16037. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  16038. if (this._newPartsExcess > 1.0) {
  16039. newParticles += this._newPartsExcess >> 0;
  16040. this._newPartsExcess -= this._newPartsExcess >> 0;
  16041. }
  16042. this._alive = false;
  16043. if (!this._stopped) {
  16044. this._actualFrame += this._scaledUpdateSpeed;
  16045. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  16046. this.stop();
  16047. }
  16048. else {
  16049. newParticles = 0;
  16050. }
  16051. this._update(newParticles);
  16052. // Stopped?
  16053. if (this._stopped) {
  16054. if (!this._alive) {
  16055. this._started = false;
  16056. if (this.disposeOnStop) {
  16057. this._scene._toBeDisposed.push(this);
  16058. }
  16059. }
  16060. }
  16061. // Update VBO
  16062. var offset = 0;
  16063. for (var index = 0; index < this.particles.length; index++) {
  16064. var particle = this.particles[index];
  16065. this._appendParticleVertex(offset++, particle, 0, 0);
  16066. this._appendParticleVertex(offset++, particle, 1, 0);
  16067. this._appendParticleVertex(offset++, particle, 1, 1);
  16068. this._appendParticleVertex(offset++, particle, 0, 1);
  16069. }
  16070. var engine = this._scene.getEngine();
  16071. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  16072. };
  16073. ParticleSystem.prototype.render = function () {
  16074. var effect = this._getEffect();
  16075. // Check
  16076. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  16077. return 0;
  16078. var engine = this._scene.getEngine();
  16079. // Render
  16080. engine.enableEffect(effect);
  16081. engine.setState(false);
  16082. var viewMatrix = this._scene.getViewMatrix();
  16083. effect.setTexture("diffuseSampler", this.particleTexture);
  16084. effect.setMatrix("view", viewMatrix);
  16085. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  16086. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  16087. if (this._scene.clipPlane) {
  16088. var clipPlane = this._scene.clipPlane;
  16089. var invView = viewMatrix.clone();
  16090. invView.invert();
  16091. effect.setMatrix("invView", invView);
  16092. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  16093. }
  16094. // VBOs
  16095. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  16096. // Draw order
  16097. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  16098. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  16099. }
  16100. else {
  16101. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  16102. }
  16103. if (this.forceDepthWrite) {
  16104. engine.setDepthWrite(true);
  16105. }
  16106. engine.draw(true, 0, this.particles.length * 6);
  16107. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16108. return this.particles.length;
  16109. };
  16110. ParticleSystem.prototype.dispose = function () {
  16111. if (this._vertexBuffer) {
  16112. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  16113. this._vertexBuffer = null;
  16114. }
  16115. if (this._indexBuffer) {
  16116. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  16117. this._indexBuffer = null;
  16118. }
  16119. if (this.particleTexture) {
  16120. this.particleTexture.dispose();
  16121. this.particleTexture = null;
  16122. }
  16123. // Remove from scene
  16124. var index = this._scene.particleSystems.indexOf(this);
  16125. this._scene.particleSystems.splice(index, 1);
  16126. // Callback
  16127. if (this.onDispose) {
  16128. this.onDispose();
  16129. }
  16130. };
  16131. // Clone
  16132. ParticleSystem.prototype.clone = function (name, newEmitter) {
  16133. var result = new ParticleSystem(name, this._capacity, this._scene);
  16134. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  16135. if (newEmitter === undefined) {
  16136. newEmitter = this.emitter;
  16137. }
  16138. result.emitter = newEmitter;
  16139. if (this.particleTexture) {
  16140. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  16141. }
  16142. result.start();
  16143. return result;
  16144. };
  16145. // Statics
  16146. ParticleSystem.BLENDMODE_ONEONE = 0;
  16147. ParticleSystem.BLENDMODE_STANDARD = 1;
  16148. return ParticleSystem;
  16149. })();
  16150. BABYLON.ParticleSystem = ParticleSystem;
  16151. })(BABYLON || (BABYLON = {}));
  16152. //# sourceMappingURL=babylon.particleSystem.js.mapvar BABYLON;
  16153. (function (BABYLON) {
  16154. var Animation = (function () {
  16155. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  16156. this.name = name;
  16157. this.targetProperty = targetProperty;
  16158. this.framePerSecond = framePerSecond;
  16159. this.dataType = dataType;
  16160. this.loopMode = loopMode;
  16161. this._offsetsCache = {};
  16162. this._highLimitsCache = {};
  16163. this._stopped = false;
  16164. this.targetPropertyPath = targetProperty.split(".");
  16165. this.dataType = dataType;
  16166. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  16167. }
  16168. Animation.CreateAndStartAnimation = function (name, mesh, tartgetProperty, framePerSecond, totalFrame, from, to, loopMode) {
  16169. var dataType = undefined;
  16170. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  16171. dataType = Animation.ANIMATIONTYPE_FLOAT;
  16172. }
  16173. else if (from instanceof BABYLON.Quaternion) {
  16174. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  16175. }
  16176. else if (from instanceof BABYLON.Vector3) {
  16177. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  16178. }
  16179. else if (from instanceof BABYLON.Vector2) {
  16180. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  16181. }
  16182. else if (from instanceof BABYLON.Color3) {
  16183. dataType = Animation.ANIMATIONTYPE_COLOR3;
  16184. }
  16185. if (dataType == undefined) {
  16186. return null;
  16187. }
  16188. var animation = new Animation(name, tartgetProperty, framePerSecond, dataType, loopMode);
  16189. var keys = [];
  16190. keys.push({ frame: 0, value: from });
  16191. keys.push({ frame: totalFrame, value: to });
  16192. animation.setKeys(keys);
  16193. mesh.animations.push(animation);
  16194. return mesh.getScene().beginAnimation(mesh, 0, totalFrame, (animation.loopMode === 1));
  16195. };
  16196. // Methods
  16197. Animation.prototype.isStopped = function () {
  16198. return this._stopped;
  16199. };
  16200. Animation.prototype.getKeys = function () {
  16201. return this._keys;
  16202. };
  16203. Animation.prototype.getEasingFunction = function () {
  16204. return this._easingFunction;
  16205. };
  16206. Animation.prototype.setEasingFunction = function (easingFunction) {
  16207. this._easingFunction = easingFunction;
  16208. };
  16209. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  16210. return startValue + (endValue - startValue) * gradient;
  16211. };
  16212. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  16213. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  16214. };
  16215. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  16216. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  16217. };
  16218. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  16219. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  16220. };
  16221. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  16222. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  16223. };
  16224. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  16225. var startScale = new BABYLON.Vector3(0, 0, 0);
  16226. var startRotation = new BABYLON.Quaternion();
  16227. var startTranslation = new BABYLON.Vector3(0, 0, 0);
  16228. startValue.decompose(startScale, startRotation, startTranslation);
  16229. var endScale = new BABYLON.Vector3(0, 0, 0);
  16230. var endRotation = new BABYLON.Quaternion();
  16231. var endTranslation = new BABYLON.Vector3(0, 0, 0);
  16232. endValue.decompose(endScale, endRotation, endTranslation);
  16233. var resultScale = this.vector3InterpolateFunction(startScale, endScale, gradient);
  16234. var resultRotation = this.quaternionInterpolateFunction(startRotation, endRotation, gradient);
  16235. var resultTranslation = this.vector3InterpolateFunction(startTranslation, endTranslation, gradient);
  16236. var result = BABYLON.Matrix.Compose(resultScale, resultRotation, resultTranslation);
  16237. return result;
  16238. };
  16239. Animation.prototype.clone = function () {
  16240. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  16241. clone.setKeys(this._keys);
  16242. return clone;
  16243. };
  16244. Animation.prototype.setKeys = function (values) {
  16245. this._keys = values.slice(0);
  16246. this._offsetsCache = {};
  16247. this._highLimitsCache = {};
  16248. };
  16249. Animation.prototype._getKeyValue = function (value) {
  16250. if (typeof value === "function") {
  16251. return value();
  16252. }
  16253. return value;
  16254. };
  16255. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  16256. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  16257. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  16258. }
  16259. this.currentFrame = currentFrame;
  16260. // Try to get a hash to find the right key
  16261. var startKey = Math.max(0, Math.min(this._keys.length - 1, Math.floor(this._keys.length * (currentFrame - this._keys[0].frame) / (this._keys[this._keys.length - 1].frame - this._keys[0].frame)) - 1));
  16262. if (this._keys[startKey].frame >= currentFrame) {
  16263. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  16264. startKey--;
  16265. }
  16266. }
  16267. for (var key = startKey; key < this._keys.length; key++) {
  16268. if (this._keys[key + 1].frame >= currentFrame) {
  16269. var startValue = this._getKeyValue(this._keys[key].value);
  16270. var endValue = this._getKeyValue(this._keys[key + 1].value);
  16271. // gradient : percent of currentFrame between the frame inf and the frame sup
  16272. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  16273. // check for easingFunction and correction of gradient
  16274. if (this._easingFunction != null) {
  16275. gradient = this._easingFunction.ease(gradient);
  16276. }
  16277. switch (this.dataType) {
  16278. case Animation.ANIMATIONTYPE_FLOAT:
  16279. switch (loopMode) {
  16280. case Animation.ANIMATIONLOOPMODE_CYCLE:
  16281. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  16282. return this.floatInterpolateFunction(startValue, endValue, gradient);
  16283. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  16284. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  16285. }
  16286. break;
  16287. case Animation.ANIMATIONTYPE_QUATERNION:
  16288. var quaternion = null;
  16289. switch (loopMode) {
  16290. case Animation.ANIMATIONLOOPMODE_CYCLE:
  16291. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  16292. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  16293. break;
  16294. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  16295. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  16296. break;
  16297. }
  16298. return quaternion;
  16299. case Animation.ANIMATIONTYPE_VECTOR3:
  16300. switch (loopMode) {
  16301. case Animation.ANIMATIONLOOPMODE_CYCLE:
  16302. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  16303. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  16304. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  16305. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  16306. }
  16307. case Animation.ANIMATIONTYPE_VECTOR2:
  16308. switch (loopMode) {
  16309. case Animation.ANIMATIONLOOPMODE_CYCLE:
  16310. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  16311. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  16312. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  16313. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  16314. }
  16315. case Animation.ANIMATIONTYPE_COLOR3:
  16316. switch (loopMode) {
  16317. case Animation.ANIMATIONLOOPMODE_CYCLE:
  16318. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  16319. return this.color3InterpolateFunction(startValue, endValue, gradient);
  16320. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  16321. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  16322. }
  16323. case Animation.ANIMATIONTYPE_MATRIX:
  16324. switch (loopMode) {
  16325. case Animation.ANIMATIONLOOPMODE_CYCLE:
  16326. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  16327. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  16328. return startValue;
  16329. }
  16330. default:
  16331. break;
  16332. }
  16333. break;
  16334. }
  16335. }
  16336. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  16337. };
  16338. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  16339. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  16340. this._stopped = true;
  16341. return false;
  16342. }
  16343. var returnValue = true;
  16344. // Adding a start key at frame 0 if missing
  16345. if (this._keys[0].frame !== 0) {
  16346. var newKey = { frame: 0, value: this._keys[0].value };
  16347. this._keys.splice(0, 0, newKey);
  16348. }
  16349. // Check limits
  16350. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  16351. from = this._keys[0].frame;
  16352. }
  16353. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  16354. to = this._keys[this._keys.length - 1].frame;
  16355. }
  16356. // Compute ratio
  16357. var range = to - from;
  16358. var offsetValue;
  16359. // ratio represents the frame delta between from and to
  16360. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  16361. var highLimitValue = 0;
  16362. if (ratio > range && !loop) {
  16363. returnValue = false;
  16364. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  16365. }
  16366. else {
  16367. // Get max value if required
  16368. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  16369. var keyOffset = to.toString() + from.toString();
  16370. if (!this._offsetsCache[keyOffset]) {
  16371. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  16372. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  16373. switch (this.dataType) {
  16374. case Animation.ANIMATIONTYPE_FLOAT:
  16375. this._offsetsCache[keyOffset] = toValue - fromValue;
  16376. break;
  16377. case Animation.ANIMATIONTYPE_QUATERNION:
  16378. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  16379. break;
  16380. case Animation.ANIMATIONTYPE_VECTOR3:
  16381. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  16382. case Animation.ANIMATIONTYPE_VECTOR2:
  16383. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  16384. case Animation.ANIMATIONTYPE_COLOR3:
  16385. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  16386. default:
  16387. break;
  16388. }
  16389. this._highLimitsCache[keyOffset] = toValue;
  16390. }
  16391. highLimitValue = this._highLimitsCache[keyOffset];
  16392. offsetValue = this._offsetsCache[keyOffset];
  16393. }
  16394. }
  16395. if (offsetValue === undefined) {
  16396. switch (this.dataType) {
  16397. case Animation.ANIMATIONTYPE_FLOAT:
  16398. offsetValue = 0;
  16399. break;
  16400. case Animation.ANIMATIONTYPE_QUATERNION:
  16401. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  16402. break;
  16403. case Animation.ANIMATIONTYPE_VECTOR3:
  16404. offsetValue = BABYLON.Vector3.Zero();
  16405. break;
  16406. case Animation.ANIMATIONTYPE_VECTOR2:
  16407. offsetValue = BABYLON.Vector2.Zero();
  16408. break;
  16409. case Animation.ANIMATIONTYPE_COLOR3:
  16410. offsetValue = BABYLON.Color3.Black();
  16411. }
  16412. }
  16413. // Compute value
  16414. var repeatCount = (ratio / range) >> 0;
  16415. var currentFrame = returnValue ? from + ratio % range : to;
  16416. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  16417. // Set value
  16418. if (this.targetPropertyPath.length > 1) {
  16419. var property = this._target[this.targetPropertyPath[0]];
  16420. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  16421. property = property[this.targetPropertyPath[index]];
  16422. }
  16423. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  16424. }
  16425. else {
  16426. this._target[this.targetPropertyPath[0]] = currentValue;
  16427. }
  16428. if (this._target.markAsDirty) {
  16429. this._target.markAsDirty(this.targetProperty);
  16430. }
  16431. if (!returnValue) {
  16432. this._stopped = true;
  16433. }
  16434. return returnValue;
  16435. };
  16436. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  16437. get: function () {
  16438. return Animation._ANIMATIONTYPE_FLOAT;
  16439. },
  16440. enumerable: true,
  16441. configurable: true
  16442. });
  16443. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  16444. get: function () {
  16445. return Animation._ANIMATIONTYPE_VECTOR3;
  16446. },
  16447. enumerable: true,
  16448. configurable: true
  16449. });
  16450. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  16451. get: function () {
  16452. return Animation._ANIMATIONTYPE_VECTOR2;
  16453. },
  16454. enumerable: true,
  16455. configurable: true
  16456. });
  16457. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  16458. get: function () {
  16459. return Animation._ANIMATIONTYPE_QUATERNION;
  16460. },
  16461. enumerable: true,
  16462. configurable: true
  16463. });
  16464. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  16465. get: function () {
  16466. return Animation._ANIMATIONTYPE_MATRIX;
  16467. },
  16468. enumerable: true,
  16469. configurable: true
  16470. });
  16471. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  16472. get: function () {
  16473. return Animation._ANIMATIONTYPE_COLOR3;
  16474. },
  16475. enumerable: true,
  16476. configurable: true
  16477. });
  16478. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  16479. get: function () {
  16480. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  16481. },
  16482. enumerable: true,
  16483. configurable: true
  16484. });
  16485. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  16486. get: function () {
  16487. return Animation._ANIMATIONLOOPMODE_CYCLE;
  16488. },
  16489. enumerable: true,
  16490. configurable: true
  16491. });
  16492. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  16493. get: function () {
  16494. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  16495. },
  16496. enumerable: true,
  16497. configurable: true
  16498. });
  16499. // Statics
  16500. Animation._ANIMATIONTYPE_FLOAT = 0;
  16501. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  16502. Animation._ANIMATIONTYPE_QUATERNION = 2;
  16503. Animation._ANIMATIONTYPE_MATRIX = 3;
  16504. Animation._ANIMATIONTYPE_COLOR3 = 4;
  16505. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  16506. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  16507. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  16508. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  16509. return Animation;
  16510. })();
  16511. BABYLON.Animation = Animation;
  16512. })(BABYLON || (BABYLON = {}));
  16513. //# sourceMappingURL=babylon.animation.js.mapvar BABYLON;
  16514. (function (BABYLON) {
  16515. var Animatable = (function () {
  16516. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  16517. if (fromFrame === void 0) { fromFrame = 0; }
  16518. if (toFrame === void 0) { toFrame = 100; }
  16519. if (loopAnimation === void 0) { loopAnimation = false; }
  16520. if (speedRatio === void 0) { speedRatio = 1.0; }
  16521. this.target = target;
  16522. this.fromFrame = fromFrame;
  16523. this.toFrame = toFrame;
  16524. this.loopAnimation = loopAnimation;
  16525. this.speedRatio = speedRatio;
  16526. this.onAnimationEnd = onAnimationEnd;
  16527. this._animations = new Array();
  16528. this._paused = false;
  16529. this.animationStarted = false;
  16530. if (animations) {
  16531. this.appendAnimations(target, animations);
  16532. }
  16533. this._scene = scene;
  16534. scene._activeAnimatables.push(this);
  16535. }
  16536. // Methods
  16537. Animatable.prototype.appendAnimations = function (target, animations) {
  16538. for (var index = 0; index < animations.length; index++) {
  16539. var animation = animations[index];
  16540. animation._target = target;
  16541. this._animations.push(animation);
  16542. }
  16543. };
  16544. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  16545. var animations = this._animations;
  16546. for (var index = 0; index < animations.length; index++) {
  16547. if (animations[index].targetProperty === property) {
  16548. return animations[index];
  16549. }
  16550. }
  16551. return null;
  16552. };
  16553. Animatable.prototype.pause = function () {
  16554. if (this._paused) {
  16555. return;
  16556. }
  16557. this._paused = true;
  16558. };
  16559. Animatable.prototype.restart = function () {
  16560. this._paused = false;
  16561. };
  16562. Animatable.prototype.stop = function () {
  16563. var index = this._scene._activeAnimatables.indexOf(this);
  16564. if (index > -1) {
  16565. this._scene._activeAnimatables.splice(index, 1);
  16566. }
  16567. if (this.onAnimationEnd) {
  16568. this.onAnimationEnd();
  16569. }
  16570. };
  16571. Animatable.prototype._animate = function (delay) {
  16572. if (this._paused) {
  16573. if (!this._pausedDelay) {
  16574. this._pausedDelay = delay;
  16575. }
  16576. return true;
  16577. }
  16578. if (!this._localDelayOffset) {
  16579. this._localDelayOffset = delay;
  16580. }
  16581. else if (this._pausedDelay) {
  16582. this._localDelayOffset += delay - this._pausedDelay;
  16583. this._pausedDelay = null;
  16584. }
  16585. // Animating
  16586. var running = false;
  16587. var animations = this._animations;
  16588. for (var index = 0; index < animations.length; index++) {
  16589. var animation = animations[index];
  16590. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  16591. running = running || isRunning;
  16592. }
  16593. if (!running) {
  16594. // Remove from active animatables
  16595. index = this._scene._activeAnimatables.indexOf(this);
  16596. this._scene._activeAnimatables.splice(index, 1);
  16597. }
  16598. if (!running && this.onAnimationEnd) {
  16599. this.onAnimationEnd();
  16600. }
  16601. return running;
  16602. };
  16603. return Animatable;
  16604. })();
  16605. BABYLON.Animatable = Animatable;
  16606. })(BABYLON || (BABYLON = {}));
  16607. //# sourceMappingURL=babylon.animatable.js.map
  16608. var BABYLON;
  16609. (function (BABYLON) {
  16610. var EasingFunction = (function () {
  16611. function EasingFunction() {
  16612. // Properties
  16613. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  16614. }
  16615. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  16616. get: function () {
  16617. return EasingFunction._EASINGMODE_EASEIN;
  16618. },
  16619. enumerable: true,
  16620. configurable: true
  16621. });
  16622. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  16623. get: function () {
  16624. return EasingFunction._EASINGMODE_EASEOUT;
  16625. },
  16626. enumerable: true,
  16627. configurable: true
  16628. });
  16629. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  16630. get: function () {
  16631. return EasingFunction._EASINGMODE_EASEINOUT;
  16632. },
  16633. enumerable: true,
  16634. configurable: true
  16635. });
  16636. EasingFunction.prototype.setEasingMode = function (easingMode) {
  16637. var n = Math.min(Math.max(easingMode, 0), 2);
  16638. this._easingMode = n;
  16639. };
  16640. EasingFunction.prototype.getEasingMode = function () {
  16641. return this._easingMode;
  16642. };
  16643. EasingFunction.prototype.easeInCore = function (gradient) {
  16644. throw new Error('You must implement this method');
  16645. };
  16646. EasingFunction.prototype.ease = function (gradient) {
  16647. switch (this._easingMode) {
  16648. case EasingFunction.EASINGMODE_EASEIN:
  16649. return this.easeInCore(gradient);
  16650. case EasingFunction.EASINGMODE_EASEOUT:
  16651. return (1 - this.easeInCore(1 - gradient));
  16652. }
  16653. if (gradient >= 0.5) {
  16654. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  16655. }
  16656. return (this.easeInCore(gradient * 2) * 0.5);
  16657. };
  16658. //Statics
  16659. EasingFunction._EASINGMODE_EASEIN = 0;
  16660. EasingFunction._EASINGMODE_EASEOUT = 1;
  16661. EasingFunction._EASINGMODE_EASEINOUT = 2;
  16662. return EasingFunction;
  16663. })();
  16664. BABYLON.EasingFunction = EasingFunction;
  16665. var CircleEase = (function (_super) {
  16666. __extends(CircleEase, _super);
  16667. function CircleEase() {
  16668. _super.apply(this, arguments);
  16669. }
  16670. CircleEase.prototype.easeInCore = function (gradient) {
  16671. gradient = Math.max(0, Math.min(1, gradient));
  16672. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  16673. };
  16674. return CircleEase;
  16675. })(EasingFunction);
  16676. BABYLON.CircleEase = CircleEase;
  16677. var BackEase = (function (_super) {
  16678. __extends(BackEase, _super);
  16679. function BackEase(amplitude) {
  16680. if (amplitude === void 0) { amplitude = 1; }
  16681. _super.call(this);
  16682. this.amplitude = amplitude;
  16683. }
  16684. BackEase.prototype.easeInCore = function (gradient) {
  16685. var num = Math.max(0, this.amplitude);
  16686. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  16687. };
  16688. return BackEase;
  16689. })(EasingFunction);
  16690. BABYLON.BackEase = BackEase;
  16691. var BounceEase = (function (_super) {
  16692. __extends(BounceEase, _super);
  16693. function BounceEase(bounces, bounciness) {
  16694. if (bounces === void 0) { bounces = 3; }
  16695. if (bounciness === void 0) { bounciness = 2; }
  16696. _super.call(this);
  16697. this.bounces = bounces;
  16698. this.bounciness = bounciness;
  16699. }
  16700. BounceEase.prototype.easeInCore = function (gradient) {
  16701. var y = Math.max(0.0, this.bounces);
  16702. var bounciness = this.bounciness;
  16703. if (bounciness <= 1.0) {
  16704. bounciness = 1.001;
  16705. }
  16706. var num9 = Math.pow(bounciness, y);
  16707. var num5 = 1.0 - bounciness;
  16708. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  16709. var num15 = gradient * num4;
  16710. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  16711. var num3 = Math.floor(num65);
  16712. var num13 = num3 + 1.0;
  16713. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  16714. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  16715. var num7 = (num8 + num12) * 0.5;
  16716. var num6 = gradient - num7;
  16717. var num2 = num7 - num8;
  16718. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  16719. };
  16720. return BounceEase;
  16721. })(EasingFunction);
  16722. BABYLON.BounceEase = BounceEase;
  16723. var CubicEase = (function (_super) {
  16724. __extends(CubicEase, _super);
  16725. function CubicEase() {
  16726. _super.apply(this, arguments);
  16727. }
  16728. CubicEase.prototype.easeInCore = function (gradient) {
  16729. return (gradient * gradient * gradient);
  16730. };
  16731. return CubicEase;
  16732. })(EasingFunction);
  16733. BABYLON.CubicEase = CubicEase;
  16734. var ElasticEase = (function (_super) {
  16735. __extends(ElasticEase, _super);
  16736. function ElasticEase(oscillations, springiness) {
  16737. if (oscillations === void 0) { oscillations = 3; }
  16738. if (springiness === void 0) { springiness = 3; }
  16739. _super.call(this);
  16740. this.oscillations = oscillations;
  16741. this.springiness = springiness;
  16742. }
  16743. ElasticEase.prototype.easeInCore = function (gradient) {
  16744. var num2;
  16745. var num3 = Math.max(0.0, this.oscillations);
  16746. var num = Math.max(0.0, this.springiness);
  16747. if (num == 0) {
  16748. num2 = gradient;
  16749. }
  16750. else {
  16751. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  16752. }
  16753. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  16754. };
  16755. return ElasticEase;
  16756. })(EasingFunction);
  16757. BABYLON.ElasticEase = ElasticEase;
  16758. var ExponentialEase = (function (_super) {
  16759. __extends(ExponentialEase, _super);
  16760. function ExponentialEase(exponent) {
  16761. if (exponent === void 0) { exponent = 2; }
  16762. _super.call(this);
  16763. this.exponent = exponent;
  16764. }
  16765. ExponentialEase.prototype.easeInCore = function (gradient) {
  16766. if (this.exponent <= 0) {
  16767. return gradient;
  16768. }
  16769. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  16770. };
  16771. return ExponentialEase;
  16772. })(EasingFunction);
  16773. BABYLON.ExponentialEase = ExponentialEase;
  16774. var PowerEase = (function (_super) {
  16775. __extends(PowerEase, _super);
  16776. function PowerEase(power) {
  16777. if (power === void 0) { power = 2; }
  16778. _super.call(this);
  16779. this.power = power;
  16780. }
  16781. PowerEase.prototype.easeInCore = function (gradient) {
  16782. var y = Math.max(0.0, this.power);
  16783. return Math.pow(gradient, y);
  16784. };
  16785. return PowerEase;
  16786. })(EasingFunction);
  16787. BABYLON.PowerEase = PowerEase;
  16788. var QuadraticEase = (function (_super) {
  16789. __extends(QuadraticEase, _super);
  16790. function QuadraticEase() {
  16791. _super.apply(this, arguments);
  16792. }
  16793. QuadraticEase.prototype.easeInCore = function (gradient) {
  16794. return (gradient * gradient);
  16795. };
  16796. return QuadraticEase;
  16797. })(EasingFunction);
  16798. BABYLON.QuadraticEase = QuadraticEase;
  16799. var QuarticEase = (function (_super) {
  16800. __extends(QuarticEase, _super);
  16801. function QuarticEase() {
  16802. _super.apply(this, arguments);
  16803. }
  16804. QuarticEase.prototype.easeInCore = function (gradient) {
  16805. return (gradient * gradient * gradient * gradient);
  16806. };
  16807. return QuarticEase;
  16808. })(EasingFunction);
  16809. BABYLON.QuarticEase = QuarticEase;
  16810. var QuinticEase = (function (_super) {
  16811. __extends(QuinticEase, _super);
  16812. function QuinticEase() {
  16813. _super.apply(this, arguments);
  16814. }
  16815. QuinticEase.prototype.easeInCore = function (gradient) {
  16816. return (gradient * gradient * gradient * gradient * gradient);
  16817. };
  16818. return QuinticEase;
  16819. })(EasingFunction);
  16820. BABYLON.QuinticEase = QuinticEase;
  16821. var SineEase = (function (_super) {
  16822. __extends(SineEase, _super);
  16823. function SineEase() {
  16824. _super.apply(this, arguments);
  16825. }
  16826. SineEase.prototype.easeInCore = function (gradient) {
  16827. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  16828. };
  16829. return SineEase;
  16830. })(EasingFunction);
  16831. BABYLON.SineEase = SineEase;
  16832. var BezierCurveEase = (function (_super) {
  16833. __extends(BezierCurveEase, _super);
  16834. function BezierCurveEase(x1, y1, x2, y2) {
  16835. if (x1 === void 0) { x1 = 0; }
  16836. if (y1 === void 0) { y1 = 0; }
  16837. if (x2 === void 0) { x2 = 1; }
  16838. if (y2 === void 0) { y2 = 1; }
  16839. _super.call(this);
  16840. this.x1 = x1;
  16841. this.y1 = y1;
  16842. this.x2 = x2;
  16843. this.y2 = y2;
  16844. }
  16845. BezierCurveEase.prototype.easeInCore = function (gradient) {
  16846. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  16847. };
  16848. return BezierCurveEase;
  16849. })(EasingFunction);
  16850. BABYLON.BezierCurveEase = BezierCurveEase;
  16851. })(BABYLON || (BABYLON = {}));
  16852. //# sourceMappingURL=babylon.easing.js.mapvar BABYLON;
  16853. (function (BABYLON) {
  16854. var Octree = (function () {
  16855. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  16856. if (maxDepth === void 0) { maxDepth = 2; }
  16857. this.maxDepth = maxDepth;
  16858. this.dynamicContent = new Array();
  16859. this._maxBlockCapacity = maxBlockCapacity || 64;
  16860. this._selectionContent = new BABYLON.SmartArray(1024);
  16861. this._creationFunc = creationFunc;
  16862. }
  16863. // Methods
  16864. Octree.prototype.update = function (worldMin, worldMax, entries) {
  16865. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  16866. };
  16867. Octree.prototype.addMesh = function (entry) {
  16868. for (var index = 0; index < this.blocks.length; index++) {
  16869. var block = this.blocks[index];
  16870. block.addEntry(entry);
  16871. }
  16872. };
  16873. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  16874. this._selectionContent.reset();
  16875. for (var index = 0; index < this.blocks.length; index++) {
  16876. var block = this.blocks[index];
  16877. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  16878. }
  16879. if (allowDuplicate) {
  16880. this._selectionContent.concat(this.dynamicContent);
  16881. }
  16882. else {
  16883. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  16884. }
  16885. return this._selectionContent;
  16886. };
  16887. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  16888. this._selectionContent.reset();
  16889. for (var index = 0; index < this.blocks.length; index++) {
  16890. var block = this.blocks[index];
  16891. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  16892. }
  16893. if (allowDuplicate) {
  16894. this._selectionContent.concat(this.dynamicContent);
  16895. }
  16896. else {
  16897. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  16898. }
  16899. return this._selectionContent;
  16900. };
  16901. Octree.prototype.intersectsRay = function (ray) {
  16902. this._selectionContent.reset();
  16903. for (var index = 0; index < this.blocks.length; index++) {
  16904. var block = this.blocks[index];
  16905. block.intersectsRay(ray, this._selectionContent);
  16906. }
  16907. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  16908. return this._selectionContent;
  16909. };
  16910. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  16911. target.blocks = new Array();
  16912. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  16913. for (var x = 0; x < 2; x++) {
  16914. for (var y = 0; y < 2; y++) {
  16915. for (var z = 0; z < 2; z++) {
  16916. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  16917. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  16918. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  16919. block.addEntries(entries);
  16920. target.blocks.push(block);
  16921. }
  16922. }
  16923. }
  16924. };
  16925. Octree.CreationFuncForMeshes = function (entry, block) {
  16926. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  16927. block.entries.push(entry);
  16928. }
  16929. };
  16930. Octree.CreationFuncForSubMeshes = function (entry, block) {
  16931. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  16932. block.entries.push(entry);
  16933. }
  16934. };
  16935. return Octree;
  16936. })();
  16937. BABYLON.Octree = Octree;
  16938. })(BABYLON || (BABYLON = {}));
  16939. //# sourceMappingURL=babylon.octree.js.mapvar BABYLON;
  16940. (function (BABYLON) {
  16941. var OctreeBlock = (function () {
  16942. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  16943. this.entries = new Array();
  16944. this._boundingVectors = new Array();
  16945. this._capacity = capacity;
  16946. this._depth = depth;
  16947. this._maxDepth = maxDepth;
  16948. this._creationFunc = creationFunc;
  16949. this._minPoint = minPoint;
  16950. this._maxPoint = maxPoint;
  16951. this._boundingVectors.push(minPoint.clone());
  16952. this._boundingVectors.push(maxPoint.clone());
  16953. this._boundingVectors.push(minPoint.clone());
  16954. this._boundingVectors[2].x = maxPoint.x;
  16955. this._boundingVectors.push(minPoint.clone());
  16956. this._boundingVectors[3].y = maxPoint.y;
  16957. this._boundingVectors.push(minPoint.clone());
  16958. this._boundingVectors[4].z = maxPoint.z;
  16959. this._boundingVectors.push(maxPoint.clone());
  16960. this._boundingVectors[5].z = minPoint.z;
  16961. this._boundingVectors.push(maxPoint.clone());
  16962. this._boundingVectors[6].x = minPoint.x;
  16963. this._boundingVectors.push(maxPoint.clone());
  16964. this._boundingVectors[7].y = minPoint.y;
  16965. }
  16966. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  16967. // Property
  16968. get: function () {
  16969. return this._capacity;
  16970. },
  16971. enumerable: true,
  16972. configurable: true
  16973. });
  16974. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  16975. get: function () {
  16976. return this._minPoint;
  16977. },
  16978. enumerable: true,
  16979. configurable: true
  16980. });
  16981. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  16982. get: function () {
  16983. return this._maxPoint;
  16984. },
  16985. enumerable: true,
  16986. configurable: true
  16987. });
  16988. // Methods
  16989. OctreeBlock.prototype.addEntry = function (entry) {
  16990. if (this.blocks) {
  16991. for (var index = 0; index < this.blocks.length; index++) {
  16992. var block = this.blocks[index];
  16993. block.addEntry(entry);
  16994. }
  16995. return;
  16996. }
  16997. this._creationFunc(entry, this);
  16998. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  16999. this.createInnerBlocks();
  17000. }
  17001. };
  17002. OctreeBlock.prototype.addEntries = function (entries) {
  17003. for (var index = 0; index < entries.length; index++) {
  17004. var mesh = entries[index];
  17005. this.addEntry(mesh);
  17006. }
  17007. };
  17008. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  17009. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  17010. if (this.blocks) {
  17011. for (var index = 0; index < this.blocks.length; index++) {
  17012. var block = this.blocks[index];
  17013. block.select(frustumPlanes, selection, allowDuplicate);
  17014. }
  17015. return;
  17016. }
  17017. if (allowDuplicate) {
  17018. selection.concat(this.entries);
  17019. }
  17020. else {
  17021. selection.concatWithNoDuplicate(this.entries);
  17022. }
  17023. }
  17024. };
  17025. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  17026. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  17027. if (this.blocks) {
  17028. for (var index = 0; index < this.blocks.length; index++) {
  17029. var block = this.blocks[index];
  17030. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  17031. }
  17032. return;
  17033. }
  17034. if (allowDuplicate) {
  17035. selection.concat(this.entries);
  17036. }
  17037. else {
  17038. selection.concatWithNoDuplicate(this.entries);
  17039. }
  17040. }
  17041. };
  17042. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  17043. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  17044. if (this.blocks) {
  17045. for (var index = 0; index < this.blocks.length; index++) {
  17046. var block = this.blocks[index];
  17047. block.intersectsRay(ray, selection);
  17048. }
  17049. return;
  17050. }
  17051. selection.concatWithNoDuplicate(this.entries);
  17052. }
  17053. };
  17054. OctreeBlock.prototype.createInnerBlocks = function () {
  17055. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  17056. };
  17057. return OctreeBlock;
  17058. })();
  17059. BABYLON.OctreeBlock = OctreeBlock;
  17060. })(BABYLON || (BABYLON = {}));
  17061. //# sourceMappingURL=babylon.octreeBlock.js.mapvar BABYLON;
  17062. (function (BABYLON) {
  17063. var Bone = (function () {
  17064. function Bone(name, skeleton, parentBone, matrix) {
  17065. this.name = name;
  17066. this.children = new Array();
  17067. this.animations = new Array();
  17068. this._worldTransform = new BABYLON.Matrix();
  17069. this._absoluteTransform = new BABYLON.Matrix();
  17070. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  17071. this._skeleton = skeleton;
  17072. this._matrix = matrix;
  17073. this._baseMatrix = matrix;
  17074. skeleton.bones.push(this);
  17075. if (parentBone) {
  17076. this._parent = parentBone;
  17077. parentBone.children.push(this);
  17078. }
  17079. else {
  17080. this._parent = null;
  17081. }
  17082. this._updateDifferenceMatrix();
  17083. }
  17084. // Members
  17085. Bone.prototype.getParent = function () {
  17086. return this._parent;
  17087. };
  17088. Bone.prototype.getLocalMatrix = function () {
  17089. return this._matrix;
  17090. };
  17091. Bone.prototype.getBaseMatrix = function () {
  17092. return this._baseMatrix;
  17093. };
  17094. Bone.prototype.getWorldMatrix = function () {
  17095. return this._worldTransform;
  17096. };
  17097. Bone.prototype.getInvertedAbsoluteTransform = function () {
  17098. return this._invertedAbsoluteTransform;
  17099. };
  17100. Bone.prototype.getAbsoluteMatrix = function () {
  17101. var matrix = this._matrix.clone();
  17102. var parent = this._parent;
  17103. while (parent) {
  17104. matrix = matrix.multiply(parent.getLocalMatrix());
  17105. parent = parent.getParent();
  17106. }
  17107. return matrix;
  17108. };
  17109. // Methods
  17110. Bone.prototype.updateMatrix = function (matrix) {
  17111. this._matrix = matrix;
  17112. this._skeleton._markAsDirty();
  17113. this._updateDifferenceMatrix();
  17114. };
  17115. Bone.prototype._updateDifferenceMatrix = function () {
  17116. if (this._parent) {
  17117. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  17118. }
  17119. else {
  17120. this._absoluteTransform.copyFrom(this._matrix);
  17121. }
  17122. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  17123. for (var index = 0; index < this.children.length; index++) {
  17124. this.children[index]._updateDifferenceMatrix();
  17125. }
  17126. };
  17127. Bone.prototype.markAsDirty = function () {
  17128. this._skeleton._markAsDirty();
  17129. };
  17130. return Bone;
  17131. })();
  17132. BABYLON.Bone = Bone;
  17133. })(BABYLON || (BABYLON = {}));
  17134. //# sourceMappingURL=babylon.bone.js.mapvar BABYLON;
  17135. (function (BABYLON) {
  17136. var Skeleton = (function () {
  17137. function Skeleton(name, id, scene) {
  17138. this.name = name;
  17139. this.id = id;
  17140. this.bones = new Array();
  17141. this._isDirty = true;
  17142. this._identity = BABYLON.Matrix.Identity();
  17143. this.bones = [];
  17144. this._scene = scene;
  17145. scene.skeletons.push(this);
  17146. }
  17147. // Members
  17148. Skeleton.prototype.getTransformMatrices = function () {
  17149. return this._transformMatrices;
  17150. };
  17151. // Methods
  17152. Skeleton.prototype._markAsDirty = function () {
  17153. this._isDirty = true;
  17154. };
  17155. Skeleton.prototype.prepare = function () {
  17156. if (!this._isDirty) {
  17157. return;
  17158. }
  17159. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  17160. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  17161. }
  17162. for (var index = 0; index < this.bones.length; index++) {
  17163. var bone = this.bones[index];
  17164. var parentBone = bone.getParent();
  17165. if (parentBone) {
  17166. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  17167. }
  17168. else {
  17169. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  17170. }
  17171. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  17172. }
  17173. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  17174. this._isDirty = false;
  17175. this._scene._activeBones += this.bones.length;
  17176. };
  17177. Skeleton.prototype.getAnimatables = function () {
  17178. if (!this._animatables || this._animatables.length !== this.bones.length) {
  17179. this._animatables = [];
  17180. for (var index = 0; index < this.bones.length; index++) {
  17181. this._animatables.push(this.bones[index]);
  17182. }
  17183. }
  17184. return this._animatables;
  17185. };
  17186. Skeleton.prototype.clone = function (name, id) {
  17187. var result = new Skeleton(name, id || name, this._scene);
  17188. for (var index = 0; index < this.bones.length; index++) {
  17189. var source = this.bones[index];
  17190. var parentBone = null;
  17191. if (source.getParent()) {
  17192. var parentIndex = this.bones.indexOf(source.getParent());
  17193. parentBone = result.bones[parentIndex];
  17194. }
  17195. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  17196. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  17197. }
  17198. return result;
  17199. };
  17200. return Skeleton;
  17201. })();
  17202. BABYLON.Skeleton = Skeleton;
  17203. })(BABYLON || (BABYLON = {}));
  17204. //# sourceMappingURL=babylon.skeleton.js.mapvar BABYLON;
  17205. (function (BABYLON) {
  17206. var PostProcess = (function () {
  17207. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable, defines) {
  17208. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  17209. this.name = name;
  17210. this.width = -1;
  17211. this.height = -1;
  17212. this._reusable = false;
  17213. this._textures = new BABYLON.SmartArray(2);
  17214. this._currentRenderTextureInd = 0;
  17215. if (camera != null) {
  17216. this._camera = camera;
  17217. this._scene = camera.getScene();
  17218. camera.attachPostProcess(this);
  17219. this._engine = this._scene.getEngine();
  17220. }
  17221. else {
  17222. this._engine = engine;
  17223. }
  17224. this._renderRatio = ratio;
  17225. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  17226. this._reusable = reusable || false;
  17227. samplers = samplers || [];
  17228. samplers.push("textureSampler");
  17229. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: fragmentUrl }, ["position"], parameters || [], samplers, defines !== undefined ? defines : "");
  17230. }
  17231. PostProcess.prototype.isReusable = function () {
  17232. return this._reusable;
  17233. };
  17234. PostProcess.prototype.activate = function (camera, sourceTexture) {
  17235. camera = camera || this._camera;
  17236. var scene = camera.getScene();
  17237. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  17238. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  17239. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  17240. desiredWidth = BABYLON.Tools.GetExponantOfTwo(desiredWidth, maxSize);
  17241. desiredHeight = BABYLON.Tools.GetExponantOfTwo(desiredHeight, maxSize);
  17242. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  17243. if (this._textures.length > 0) {
  17244. for (var i = 0; i < this._textures.length; i++) {
  17245. this._engine._releaseTexture(this._textures.data[i]);
  17246. }
  17247. this._textures.reset();
  17248. }
  17249. this.width = desiredWidth;
  17250. this.height = desiredHeight;
  17251. 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 }));
  17252. if (this._reusable) {
  17253. 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 }));
  17254. }
  17255. if (this.onSizeChanged) {
  17256. this.onSizeChanged();
  17257. }
  17258. }
  17259. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  17260. if (this.onActivate) {
  17261. this.onActivate(camera);
  17262. }
  17263. // Clear
  17264. if (this.clearColor) {
  17265. this._engine.clear(this.clearColor, true, true);
  17266. }
  17267. else {
  17268. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  17269. }
  17270. if (this._reusable) {
  17271. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  17272. }
  17273. };
  17274. PostProcess.prototype.apply = function () {
  17275. // Check
  17276. if (!this._effect.isReady())
  17277. return null;
  17278. // States
  17279. this._engine.enableEffect(this._effect);
  17280. this._engine.setState(false);
  17281. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  17282. this._engine.setDepthBuffer(false);
  17283. this._engine.setDepthWrite(false);
  17284. // Texture
  17285. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  17286. // Parameters
  17287. if (this.onApply) {
  17288. this.onApply(this._effect);
  17289. }
  17290. return this._effect;
  17291. };
  17292. PostProcess.prototype.dispose = function (camera) {
  17293. camera = camera || this._camera;
  17294. if (this._textures.length > 0) {
  17295. for (var i = 0; i < this._textures.length; i++) {
  17296. this._engine._releaseTexture(this._textures.data[i]);
  17297. }
  17298. this._textures.reset();
  17299. }
  17300. if (!camera) {
  17301. return;
  17302. }
  17303. camera.detachPostProcess(this);
  17304. var index = camera._postProcesses.indexOf(this);
  17305. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  17306. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  17307. }
  17308. };
  17309. return PostProcess;
  17310. })();
  17311. BABYLON.PostProcess = PostProcess;
  17312. })(BABYLON || (BABYLON = {}));
  17313. //# sourceMappingURL=babylon.postProcess.js.mapvar BABYLON;
  17314. (function (BABYLON) {
  17315. var PostProcessManager = (function () {
  17316. function PostProcessManager(scene) {
  17317. this._vertexDeclaration = [2];
  17318. this._vertexStrideSize = 2 * 4;
  17319. this._scene = scene;
  17320. // VBO
  17321. var vertices = [];
  17322. vertices.push(1, 1);
  17323. vertices.push(-1, 1);
  17324. vertices.push(-1, -1);
  17325. vertices.push(1, -1);
  17326. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  17327. // Indices
  17328. var indices = [];
  17329. indices.push(0);
  17330. indices.push(1);
  17331. indices.push(2);
  17332. indices.push(0);
  17333. indices.push(2);
  17334. indices.push(3);
  17335. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  17336. }
  17337. // Methods
  17338. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  17339. var postProcesses = this._scene.activeCamera._postProcesses;
  17340. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  17341. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  17342. return false;
  17343. }
  17344. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  17345. return true;
  17346. };
  17347. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  17348. var engine = this._scene.getEngine();
  17349. for (var index = 0; index < postProcesses.length; index++) {
  17350. if (index < postProcesses.length - 1) {
  17351. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  17352. }
  17353. else {
  17354. if (targetTexture) {
  17355. engine.bindFramebuffer(targetTexture);
  17356. }
  17357. else {
  17358. engine.restoreDefaultFramebuffer();
  17359. }
  17360. }
  17361. var pp = postProcesses[index];
  17362. var effect = pp.apply();
  17363. if (effect) {
  17364. if (pp.onBeforeRender) {
  17365. pp.onBeforeRender(effect);
  17366. }
  17367. // VBOs
  17368. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  17369. // Draw order
  17370. engine.draw(true, 0, 6);
  17371. }
  17372. }
  17373. // Restore depth buffer
  17374. engine.setDepthBuffer(true);
  17375. engine.setDepthWrite(true);
  17376. };
  17377. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, postProcesses) {
  17378. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  17379. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  17380. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  17381. return;
  17382. }
  17383. var engine = this._scene.getEngine();
  17384. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  17385. if (index < postProcessesTakenIndices.length - 1) {
  17386. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  17387. }
  17388. else {
  17389. if (targetTexture) {
  17390. engine.bindFramebuffer(targetTexture);
  17391. }
  17392. else {
  17393. engine.restoreDefaultFramebuffer();
  17394. }
  17395. }
  17396. if (doNotPresent) {
  17397. break;
  17398. }
  17399. var pp = postProcesses[postProcessesTakenIndices[index]];
  17400. var effect = pp.apply();
  17401. if (effect) {
  17402. if (pp.onBeforeRender) {
  17403. pp.onBeforeRender(effect);
  17404. }
  17405. // VBOs
  17406. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  17407. // Draw order
  17408. engine.draw(true, 0, 6);
  17409. }
  17410. }
  17411. // Restore depth buffer
  17412. engine.setDepthBuffer(true);
  17413. engine.setDepthWrite(true);
  17414. };
  17415. PostProcessManager.prototype.dispose = function () {
  17416. if (this._vertexBuffer) {
  17417. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  17418. this._vertexBuffer = null;
  17419. }
  17420. if (this._indexBuffer) {
  17421. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  17422. this._indexBuffer = null;
  17423. }
  17424. };
  17425. return PostProcessManager;
  17426. })();
  17427. BABYLON.PostProcessManager = PostProcessManager;
  17428. })(BABYLON || (BABYLON = {}));
  17429. //# sourceMappingURL=babylon.postProcessManager.js.map
  17430. var BABYLON;
  17431. (function (BABYLON) {
  17432. var PassPostProcess = (function (_super) {
  17433. __extends(PassPostProcess, _super);
  17434. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  17435. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  17436. }
  17437. return PassPostProcess;
  17438. })(BABYLON.PostProcess);
  17439. BABYLON.PassPostProcess = PassPostProcess;
  17440. })(BABYLON || (BABYLON = {}));
  17441. //# sourceMappingURL=babylon.passPostProcess.js.map
  17442. var BABYLON;
  17443. (function (BABYLON) {
  17444. var BlurPostProcess = (function (_super) {
  17445. __extends(BlurPostProcess, _super);
  17446. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  17447. var _this = this;
  17448. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  17449. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  17450. this.direction = direction;
  17451. this.blurWidth = blurWidth;
  17452. this.onApply = function (effect) {
  17453. effect.setFloat2("screenSize", _this.width, _this.height);
  17454. effect.setVector2("direction", _this.direction);
  17455. effect.setFloat("blurWidth", _this.blurWidth);
  17456. };
  17457. }
  17458. return BlurPostProcess;
  17459. })(BABYLON.PostProcess);
  17460. BABYLON.BlurPostProcess = BlurPostProcess;
  17461. })(BABYLON || (BABYLON = {}));
  17462. //# sourceMappingURL=babylon.blurPostProcess.js.map
  17463. var BABYLON;
  17464. (function (BABYLON) {
  17465. var FilterPostProcess = (function (_super) {
  17466. __extends(FilterPostProcess, _super);
  17467. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  17468. var _this = this;
  17469. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  17470. this.kernelMatrix = kernelMatrix;
  17471. this.onApply = function (effect) {
  17472. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  17473. };
  17474. }
  17475. return FilterPostProcess;
  17476. })(BABYLON.PostProcess);
  17477. BABYLON.FilterPostProcess = FilterPostProcess;
  17478. })(BABYLON || (BABYLON = {}));
  17479. //# sourceMappingURL=babylon.filterPostProcess.js.map
  17480. var BABYLON;
  17481. (function (BABYLON) {
  17482. var RefractionPostProcess = (function (_super) {
  17483. __extends(RefractionPostProcess, _super);
  17484. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  17485. var _this = this;
  17486. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  17487. this.color = color;
  17488. this.depth = depth;
  17489. this.colorLevel = colorLevel;
  17490. this.onActivate = function (cam) {
  17491. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  17492. };
  17493. this.onApply = function (effect) {
  17494. effect.setColor3("baseColor", _this.color);
  17495. effect.setFloat("depth", _this.depth);
  17496. effect.setFloat("colorLevel", _this.colorLevel);
  17497. effect.setTexture("refractionSampler", _this._refRexture);
  17498. };
  17499. }
  17500. // Methods
  17501. RefractionPostProcess.prototype.dispose = function (camera) {
  17502. if (this._refRexture) {
  17503. this._refRexture.dispose();
  17504. }
  17505. _super.prototype.dispose.call(this, camera);
  17506. };
  17507. return RefractionPostProcess;
  17508. })(BABYLON.PostProcess);
  17509. BABYLON.RefractionPostProcess = RefractionPostProcess;
  17510. })(BABYLON || (BABYLON = {}));
  17511. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  17512. var BABYLON;
  17513. (function (BABYLON) {
  17514. var BlackAndWhitePostProcess = (function (_super) {
  17515. __extends(BlackAndWhitePostProcess, _super);
  17516. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  17517. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  17518. }
  17519. return BlackAndWhitePostProcess;
  17520. })(BABYLON.PostProcess);
  17521. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  17522. })(BABYLON || (BABYLON = {}));
  17523. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  17524. var BABYLON;
  17525. (function (BABYLON) {
  17526. var ConvolutionPostProcess = (function (_super) {
  17527. __extends(ConvolutionPostProcess, _super);
  17528. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  17529. var _this = this;
  17530. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  17531. this.kernel = kernel;
  17532. this.onApply = function (effect) {
  17533. effect.setFloat2("screenSize", _this.width, _this.height);
  17534. effect.setArray("kernel", _this.kernel);
  17535. };
  17536. }
  17537. // Statics
  17538. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  17539. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  17540. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  17541. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  17542. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  17543. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  17544. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  17545. return ConvolutionPostProcess;
  17546. })(BABYLON.PostProcess);
  17547. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  17548. })(BABYLON || (BABYLON = {}));
  17549. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  17550. var BABYLON;
  17551. (function (BABYLON) {
  17552. var FxaaPostProcess = (function (_super) {
  17553. __extends(FxaaPostProcess, _super);
  17554. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  17555. var _this = this;
  17556. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  17557. this.onSizeChanged = function () {
  17558. _this.texelWidth = 1.0 / _this.width;
  17559. _this.texelHeight = 1.0 / _this.height;
  17560. };
  17561. this.onApply = function (effect) {
  17562. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  17563. };
  17564. }
  17565. return FxaaPostProcess;
  17566. })(BABYLON.PostProcess);
  17567. BABYLON.FxaaPostProcess = FxaaPostProcess;
  17568. })(BABYLON || (BABYLON = {}));
  17569. //# sourceMappingURL=babylon.fxaaPostProcess.js.mapvar BABYLON;
  17570. (function (BABYLON) {
  17571. var LensFlare = (function () {
  17572. function LensFlare(size, position, color, imgUrl, system) {
  17573. this.size = size;
  17574. this.position = position;
  17575. this.dispose = function () {
  17576. if (this.texture) {
  17577. this.texture.dispose();
  17578. }
  17579. // Remove from scene
  17580. var index = this._system.lensFlares.indexOf(this);
  17581. this._system.lensFlares.splice(index, 1);
  17582. };
  17583. this.color = color || new BABYLON.Color3(1, 1, 1);
  17584. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  17585. this._system = system;
  17586. system.lensFlares.push(this);
  17587. }
  17588. return LensFlare;
  17589. })();
  17590. BABYLON.LensFlare = LensFlare;
  17591. })(BABYLON || (BABYLON = {}));
  17592. //# sourceMappingURL=babylon.lensFlare.js.mapvar BABYLON;
  17593. (function (BABYLON) {
  17594. var LensFlareSystem = (function () {
  17595. function LensFlareSystem(name, emitter, scene) {
  17596. this.name = name;
  17597. this.lensFlares = new Array();
  17598. this.borderLimit = 300;
  17599. this._vertexDeclaration = [2];
  17600. this._vertexStrideSize = 2 * 4;
  17601. this._isEnabled = true;
  17602. this._scene = scene;
  17603. this._emitter = emitter;
  17604. scene.lensFlareSystems.push(this);
  17605. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  17606. // VBO
  17607. var vertices = [];
  17608. vertices.push(1, 1);
  17609. vertices.push(-1, 1);
  17610. vertices.push(-1, -1);
  17611. vertices.push(1, -1);
  17612. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  17613. // Indices
  17614. var indices = [];
  17615. indices.push(0);
  17616. indices.push(1);
  17617. indices.push(2);
  17618. indices.push(0);
  17619. indices.push(2);
  17620. indices.push(3);
  17621. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  17622. // Effects
  17623. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  17624. }
  17625. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  17626. get: function () {
  17627. return this._isEnabled;
  17628. },
  17629. set: function (value) {
  17630. this._isEnabled = value;
  17631. },
  17632. enumerable: true,
  17633. configurable: true
  17634. });
  17635. LensFlareSystem.prototype.getScene = function () {
  17636. return this._scene;
  17637. };
  17638. LensFlareSystem.prototype.getEmitter = function () {
  17639. return this._emitter;
  17640. };
  17641. LensFlareSystem.prototype.getEmitterPosition = function () {
  17642. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  17643. };
  17644. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  17645. var position = this.getEmitterPosition();
  17646. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  17647. this._positionX = position.x;
  17648. this._positionY = position.y;
  17649. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  17650. if (position.z > 0) {
  17651. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  17652. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  17653. return true;
  17654. }
  17655. }
  17656. return false;
  17657. };
  17658. LensFlareSystem.prototype._isVisible = function () {
  17659. if (!this._isEnabled) {
  17660. return false;
  17661. }
  17662. var emitterPosition = this.getEmitterPosition();
  17663. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  17664. var distance = direction.length();
  17665. direction.normalize();
  17666. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  17667. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  17668. return !pickInfo.hit || pickInfo.distance > distance;
  17669. };
  17670. LensFlareSystem.prototype.render = function () {
  17671. if (!this._effect.isReady())
  17672. return false;
  17673. var engine = this._scene.getEngine();
  17674. var viewport = this._scene.activeCamera.viewport;
  17675. var globalViewport = viewport.toGlobal(engine);
  17676. // Position
  17677. if (!this.computeEffectivePosition(globalViewport)) {
  17678. return false;
  17679. }
  17680. // Visibility
  17681. if (!this._isVisible()) {
  17682. return false;
  17683. }
  17684. // Intensity
  17685. var awayX;
  17686. var awayY;
  17687. if (this._positionX < this.borderLimit + globalViewport.x) {
  17688. awayX = this.borderLimit + globalViewport.x - this._positionX;
  17689. }
  17690. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  17691. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  17692. }
  17693. else {
  17694. awayX = 0;
  17695. }
  17696. if (this._positionY < this.borderLimit + globalViewport.y) {
  17697. awayY = this.borderLimit + globalViewport.y - this._positionY;
  17698. }
  17699. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  17700. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  17701. }
  17702. else {
  17703. awayY = 0;
  17704. }
  17705. var away = (awayX > awayY) ? awayX : awayY;
  17706. if (away > this.borderLimit) {
  17707. away = this.borderLimit;
  17708. }
  17709. var intensity = 1.0 - (away / this.borderLimit);
  17710. if (intensity < 0) {
  17711. return false;
  17712. }
  17713. if (intensity > 1.0) {
  17714. intensity = 1.0;
  17715. }
  17716. // Position
  17717. var centerX = globalViewport.x + globalViewport.width / 2;
  17718. var centerY = globalViewport.y + globalViewport.height / 2;
  17719. var distX = centerX - this._positionX;
  17720. var distY = centerY - this._positionY;
  17721. // Effects
  17722. engine.enableEffect(this._effect);
  17723. engine.setState(false);
  17724. engine.setDepthBuffer(false);
  17725. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  17726. // VBOs
  17727. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  17728. for (var index = 0; index < this.lensFlares.length; index++) {
  17729. var flare = this.lensFlares[index];
  17730. var x = centerX - (distX * flare.position);
  17731. var y = centerY - (distY * flare.position);
  17732. var cw = flare.size;
  17733. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  17734. var cx = 2 * (x / globalViewport.width) - 1.0;
  17735. var cy = 1.0 - 2 * (y / globalViewport.height);
  17736. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  17737. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  17738. // Texture
  17739. this._effect.setTexture("textureSampler", flare.texture);
  17740. // Color
  17741. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  17742. // Draw order
  17743. engine.draw(true, 0, 6);
  17744. }
  17745. engine.setDepthBuffer(true);
  17746. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  17747. return true;
  17748. };
  17749. LensFlareSystem.prototype.dispose = function () {
  17750. if (this._vertexBuffer) {
  17751. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  17752. this._vertexBuffer = null;
  17753. }
  17754. if (this._indexBuffer) {
  17755. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  17756. this._indexBuffer = null;
  17757. }
  17758. while (this.lensFlares.length) {
  17759. this.lensFlares[0].dispose();
  17760. }
  17761. // Remove from scene
  17762. var index = this._scene.lensFlareSystems.indexOf(this);
  17763. this._scene.lensFlareSystems.splice(index, 1);
  17764. };
  17765. return LensFlareSystem;
  17766. })();
  17767. BABYLON.LensFlareSystem = LensFlareSystem;
  17768. })(BABYLON || (BABYLON = {}));
  17769. //# sourceMappingURL=babylon.lensFlareSystem.js.mapvar BABYLON;
  17770. (function (BABYLON) {
  17771. var IntersectionInfo = (function () {
  17772. function IntersectionInfo(bu, bv, distance) {
  17773. this.bu = bu;
  17774. this.bv = bv;
  17775. this.distance = distance;
  17776. this.faceId = 0;
  17777. this.subMeshId = 0;
  17778. }
  17779. return IntersectionInfo;
  17780. })();
  17781. BABYLON.IntersectionInfo = IntersectionInfo;
  17782. var PickingInfo = (function () {
  17783. function PickingInfo() {
  17784. this.hit = false;
  17785. this.distance = 0;
  17786. this.pickedPoint = null;
  17787. this.pickedMesh = null;
  17788. this.bu = 0;
  17789. this.bv = 0;
  17790. this.faceId = -1;
  17791. this.subMeshId = 0;
  17792. }
  17793. // Methods
  17794. PickingInfo.prototype.getNormal = function () {
  17795. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  17796. return null;
  17797. }
  17798. var indices = this.pickedMesh.getIndices();
  17799. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17800. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  17801. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  17802. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  17803. normal0 = normal0.scale(this.bu);
  17804. normal1 = normal1.scale(this.bv);
  17805. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  17806. return new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  17807. };
  17808. PickingInfo.prototype.getTextureCoordinates = function () {
  17809. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  17810. return null;
  17811. }
  17812. var indices = this.pickedMesh.getIndices();
  17813. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  17814. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  17815. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  17816. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  17817. uv0 = uv0.scale(this.bu);
  17818. uv1 = uv1.scale(this.bv);
  17819. uv2 = uv2.scale(1.0 - this.bu - this.bv);
  17820. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  17821. };
  17822. return PickingInfo;
  17823. })();
  17824. BABYLON.PickingInfo = PickingInfo;
  17825. })(BABYLON || (BABYLON = {}));
  17826. //# sourceMappingURL=babylon.pickingInfo.js.mapvar BABYLON;
  17827. (function (BABYLON) {
  17828. var FilesInput = (function () {
  17829. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  17830. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  17831. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  17832. this._engine = p_engine;
  17833. this._canvas = p_canvas;
  17834. this._currentScene = p_scene;
  17835. this._sceneLoadedCallback = p_sceneLoadedCallback;
  17836. this._progressCallback = p_progressCallback;
  17837. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  17838. this._textureLoadingCallback = p_textureLoadingCallback;
  17839. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  17840. }
  17841. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  17842. var _this = this;
  17843. if (p_elementToMonitor) {
  17844. this._elementToMonitor = p_elementToMonitor;
  17845. this._elementToMonitor.addEventListener("dragenter", function (e) {
  17846. _this.drag(e);
  17847. }, false);
  17848. this._elementToMonitor.addEventListener("dragover", function (e) {
  17849. _this.drag(e);
  17850. }, false);
  17851. this._elementToMonitor.addEventListener("drop", function (e) {
  17852. _this.drop(e);
  17853. }, false);
  17854. }
  17855. };
  17856. FilesInput.prototype.renderFunction = function () {
  17857. if (this._additionnalRenderLoopLogicCallback) {
  17858. this._additionnalRenderLoopLogicCallback();
  17859. }
  17860. if (this._currentScene) {
  17861. if (this._textureLoadingCallback) {
  17862. var remaining = this._currentScene.getWaitingItemsCount();
  17863. if (remaining > 0) {
  17864. this._textureLoadingCallback(remaining);
  17865. }
  17866. }
  17867. this._currentScene.render();
  17868. }
  17869. };
  17870. FilesInput.prototype.drag = function (e) {
  17871. e.stopPropagation();
  17872. e.preventDefault();
  17873. };
  17874. FilesInput.prototype.drop = function (eventDrop) {
  17875. eventDrop.stopPropagation();
  17876. eventDrop.preventDefault();
  17877. this.loadFiles(eventDrop);
  17878. };
  17879. FilesInput.prototype.loadFiles = function (event) {
  17880. if (this._startingProcessingFilesCallback)
  17881. this._startingProcessingFilesCallback();
  17882. // Handling data transfer via drag'n'drop
  17883. if (event && event.dataTransfer && event.dataTransfer.files) {
  17884. this._filesToLoad = event.dataTransfer.files;
  17885. }
  17886. // Handling files from input files
  17887. if (event && event.target && event.target.files) {
  17888. this._filesToLoad = event.target.files;
  17889. }
  17890. if (this._filesToLoad && this._filesToLoad.length > 0) {
  17891. for (var i = 0; i < this._filesToLoad.length; i++) {
  17892. switch (this._filesToLoad[i].type) {
  17893. case "image/jpeg":
  17894. case "image/png":
  17895. case "image/bmp":
  17896. FilesInput.FilesTextures[this._filesToLoad[i].name] = this._filesToLoad[i];
  17897. break;
  17898. case "image/targa":
  17899. case "image/vnd.ms-dds":
  17900. case "audio/wav":
  17901. case "audio/x-wav":
  17902. case "audio/mp3":
  17903. case "audio/mpeg":
  17904. case "audio/mpeg3":
  17905. case "audio/x-mpeg-3":
  17906. case "audio/ogg":
  17907. FilesInput.FilesToLoad[this._filesToLoad[i].name] = this._filesToLoad[i];
  17908. break;
  17909. default:
  17910. 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) {
  17911. this._sceneFileToLoad = this._filesToLoad[i];
  17912. }
  17913. break;
  17914. }
  17915. }
  17916. this.reload();
  17917. }
  17918. };
  17919. FilesInput.prototype.reload = function () {
  17920. var _this = this;
  17921. var that = this;
  17922. // If a ".babylon" file has been provided
  17923. if (this._sceneFileToLoad) {
  17924. if (this._currentScene) {
  17925. this._engine.stopRenderLoop();
  17926. this._currentScene.dispose();
  17927. }
  17928. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  17929. that._currentScene = newScene;
  17930. // Wait for textures and shaders to be ready
  17931. that._currentScene.executeWhenReady(function () {
  17932. // Attach camera to canvas inputs
  17933. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  17934. that._currentScene.createDefaultCameraOrLight();
  17935. }
  17936. that._currentScene.activeCamera.attachControl(that._canvas);
  17937. if (that._sceneLoadedCallback) {
  17938. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  17939. }
  17940. that._engine.runRenderLoop(function () {
  17941. that.renderFunction();
  17942. });
  17943. });
  17944. }, function (progress) {
  17945. if (_this._progressCallback) {
  17946. _this._progressCallback(progress);
  17947. }
  17948. });
  17949. }
  17950. else {
  17951. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  17952. }
  17953. };
  17954. FilesInput.FilesTextures = new Array();
  17955. FilesInput.FilesToLoad = new Array();
  17956. return FilesInput;
  17957. })();
  17958. BABYLON.FilesInput = FilesInput;
  17959. })(BABYLON || (BABYLON = {}));
  17960. //# sourceMappingURL=babylon.filesInput.js.mapvar BABYLON;
  17961. (function (BABYLON) {
  17962. var OimoJSPlugin = (function () {
  17963. function OimoJSPlugin() {
  17964. this._registeredMeshes = [];
  17965. /**
  17966. * Update the body position according to the mesh position
  17967. * @param mesh
  17968. */
  17969. this.updateBodyPosition = function (mesh) {
  17970. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17971. var registeredMesh = this._registeredMeshes[index];
  17972. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  17973. var body = registeredMesh.body.body;
  17974. mesh.computeWorldMatrix(true);
  17975. var center = mesh.getBoundingInfo().boundingBox.center;
  17976. body.setPosition(center.x, center.y, center.z);
  17977. body.setRotation(mesh.rotation.x, mesh.rotation.y, mesh.rotation.z);
  17978. return;
  17979. }
  17980. // Case where the parent has been updated
  17981. if (registeredMesh.mesh.parent === mesh) {
  17982. mesh.computeWorldMatrix(true);
  17983. registeredMesh.mesh.computeWorldMatrix(true);
  17984. var absolutePosition = registeredMesh.mesh.getAbsolutePosition();
  17985. var absoluteRotation = mesh.rotation;
  17986. body = registeredMesh.body.body;
  17987. body.setPosition(absolutePosition.x, absolutePosition.y, absolutePosition.z);
  17988. body.setRotation(absoluteRotation.x, absoluteRotation.y, absoluteRotation.z);
  17989. return;
  17990. }
  17991. }
  17992. };
  17993. }
  17994. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  17995. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  17996. };
  17997. OimoJSPlugin.prototype.initialize = function (iterations) {
  17998. this._world = new OIMO.World();
  17999. this._world.clear();
  18000. };
  18001. OimoJSPlugin.prototype.setGravity = function (gravity) {
  18002. this._world.gravity = gravity;
  18003. };
  18004. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  18005. var body = null;
  18006. this.unregisterMesh(mesh);
  18007. mesh.computeWorldMatrix(true);
  18008. var initialRotation = null;
  18009. if (mesh.rotationQuaternion) {
  18010. initialRotation = mesh.rotationQuaternion.clone();
  18011. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  18012. mesh.computeWorldMatrix(true);
  18013. }
  18014. var bbox = mesh.getBoundingInfo().boundingBox;
  18015. // The delta between the mesh position and the mesh bounding box center
  18016. var deltaPosition = mesh.position.subtract(bbox.center);
  18017. // Transform delta position with the rotation
  18018. if (initialRotation) {
  18019. var m = new BABYLON.Matrix();
  18020. initialRotation.toRotationMatrix(m);
  18021. deltaPosition = BABYLON.Vector3.TransformCoordinates(deltaPosition, m);
  18022. }
  18023. switch (impostor) {
  18024. case BABYLON.PhysicsEngine.SphereImpostor:
  18025. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  18026. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  18027. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  18028. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  18029. body = new OIMO.Body({
  18030. type: 'sphere',
  18031. size: [size],
  18032. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  18033. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  18034. move: options.mass != 0,
  18035. config: [options.mass, options.friction, options.restitution],
  18036. world: this._world
  18037. });
  18038. break;
  18039. case BABYLON.PhysicsEngine.PlaneImpostor:
  18040. case BABYLON.PhysicsEngine.CylinderImpostor:
  18041. case BABYLON.PhysicsEngine.BoxImpostor:
  18042. var min = bbox.minimumWorld;
  18043. var max = bbox.maximumWorld;
  18044. var box = max.subtract(min);
  18045. var sizeX = this._checkWithEpsilon(box.x);
  18046. var sizeY = this._checkWithEpsilon(box.y);
  18047. var sizeZ = this._checkWithEpsilon(box.z);
  18048. body = new OIMO.Body({
  18049. type: 'box',
  18050. size: [sizeX, sizeY, sizeZ],
  18051. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  18052. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  18053. move: options.mass != 0,
  18054. config: [options.mass, options.friction, options.restitution],
  18055. world: this._world
  18056. });
  18057. break;
  18058. }
  18059. //If quaternion was set as the rotation of the object
  18060. if (initialRotation) {
  18061. //We have to access the rigid body's properties to set the quaternion.
  18062. //The setQuaternion function of Oimo only sets the newOrientation that is only set after an impulse is given or a collision.
  18063. body.body.orientation = new OIMO.Quat(initialRotation.w, initialRotation.x, initialRotation.y, initialRotation.z);
  18064. //update the internal rotation matrix
  18065. body.body.syncShapes();
  18066. }
  18067. this._registeredMeshes.push({
  18068. mesh: mesh,
  18069. body: body,
  18070. delta: deltaPosition
  18071. });
  18072. return body;
  18073. };
  18074. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  18075. var types = [], sizes = [], positions = [], rotations = [];
  18076. var initialMesh = parts[0].mesh;
  18077. for (var index = 0; index < parts.length; index++) {
  18078. var part = parts[index];
  18079. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  18080. types.push(bodyParameters.type);
  18081. sizes.push.apply(sizes, bodyParameters.size);
  18082. positions.push.apply(positions, bodyParameters.pos);
  18083. rotations.push.apply(rotations, bodyParameters.rot);
  18084. }
  18085. var body = new OIMO.Body({
  18086. type: types,
  18087. size: sizes,
  18088. pos: positions,
  18089. rot: rotations,
  18090. move: options.mass != 0,
  18091. config: [options.mass, options.friction, options.restitution],
  18092. world: this._world
  18093. });
  18094. this._registeredMeshes.push({
  18095. mesh: initialMesh,
  18096. body: body
  18097. });
  18098. return body;
  18099. };
  18100. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  18101. var bodyParameters = null;
  18102. var mesh = part.mesh;
  18103. // We need the bounding box/sphere info to compute the physics body
  18104. mesh.computeWorldMatrix();
  18105. switch (part.impostor) {
  18106. case BABYLON.PhysicsEngine.SphereImpostor:
  18107. var bbox = mesh.getBoundingInfo().boundingBox;
  18108. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  18109. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  18110. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  18111. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  18112. bodyParameters = {
  18113. type: 'sphere',
  18114. /* bug with oimo : sphere needs 3 sizes in this case */
  18115. size: [size, -1, -1],
  18116. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  18117. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  18118. };
  18119. break;
  18120. case BABYLON.PhysicsEngine.PlaneImpostor:
  18121. case BABYLON.PhysicsEngine.BoxImpostor:
  18122. bbox = mesh.getBoundingInfo().boundingBox;
  18123. var min = bbox.minimumWorld;
  18124. var max = bbox.maximumWorld;
  18125. var box = max.subtract(min);
  18126. var sizeX = this._checkWithEpsilon(box.x);
  18127. var sizeY = this._checkWithEpsilon(box.y);
  18128. var sizeZ = this._checkWithEpsilon(box.z);
  18129. var relativePosition = mesh.position;
  18130. bodyParameters = {
  18131. type: 'box',
  18132. size: [sizeX, sizeY, sizeZ],
  18133. pos: [relativePosition.x, relativePosition.y, relativePosition.z],
  18134. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  18135. };
  18136. break;
  18137. }
  18138. return bodyParameters;
  18139. };
  18140. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  18141. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18142. var registeredMesh = this._registeredMeshes[index];
  18143. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  18144. if (registeredMesh.body) {
  18145. this._world.removeRigidBody(registeredMesh.body.body);
  18146. this._unbindBody(registeredMesh.body);
  18147. }
  18148. this._registeredMeshes.splice(index, 1);
  18149. return;
  18150. }
  18151. }
  18152. };
  18153. OimoJSPlugin.prototype._unbindBody = function (body) {
  18154. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18155. var registeredMesh = this._registeredMeshes[index];
  18156. if (registeredMesh.body === body) {
  18157. registeredMesh.body = null;
  18158. }
  18159. }
  18160. };
  18161. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  18162. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18163. var registeredMesh = this._registeredMeshes[index];
  18164. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  18165. // Get object mass to have a behaviour similar to cannon.js
  18166. var mass = registeredMesh.body.body.massInfo.mass;
  18167. // The force is scaled with the mass of object
  18168. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  18169. return;
  18170. }
  18171. }
  18172. };
  18173. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  18174. var body1 = null, body2 = null;
  18175. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18176. var registeredMesh = this._registeredMeshes[index];
  18177. if (registeredMesh.mesh === mesh1) {
  18178. body1 = registeredMesh.body.body;
  18179. }
  18180. else if (registeredMesh.mesh === mesh2) {
  18181. body2 = registeredMesh.body.body;
  18182. }
  18183. }
  18184. if (!body1 || !body2) {
  18185. return false;
  18186. }
  18187. if (!options) {
  18188. options = {};
  18189. }
  18190. new OIMO.Link({
  18191. type: options.type,
  18192. body1: body1,
  18193. body2: body2,
  18194. min: options.min,
  18195. max: options.max,
  18196. axe1: options.axe1,
  18197. axe2: options.axe2,
  18198. pos1: [pivot1.x, pivot1.y, pivot1.z],
  18199. pos2: [pivot2.x, pivot2.y, pivot2.z],
  18200. collision: options.collision,
  18201. spring: options.spring,
  18202. world: this._world
  18203. });
  18204. return true;
  18205. };
  18206. OimoJSPlugin.prototype.dispose = function () {
  18207. this._world.clear();
  18208. while (this._registeredMeshes.length) {
  18209. this.unregisterMesh(this._registeredMeshes[0].mesh);
  18210. }
  18211. };
  18212. OimoJSPlugin.prototype.isSupported = function () {
  18213. return OIMO !== undefined;
  18214. };
  18215. OimoJSPlugin.prototype._getLastShape = function (body) {
  18216. var lastShape = body.shapes;
  18217. while (lastShape.next) {
  18218. lastShape = lastShape.next;
  18219. }
  18220. return lastShape;
  18221. };
  18222. OimoJSPlugin.prototype.runOneStep = function (time) {
  18223. this._world.step();
  18224. // Update the position of all registered meshes
  18225. var i = this._registeredMeshes.length;
  18226. var m;
  18227. while (i--) {
  18228. var body = this._registeredMeshes[i].body.body;
  18229. var mesh = this._registeredMeshes[i].mesh;
  18230. var delta = this._registeredMeshes[i].delta;
  18231. if (!body.sleeping) {
  18232. if (body.shapes.next) {
  18233. var parentShape = this._getLastShape(body);
  18234. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  18235. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  18236. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  18237. var mtx = BABYLON.Matrix.FromArray(body.getMatrix());
  18238. if (!mesh.rotationQuaternion) {
  18239. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  18240. }
  18241. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  18242. mesh.computeWorldMatrix();
  18243. }
  18244. else {
  18245. m = body.getMatrix();
  18246. mtx = BABYLON.Matrix.FromArray(m);
  18247. // Body position
  18248. var bodyX = mtx.m[12], bodyY = mtx.m[13], bodyZ = mtx.m[14];
  18249. if (!delta) {
  18250. mesh.position.x = bodyX;
  18251. mesh.position.y = bodyY;
  18252. mesh.position.z = bodyZ;
  18253. }
  18254. else {
  18255. mesh.position.x = bodyX + delta.x;
  18256. mesh.position.y = bodyY + delta.y;
  18257. mesh.position.z = bodyZ + delta.z;
  18258. }
  18259. if (!mesh.rotationQuaternion) {
  18260. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  18261. }
  18262. BABYLON.Quaternion.FromRotationMatrixToRef(mtx, mesh.rotationQuaternion);
  18263. mesh.computeWorldMatrix();
  18264. }
  18265. }
  18266. }
  18267. };
  18268. return OimoJSPlugin;
  18269. })();
  18270. BABYLON.OimoJSPlugin = OimoJSPlugin;
  18271. })(BABYLON || (BABYLON = {}));
  18272. //# sourceMappingURL=babylon.oimoJSPlugin.js.mapvar BABYLON;
  18273. (function (BABYLON) {
  18274. var PhysicsEngine = (function () {
  18275. function PhysicsEngine(plugin) {
  18276. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  18277. }
  18278. PhysicsEngine.prototype._initialize = function (gravity) {
  18279. this._currentPlugin.initialize();
  18280. this._setGravity(gravity);
  18281. };
  18282. PhysicsEngine.prototype._runOneStep = function (delta) {
  18283. if (delta > 0.1) {
  18284. delta = 0.1;
  18285. }
  18286. else if (delta <= 0) {
  18287. delta = 1.0 / 60.0;
  18288. }
  18289. this._currentPlugin.runOneStep(delta);
  18290. };
  18291. PhysicsEngine.prototype._setGravity = function (gravity) {
  18292. this.gravity = gravity || new BABYLON.Vector3(0, -9.82, 0);
  18293. this._currentPlugin.setGravity(this.gravity);
  18294. };
  18295. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  18296. return this._currentPlugin.registerMesh(mesh, impostor, options);
  18297. };
  18298. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  18299. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  18300. };
  18301. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  18302. this._currentPlugin.unregisterMesh(mesh);
  18303. };
  18304. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  18305. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  18306. };
  18307. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  18308. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  18309. };
  18310. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  18311. this._currentPlugin.updateBodyPosition(mesh);
  18312. };
  18313. PhysicsEngine.prototype.dispose = function () {
  18314. this._currentPlugin.dispose();
  18315. };
  18316. PhysicsEngine.prototype.isSupported = function () {
  18317. return this._currentPlugin.isSupported();
  18318. };
  18319. // Statics
  18320. PhysicsEngine.NoImpostor = 0;
  18321. PhysicsEngine.SphereImpostor = 1;
  18322. PhysicsEngine.BoxImpostor = 2;
  18323. PhysicsEngine.PlaneImpostor = 3;
  18324. PhysicsEngine.MeshImpostor = 4;
  18325. PhysicsEngine.CapsuleImpostor = 5;
  18326. PhysicsEngine.ConeImpostor = 6;
  18327. PhysicsEngine.CylinderImpostor = 7;
  18328. PhysicsEngine.ConvexHullImpostor = 8;
  18329. PhysicsEngine.Epsilon = 0.001;
  18330. return PhysicsEngine;
  18331. })();
  18332. BABYLON.PhysicsEngine = PhysicsEngine;
  18333. })(BABYLON || (BABYLON = {}));
  18334. //# sourceMappingURL=babylon.physicsEngine.js.mapvar BABYLON;
  18335. (function (BABYLON) {
  18336. var serializeLight = function (light) {
  18337. var serializationObject = {};
  18338. serializationObject.name = light.name;
  18339. serializationObject.id = light.id;
  18340. serializationObject.tags = BABYLON.Tags.GetTags(light);
  18341. if (light instanceof BABYLON.PointLight) {
  18342. serializationObject.type = 0;
  18343. serializationObject.position = light.position.asArray();
  18344. }
  18345. else if (light instanceof BABYLON.DirectionalLight) {
  18346. serializationObject.type = 1;
  18347. var directionalLight = light;
  18348. serializationObject.position = directionalLight.position.asArray();
  18349. serializationObject.direction = directionalLight.direction.asArray();
  18350. }
  18351. else if (light instanceof BABYLON.SpotLight) {
  18352. serializationObject.type = 2;
  18353. var spotLight = light;
  18354. serializationObject.position = spotLight.position.asArray();
  18355. serializationObject.direction = spotLight.position.asArray();
  18356. serializationObject.angle = spotLight.angle;
  18357. serializationObject.exponent = spotLight.exponent;
  18358. }
  18359. else if (light instanceof BABYLON.HemisphericLight) {
  18360. serializationObject.type = 3;
  18361. var hemisphericLight = light;
  18362. serializationObject.direction = hemisphericLight.direction.asArray();
  18363. serializationObject.groundColor = hemisphericLight.groundColor.asArray();
  18364. }
  18365. if (light.intensity) {
  18366. serializationObject.intensity = light.intensity;
  18367. }
  18368. serializationObject.range = light.range;
  18369. serializationObject.diffuse = light.diffuse.asArray();
  18370. serializationObject.specular = light.specular.asArray();
  18371. return serializationObject;
  18372. };
  18373. var serializeFresnelParameter = function (fresnelParameter) {
  18374. var serializationObject = {};
  18375. serializationObject.isEnabled = fresnelParameter.isEnabled;
  18376. serializationObject.leftColor = fresnelParameter.leftColor;
  18377. serializationObject.rightColor = fresnelParameter.rightColor;
  18378. serializationObject.bias = fresnelParameter.bias;
  18379. serializationObject.power = fresnelParameter.power;
  18380. return serializationObject;
  18381. };
  18382. var appendAnimations = function (source, destination) {
  18383. if (source.animations) {
  18384. destination.animations = [];
  18385. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  18386. var animation = source.animations[animationIndex];
  18387. destination.animations.push(serializeAnimation(animation));
  18388. }
  18389. }
  18390. };
  18391. var serializeCamera = function (camera) {
  18392. var serializationObject = {};
  18393. serializationObject.name = camera.name;
  18394. serializationObject.tags = BABYLON.Tags.GetTags(camera);
  18395. serializationObject.id = camera.id;
  18396. serializationObject.position = camera.position.asArray();
  18397. // Parent
  18398. if (camera.parent) {
  18399. serializationObject.parentId = camera.parent.id;
  18400. }
  18401. serializationObject.fov = camera.fov;
  18402. serializationObject.minZ = camera.minZ;
  18403. serializationObject.maxZ = camera.maxZ;
  18404. serializationObject.inertia = camera.inertia;
  18405. //setting the type
  18406. if (camera instanceof BABYLON.FreeCamera) {
  18407. serializationObject.type = "FreeCamera";
  18408. }
  18409. else if (camera instanceof BABYLON.ArcRotateCamera) {
  18410. serializationObject.type = "ArcRotateCamera";
  18411. }
  18412. else if (camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  18413. serializationObject.type = "AnaglyphArcRotateCamera";
  18414. }
  18415. else if (camera instanceof BABYLON.GamepadCamera) {
  18416. serializationObject.type = "GamepadCamera";
  18417. }
  18418. else if (camera instanceof BABYLON.AnaglyphFreeCamera) {
  18419. serializationObject.type = "AnaglyphFreeCamera";
  18420. }
  18421. else if (camera instanceof BABYLON.DeviceOrientationCamera) {
  18422. serializationObject.type = "DeviceOrientationCamera";
  18423. }
  18424. else if (camera instanceof BABYLON.FollowCamera) {
  18425. serializationObject.type = "FollowCamera";
  18426. }
  18427. else if (camera instanceof BABYLON.OculusCamera) {
  18428. serializationObject.type = "OculusCamera";
  18429. }
  18430. else if (camera instanceof BABYLON.OculusGamepadCamera) {
  18431. serializationObject.type = "OculusGamepadCamera";
  18432. }
  18433. else if (camera instanceof BABYLON.TouchCamera) {
  18434. serializationObject.type = "TouchCamera";
  18435. }
  18436. else if (camera instanceof BABYLON.VirtualJoysticksCamera) {
  18437. serializationObject.type = "VirtualJoysticksCamera";
  18438. }
  18439. else if (camera instanceof BABYLON.WebVRCamera) {
  18440. serializationObject.type = "WebVRCamera";
  18441. }
  18442. else if (camera instanceof BABYLON.VRDeviceOrientationCamera) {
  18443. serializationObject.type = "VRDeviceOrientationCamera";
  18444. }
  18445. //special properties of specific cameras
  18446. if (camera instanceof BABYLON.ArcRotateCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  18447. var arcCamera = camera;
  18448. serializationObject.alpha = arcCamera.alpha;
  18449. serializationObject.beta = arcCamera.beta;
  18450. serializationObject.radius = arcCamera.radius;
  18451. if (arcCamera.target && arcCamera.target.id) {
  18452. serializationObject.lockedTargetId = arcCamera.target.id;
  18453. }
  18454. }
  18455. else if (camera instanceof BABYLON.FollowCamera) {
  18456. var followCam = camera;
  18457. serializationObject.radius = followCam.radius;
  18458. serializationObject.heightOffset = followCam.heightOffset;
  18459. serializationObject.rotationOffset = followCam.rotationOffset;
  18460. }
  18461. else if (camera instanceof BABYLON.AnaglyphFreeCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  18462. //eye space is a private member and can only be access like this. Without changing the implementation this is the best way to get it.
  18463. if (camera['_eyeSpace'] !== undefined) {
  18464. serializationObject.eye_space = BABYLON.Tools.ToDegrees(camera['_eyeSpace']);
  18465. }
  18466. }
  18467. //general properties that not all cameras have. The [] is due to typescript's type safety
  18468. if (camera['speed'] !== undefined) {
  18469. serializationObject.speed = camera['speed'];
  18470. }
  18471. if (camera['target'] && camera['target'] instanceof BABYLON.Vector3) {
  18472. serializationObject.target = camera['target'].asArray();
  18473. }
  18474. // Target
  18475. if (camera['rotation'] && camera['rotation'] instanceof BABYLON.Vector3) {
  18476. serializationObject.rotation = camera['rotation'].asArray();
  18477. }
  18478. // Locked target
  18479. if (camera['lockedTarget'] && camera['lockedTarget'].id) {
  18480. serializationObject.lockedTargetId = camera['lockedTarget'].id;
  18481. }
  18482. serializationObject.checkCollisions = camera['checkCollisions'] || false;
  18483. serializationObject.applyGravity = camera['applyGravity'] || false;
  18484. if (camera['ellipsoid']) {
  18485. serializationObject.ellipsoid = camera['ellipsoid'].asArray();
  18486. }
  18487. // Animations
  18488. appendAnimations(camera, serializationObject);
  18489. // Layer mask
  18490. serializationObject.layerMask = camera.layerMask;
  18491. return serializationObject;
  18492. };
  18493. var serializeAnimation = function (animation) {
  18494. var serializationObject = {};
  18495. serializationObject.name = animation.name;
  18496. serializationObject.property = animation.targetProperty;
  18497. serializationObject.framePerSecond = animation.framePerSecond;
  18498. serializationObject.dataType = animation.dataType;
  18499. serializationObject.loopBehavior = animation.loopMode;
  18500. var dataType = animation.dataType;
  18501. serializationObject.keys = [];
  18502. var keys = animation.getKeys();
  18503. for (var index = 0; index < keys.length; index++) {
  18504. var animationKey = keys[index];
  18505. var key = {};
  18506. key.frame = animationKey.frame;
  18507. switch (dataType) {
  18508. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  18509. key.values = [animationKey.value];
  18510. break;
  18511. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  18512. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  18513. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  18514. key.values = animationKey.value.asArray();
  18515. break;
  18516. }
  18517. serializationObject.keys.push(key);
  18518. }
  18519. return serializationObject;
  18520. };
  18521. var serializeMultiMaterial = function (material) {
  18522. var serializationObject = {};
  18523. serializationObject.name = material.name;
  18524. serializationObject.id = material.id;
  18525. serializationObject.tags = BABYLON.Tags.GetTags(material);
  18526. serializationObject.materials = [];
  18527. for (var matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
  18528. var subMat = material.subMaterials[matIndex];
  18529. if (subMat) {
  18530. serializationObject.materials.push(subMat.id);
  18531. }
  18532. else {
  18533. serializationObject.materials.push(null);
  18534. }
  18535. }
  18536. return serializationObject;
  18537. };
  18538. var serializeMaterial = function (material) {
  18539. var serializationObject = {};
  18540. serializationObject.name = material.name;
  18541. serializationObject.ambient = material.ambientColor.asArray();
  18542. serializationObject.diffuse = material.diffuseColor.asArray();
  18543. serializationObject.specular = material.specularColor.asArray();
  18544. serializationObject.specularPower = material.specularPower;
  18545. serializationObject.emissive = material.emissiveColor.asArray();
  18546. serializationObject.alpha = material.alpha;
  18547. serializationObject.id = material.id;
  18548. serializationObject.tags = BABYLON.Tags.GetTags(material);
  18549. serializationObject.backFaceCulling = material.backFaceCulling;
  18550. if (material.diffuseTexture) {
  18551. serializationObject.diffuseTexture = serializeTexture(material.diffuseTexture);
  18552. }
  18553. if (material.diffuseFresnelParameters) {
  18554. serializationObject.diffuseFresnelParameters = serializeFresnelParameter(material.diffuseFresnelParameters);
  18555. }
  18556. if (material.ambientTexture) {
  18557. serializationObject.ambientTexture = serializeTexture(material.ambientTexture);
  18558. }
  18559. if (material.opacityTexture) {
  18560. serializationObject.opacityTexture = serializeTexture(material.opacityTexture);
  18561. }
  18562. if (material.opacityFresnelParameters) {
  18563. serializationObject.opacityFresnelParameters = serializeFresnelParameter(material.opacityFresnelParameters);
  18564. }
  18565. if (material.reflectionTexture) {
  18566. serializationObject.reflectionTexture = serializeTexture(material.reflectionTexture);
  18567. }
  18568. if (material.reflectionFresnelParameters) {
  18569. serializationObject.reflectionFresnelParameters = serializeFresnelParameter(material.reflectionFresnelParameters);
  18570. }
  18571. if (material.emissiveTexture) {
  18572. serializationObject.emissiveTexture = serializeTexture(material.emissiveTexture);
  18573. }
  18574. if (material.emissiveFresnelParameters) {
  18575. serializationObject.emissiveFresnelParameters = serializeFresnelParameter(material.emissiveFresnelParameters);
  18576. }
  18577. if (material.specularTexture) {
  18578. serializationObject.specularTexture = serializeTexture(material.specularTexture);
  18579. }
  18580. if (material.bumpTexture) {
  18581. serializationObject.bumpTexture = serializeTexture(material.bumpTexture);
  18582. }
  18583. return serializationObject;
  18584. };
  18585. var serializeTexture = function (texture) {
  18586. var serializationObject = {};
  18587. if (!texture.name) {
  18588. return null;
  18589. }
  18590. if (texture instanceof BABYLON.CubeTexture) {
  18591. serializationObject.name = texture.name;
  18592. serializationObject.hasAlpha = texture.hasAlpha;
  18593. serializationObject.level = texture.level;
  18594. serializationObject.coordinatesMode = texture.coordinatesMode;
  18595. return serializationObject;
  18596. }
  18597. if (texture instanceof BABYLON.MirrorTexture) {
  18598. var mirrorTexture = texture;
  18599. serializationObject.renderTargetSize = mirrorTexture.getRenderSize();
  18600. serializationObject.renderList = [];
  18601. for (var index = 0; index < mirrorTexture.renderList.length; index++) {
  18602. serializationObject.renderList.push(mirrorTexture.renderList[index].id);
  18603. }
  18604. serializationObject.mirrorPlane = mirrorTexture.mirrorPlane.asArray();
  18605. }
  18606. else if (texture instanceof BABYLON.RenderTargetTexture) {
  18607. var renderTargetTexture = texture;
  18608. serializationObject.renderTargetSize = renderTargetTexture.getRenderSize();
  18609. serializationObject.renderList = [];
  18610. for (index = 0; index < renderTargetTexture.renderList.length; index++) {
  18611. serializationObject.renderList.push(renderTargetTexture.renderList[index].id);
  18612. }
  18613. }
  18614. var regularTexture = texture;
  18615. serializationObject.name = texture.name;
  18616. serializationObject.hasAlpha = texture.hasAlpha;
  18617. serializationObject.level = texture.level;
  18618. serializationObject.coordinatesIndex = texture.coordinatesIndex;
  18619. serializationObject.coordinatesMode = texture.coordinatesMode;
  18620. serializationObject.uOffset = regularTexture.uOffset;
  18621. serializationObject.vOffset = regularTexture.vOffset;
  18622. serializationObject.uScale = regularTexture.uScale;
  18623. serializationObject.vScale = regularTexture.vScale;
  18624. serializationObject.uAng = regularTexture.uAng;
  18625. serializationObject.vAng = regularTexture.vAng;
  18626. serializationObject.wAng = regularTexture.wAng;
  18627. serializationObject.wrapU = texture.wrapU;
  18628. serializationObject.wrapV = texture.wrapV;
  18629. // Animations
  18630. appendAnimations(texture, serializationObject);
  18631. return serializationObject;
  18632. };
  18633. var serializeSkeleton = function (skeleton) {
  18634. var serializationObject = {};
  18635. serializationObject.name = skeleton.name;
  18636. serializationObject.id = skeleton.id;
  18637. serializationObject.bones = [];
  18638. for (var index = 0; index < skeleton.bones.length; index++) {
  18639. var bone = skeleton.bones[index];
  18640. var serializedBone = {
  18641. parentBoneIndex: bone.getParent() ? skeleton.bones.indexOf(bone.getParent()) : -1,
  18642. name: bone.name,
  18643. matrix: bone.getLocalMatrix().toArray()
  18644. };
  18645. serializationObject.bones.push(serializedBone);
  18646. if (bone.animations && bone.animations.length > 0) {
  18647. serializedBone.animation = serializeAnimation(bone.animations[0]);
  18648. }
  18649. }
  18650. return serializationObject;
  18651. };
  18652. var serializeParticleSystem = function (particleSystem) {
  18653. var serializationObject = {};
  18654. serializationObject.emitterId = particleSystem.emitter.id;
  18655. serializationObject.capacity = particleSystem.getCapacity();
  18656. if (particleSystem.particleTexture) {
  18657. serializationObject.textureName = particleSystem.particleTexture.name;
  18658. }
  18659. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  18660. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  18661. serializationObject.minSize = particleSystem.minSize;
  18662. serializationObject.maxSize = particleSystem.maxSize;
  18663. serializationObject.minLifeTime = particleSystem.minLifeTime;
  18664. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  18665. serializationObject.emitRate = particleSystem.emitRate;
  18666. serializationObject.minEmitBox = particleSystem.minEmitBox.asArray();
  18667. serializationObject.maxEmitBox = particleSystem.maxEmitBox.asArray();
  18668. serializationObject.gravity = particleSystem.gravity.asArray();
  18669. serializationObject.direction1 = particleSystem.direction1.asArray();
  18670. serializationObject.direction2 = particleSystem.direction2.asArray();
  18671. serializationObject.color1 = particleSystem.color1.asArray();
  18672. serializationObject.color2 = particleSystem.color2.asArray();
  18673. serializationObject.colorDead = particleSystem.colorDead.asArray();
  18674. serializationObject.updateSpeed = particleSystem.updateSpeed;
  18675. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  18676. serializationObject.textureMask = particleSystem.textureMask.asArray();
  18677. serializationObject.blendMode = particleSystem.blendMode;
  18678. return serializationObject;
  18679. };
  18680. var serializeLensFlareSystem = function (lensFlareSystem) {
  18681. var serializationObject = {};
  18682. serializationObject.emitterId = lensFlareSystem.getEmitter().id;
  18683. serializationObject.borderLimit = lensFlareSystem.borderLimit;
  18684. serializationObject.flares = [];
  18685. for (var index = 0; index < lensFlareSystem.lensFlares.length; index++) {
  18686. var flare = lensFlareSystem.lensFlares[index];
  18687. serializationObject.flares.push({
  18688. size: flare.size,
  18689. position: flare.position,
  18690. color: flare.color.asArray(),
  18691. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  18692. });
  18693. }
  18694. return serializationObject;
  18695. };
  18696. var serializeShadowGenerator = function (light) {
  18697. var serializationObject = {};
  18698. var shadowGenerator = light.getShadowGenerator();
  18699. serializationObject.lightId = light.id;
  18700. serializationObject.mapSize = shadowGenerator.getShadowMap().getRenderSize();
  18701. serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
  18702. serializationObject.usePoissonSampling = shadowGenerator.usePoissonSampling;
  18703. serializationObject.renderList = [];
  18704. for (var meshIndex = 0; meshIndex < shadowGenerator.getShadowMap().renderList.length; meshIndex++) {
  18705. var mesh = shadowGenerator.getShadowMap().renderList[meshIndex];
  18706. serializationObject.renderList.push(mesh.id);
  18707. }
  18708. return serializationObject;
  18709. };
  18710. var serializedGeometries = [];
  18711. var serializeGeometry = function (geometry, serializationGeometries) {
  18712. if (serializedGeometries[geometry.id]) {
  18713. return;
  18714. }
  18715. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  18716. serializationGeometries.boxes.push(serializeBox(geometry));
  18717. }
  18718. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  18719. serializationGeometries.spheres.push(serializeSphere(geometry));
  18720. }
  18721. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  18722. serializationGeometries.cylinders.push(serializeCylinder(geometry));
  18723. }
  18724. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  18725. serializationGeometries.toruses.push(serializeTorus(geometry));
  18726. }
  18727. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  18728. serializationGeometries.grounds.push(serializeGround(geometry));
  18729. }
  18730. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  18731. serializationGeometries.planes.push(serializePlane(geometry));
  18732. }
  18733. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  18734. serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
  18735. }
  18736. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  18737. throw new Error("Unknow primitive type");
  18738. }
  18739. else {
  18740. serializationGeometries.vertexData.push(serializeVertexData(geometry));
  18741. }
  18742. serializedGeometries[geometry.id] = true;
  18743. };
  18744. var serializeGeometryBase = function (geometry) {
  18745. var serializationObject = {};
  18746. serializationObject.id = geometry.id;
  18747. if (BABYLON.Tags.HasTags(geometry)) {
  18748. serializationObject.tags = BABYLON.Tags.GetTags(geometry);
  18749. }
  18750. return serializationObject;
  18751. };
  18752. var serializeVertexData = function (vertexData) {
  18753. var serializationObject = serializeGeometryBase(vertexData);
  18754. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  18755. serializationObject.positions = vertexData.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18756. }
  18757. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18758. serializationObject.normals = vertexData.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18759. }
  18760. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  18761. serializationObject.uvs = vertexData.getVerticesData(BABYLON.VertexBuffer.UVKind);
  18762. }
  18763. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  18764. serializationObject.uvs2 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  18765. }
  18766. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  18767. serializationObject.colors = vertexData.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  18768. }
  18769. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  18770. serializationObject.matricesIndices = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  18771. serializationObject.matricesIndices._isExpanded = true;
  18772. }
  18773. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  18774. serializationObject.matricesWeights = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  18775. }
  18776. serializationObject.indices = vertexData.getIndices();
  18777. return serializationObject;
  18778. };
  18779. var serializePrimitive = function (primitive) {
  18780. var serializationObject = serializeGeometryBase(primitive);
  18781. serializationObject.canBeRegenerated = primitive.canBeRegenerated();
  18782. return serializationObject;
  18783. };
  18784. var serializeBox = function (box) {
  18785. var serializationObject = serializePrimitive(box);
  18786. serializationObject.size = box.size;
  18787. return serializationObject;
  18788. };
  18789. var serializeSphere = function (sphere) {
  18790. var serializationObject = serializePrimitive(sphere);
  18791. serializationObject.segments = sphere.segments;
  18792. serializationObject.diameter = sphere.diameter;
  18793. return serializationObject;
  18794. };
  18795. var serializeCylinder = function (cylinder) {
  18796. var serializationObject = serializePrimitive(cylinder);
  18797. serializationObject.height = cylinder.height;
  18798. serializationObject.diameterTop = cylinder.diameterTop;
  18799. serializationObject.diameterBottom = cylinder.diameterBottom;
  18800. serializationObject.tessellation = cylinder.tessellation;
  18801. return serializationObject;
  18802. };
  18803. var serializeTorus = function (torus) {
  18804. var serializationObject = serializePrimitive(torus);
  18805. serializationObject.diameter = torus.diameter;
  18806. serializationObject.thickness = torus.thickness;
  18807. serializationObject.tessellation = torus.tessellation;
  18808. return serializationObject;
  18809. };
  18810. var serializeGround = function (ground) {
  18811. var serializationObject = serializePrimitive(ground);
  18812. serializationObject.width = ground.width;
  18813. serializationObject.height = ground.height;
  18814. serializationObject.subdivisions = ground.subdivisions;
  18815. return serializationObject;
  18816. };
  18817. var serializePlane = function (plane) {
  18818. var serializationObject = serializePrimitive(plane);
  18819. serializationObject.size = plane.size;
  18820. return serializationObject;
  18821. };
  18822. var serializeTorusKnot = function (torusKnot) {
  18823. var serializationObject = serializePrimitive(torusKnot);
  18824. serializationObject.radius = torusKnot.radius;
  18825. serializationObject.tube = torusKnot.tube;
  18826. serializationObject.radialSegments = torusKnot.radialSegments;
  18827. serializationObject.tubularSegments = torusKnot.tubularSegments;
  18828. serializationObject.p = torusKnot.p;
  18829. serializationObject.q = torusKnot.q;
  18830. return serializationObject;
  18831. };
  18832. var serializeMesh = function (mesh, serializationScene) {
  18833. var serializationObject = {};
  18834. serializationObject.name = mesh.name;
  18835. serializationObject.id = mesh.id;
  18836. if (BABYLON.Tags.HasTags(mesh)) {
  18837. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  18838. }
  18839. serializationObject.position = mesh.position.asArray();
  18840. if (mesh.rotationQuaternion) {
  18841. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  18842. }
  18843. else if (mesh.rotation) {
  18844. serializationObject.rotation = mesh.rotation.asArray();
  18845. }
  18846. serializationObject.scaling = mesh.scaling.asArray();
  18847. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  18848. serializationObject.isEnabled = mesh.isEnabled();
  18849. serializationObject.isVisible = mesh.isVisible;
  18850. serializationObject.infiniteDistance = mesh.infiniteDistance;
  18851. serializationObject.pickable = mesh.isPickable;
  18852. serializationObject.receiveShadows = mesh.receiveShadows;
  18853. serializationObject.billboardMode = mesh.billboardMode;
  18854. serializationObject.visibility = mesh.visibility;
  18855. serializationObject.checkCollisions = mesh.checkCollisions;
  18856. // Parent
  18857. if (mesh.parent) {
  18858. serializationObject.parentId = mesh.parent.id;
  18859. }
  18860. // Geometry
  18861. var geometry = mesh._geometry;
  18862. if (geometry) {
  18863. var geometryId = geometry.id;
  18864. serializationObject.geometryId = geometryId;
  18865. if (!mesh.getScene().getGeometryByID(geometryId)) {
  18866. // 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
  18867. serializeGeometry(geometry, serializationScene.geometries);
  18868. }
  18869. // SubMeshes
  18870. serializationObject.subMeshes = [];
  18871. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  18872. var subMesh = mesh.subMeshes[subIndex];
  18873. serializationObject.subMeshes.push({
  18874. materialIndex: subMesh.materialIndex,
  18875. verticesStart: subMesh.verticesStart,
  18876. verticesCount: subMesh.verticesCount,
  18877. indexStart: subMesh.indexStart,
  18878. indexCount: subMesh.indexCount
  18879. });
  18880. }
  18881. }
  18882. // Material
  18883. if (mesh.material) {
  18884. serializationObject.materialId = mesh.material.id;
  18885. }
  18886. else {
  18887. mesh.material = null;
  18888. }
  18889. // Skeleton
  18890. if (mesh.skeleton) {
  18891. serializationObject.skeletonId = mesh.skeleton.id;
  18892. }
  18893. // Physics
  18894. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  18895. serializationObject.physicsMass = mesh.getPhysicsMass();
  18896. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  18897. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  18898. switch (mesh.getPhysicsImpostor()) {
  18899. case BABYLON.PhysicsEngine.BoxImpostor:
  18900. serializationObject.physicsImpostor = 1;
  18901. break;
  18902. case BABYLON.PhysicsEngine.SphereImpostor:
  18903. serializationObject.physicsImpostor = 2;
  18904. break;
  18905. }
  18906. }
  18907. // Instances
  18908. serializationObject.instances = [];
  18909. for (var index = 0; index < mesh.instances.length; index++) {
  18910. var instance = mesh.instances[index];
  18911. var serializationInstance = {
  18912. name: instance.name,
  18913. position: instance.position,
  18914. rotation: instance.rotation,
  18915. rotationQuaternion: instance.rotationQuaternion,
  18916. scaling: instance.scaling
  18917. };
  18918. serializationObject.instances.push(serializationInstance);
  18919. // Animations
  18920. appendAnimations(instance, serializationInstance);
  18921. }
  18922. // Animations
  18923. appendAnimations(mesh, serializationObject);
  18924. // Layer mask
  18925. serializationObject.layerMask = mesh.layerMask;
  18926. return serializationObject;
  18927. };
  18928. var SceneSerializer = (function () {
  18929. function SceneSerializer() {
  18930. }
  18931. SceneSerializer.Serialize = function (scene) {
  18932. var serializationObject = {};
  18933. // Scene
  18934. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  18935. serializationObject.autoClear = scene.autoClear;
  18936. serializationObject.clearColor = scene.clearColor.asArray();
  18937. serializationObject.ambientColor = scene.ambientColor.asArray();
  18938. serializationObject.gravity = scene.gravity.asArray();
  18939. // Fog
  18940. if (scene.fogMode && scene.fogMode !== 0) {
  18941. serializationObject.fogMode = scene.fogMode;
  18942. serializationObject.fogColor = scene.fogColor.asArray();
  18943. serializationObject.fogStart = scene.fogStart;
  18944. serializationObject.fogEnd = scene.fogEnd;
  18945. serializationObject.fogDensity = scene.fogDensity;
  18946. }
  18947. // Lights
  18948. serializationObject.lights = [];
  18949. for (var index = 0; index < scene.lights.length; index++) {
  18950. var light = scene.lights[index];
  18951. serializationObject.lights.push(serializeLight(light));
  18952. }
  18953. // Cameras
  18954. serializationObject.cameras = [];
  18955. for (index = 0; index < scene.cameras.length; index++) {
  18956. var camera = scene.cameras[index];
  18957. serializationObject.cameras.push(serializeCamera(camera));
  18958. }
  18959. if (scene.activeCamera) {
  18960. serializationObject.activeCameraID = scene.activeCamera.id;
  18961. }
  18962. // Materials
  18963. serializationObject.materials = [];
  18964. serializationObject.multiMaterials = [];
  18965. for (index = 0; index < scene.materials.length; index++) {
  18966. var material = scene.materials[index];
  18967. if (material instanceof BABYLON.StandardMaterial) {
  18968. serializationObject.materials.push(serializeMaterial(material));
  18969. }
  18970. else if (material instanceof BABYLON.MultiMaterial) {
  18971. serializationObject.multiMaterials.push(serializeMultiMaterial(material));
  18972. }
  18973. }
  18974. // Skeletons
  18975. serializationObject.skeletons = [];
  18976. for (index = 0; index < scene.skeletons.length; index++) {
  18977. serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
  18978. }
  18979. // Geometries
  18980. serializationObject.geometries = {};
  18981. serializationObject.geometries.boxes = [];
  18982. serializationObject.geometries.spheres = [];
  18983. serializationObject.geometries.cylinders = [];
  18984. serializationObject.geometries.toruses = [];
  18985. serializationObject.geometries.grounds = [];
  18986. serializationObject.geometries.planes = [];
  18987. serializationObject.geometries.torusKnots = [];
  18988. serializationObject.geometries.vertexData = [];
  18989. serializedGeometries = [];
  18990. var geometries = scene.getGeometries();
  18991. for (index = 0; index < geometries.length; index++) {
  18992. var geometry = geometries[index];
  18993. if (geometry.isReady()) {
  18994. serializeGeometry(geometry, serializationObject.geometries);
  18995. }
  18996. }
  18997. // Meshes
  18998. serializationObject.meshes = [];
  18999. for (index = 0; index < scene.meshes.length; index++) {
  19000. var abstractMesh = scene.meshes[index];
  19001. if (abstractMesh instanceof BABYLON.Mesh) {
  19002. var mesh = abstractMesh;
  19003. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  19004. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  19005. }
  19006. }
  19007. }
  19008. // Particles Systems
  19009. serializationObject.particleSystems = [];
  19010. for (index = 0; index < scene.particleSystems.length; index++) {
  19011. serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
  19012. }
  19013. // Lens flares
  19014. serializationObject.lensFlareSystems = [];
  19015. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  19016. serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
  19017. }
  19018. // Shadows
  19019. serializationObject.shadowGenerators = [];
  19020. for (index = 0; index < scene.lights.length; index++) {
  19021. light = scene.lights[index];
  19022. if (light.getShadowGenerator()) {
  19023. serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
  19024. }
  19025. }
  19026. return serializationObject;
  19027. };
  19028. return SceneSerializer;
  19029. })();
  19030. BABYLON.SceneSerializer = SceneSerializer;
  19031. })(BABYLON || (BABYLON = {}));
  19032. //# sourceMappingURL=babylon.sceneSerializer.js.mapvar BABYLON;
  19033. (function (BABYLON) {
  19034. var SceneLoader = (function () {
  19035. function SceneLoader() {
  19036. }
  19037. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  19038. get: function () {
  19039. return SceneLoader._ForceFullSceneLoadingForIncremental;
  19040. },
  19041. set: function (value) {
  19042. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  19043. },
  19044. enumerable: true,
  19045. configurable: true
  19046. });
  19047. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  19048. get: function () {
  19049. return SceneLoader._ShowLoadingScreen;
  19050. },
  19051. set: function (value) {
  19052. SceneLoader._ShowLoadingScreen = value;
  19053. },
  19054. enumerable: true,
  19055. configurable: true
  19056. });
  19057. SceneLoader._getPluginForFilename = function (sceneFilename) {
  19058. var dotPosition = sceneFilename.lastIndexOf(".");
  19059. var queryStringPosition = sceneFilename.indexOf("?");
  19060. if (queryStringPosition === -1) {
  19061. queryStringPosition = sceneFilename.length;
  19062. }
  19063. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  19064. for (var index = 0; index < this._registeredPlugins.length; index++) {
  19065. var plugin = this._registeredPlugins[index];
  19066. if (plugin.extensions.indexOf(extension) !== -1) {
  19067. return plugin;
  19068. }
  19069. }
  19070. return this._registeredPlugins[this._registeredPlugins.length - 1];
  19071. };
  19072. // Public functions
  19073. SceneLoader.RegisterPlugin = function (plugin) {
  19074. plugin.extensions = plugin.extensions.toLowerCase();
  19075. SceneLoader._registeredPlugins.push(plugin);
  19076. };
  19077. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  19078. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  19079. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  19080. return;
  19081. }
  19082. var manifestChecked = function (success) {
  19083. scene.database = database;
  19084. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  19085. var importMeshFromData = function (data) {
  19086. var meshes = [];
  19087. var particleSystems = [];
  19088. var skeletons = [];
  19089. try {
  19090. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  19091. if (onerror) {
  19092. onerror(scene, 'unable to load the scene');
  19093. }
  19094. return;
  19095. }
  19096. }
  19097. catch (e) {
  19098. if (onerror) {
  19099. onerror(scene, e);
  19100. }
  19101. return;
  19102. }
  19103. if (onsuccess) {
  19104. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  19105. onsuccess(meshes, particleSystems, skeletons);
  19106. }
  19107. };
  19108. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  19109. // Direct load
  19110. importMeshFromData(sceneFilename.substr(5));
  19111. return;
  19112. }
  19113. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  19114. importMeshFromData(data);
  19115. }, progressCallBack, database);
  19116. };
  19117. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  19118. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  19119. };
  19120. /**
  19121. * Load a scene
  19122. * @param rootUrl a string that defines the root url for scene and resources
  19123. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  19124. * @param engine is the instance of BABYLON.Engine to use to create the scene
  19125. */
  19126. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  19127. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  19128. };
  19129. /**
  19130. * Append a scene
  19131. * @param rootUrl a string that defines the root url for scene and resources
  19132. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  19133. * @param scene is the instance of BABYLON.Scene to append to
  19134. */
  19135. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  19136. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  19137. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  19138. return;
  19139. }
  19140. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  19141. var database;
  19142. if (SceneLoader.ShowLoadingScreen) {
  19143. scene.getEngine().displayLoadingUI();
  19144. }
  19145. var loadSceneFromData = function (data) {
  19146. scene.database = database;
  19147. if (!plugin.load(scene, data, rootUrl)) {
  19148. if (onerror) {
  19149. onerror(scene);
  19150. }
  19151. scene.getEngine().hideLoadingUI();
  19152. return;
  19153. }
  19154. if (onsuccess) {
  19155. onsuccess(scene);
  19156. }
  19157. if (SceneLoader.ShowLoadingScreen) {
  19158. scene.executeWhenReady(function () {
  19159. scene.getEngine().hideLoadingUI();
  19160. });
  19161. }
  19162. };
  19163. var manifestChecked = function (success) {
  19164. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  19165. };
  19166. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  19167. // Direct load
  19168. loadSceneFromData(sceneFilename.substr(5));
  19169. return;
  19170. }
  19171. if (rootUrl.indexOf("file:") === -1) {
  19172. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  19173. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  19174. }
  19175. else {
  19176. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  19177. }
  19178. };
  19179. // Flags
  19180. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  19181. SceneLoader._ShowLoadingScreen = true;
  19182. // Members
  19183. SceneLoader._registeredPlugins = new Array();
  19184. return SceneLoader;
  19185. })();
  19186. BABYLON.SceneLoader = SceneLoader;
  19187. ;
  19188. })(BABYLON || (BABYLON = {}));
  19189. //# sourceMappingURL=babylon.sceneLoader.js.mapvar BABYLON;
  19190. (function (BABYLON) {
  19191. var Internals;
  19192. (function (Internals) {
  19193. var checkColors4 = function (colors, count) {
  19194. // Check if color3 was used
  19195. if (colors.length === count * 3) {
  19196. var colors4 = [];
  19197. for (var index = 0; index < colors.length; index += 3) {
  19198. var newIndex = (index / 3) * 4;
  19199. colors4[newIndex] = colors[index];
  19200. colors4[newIndex + 1] = colors[index + 1];
  19201. colors4[newIndex + 2] = colors[index + 2];
  19202. colors4[newIndex + 3] = 1.0;
  19203. }
  19204. return colors4;
  19205. }
  19206. return colors;
  19207. };
  19208. var loadCubeTexture = function (rootUrl, parsedTexture, scene) {
  19209. var texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene);
  19210. texture.name = parsedTexture.name;
  19211. texture.hasAlpha = parsedTexture.hasAlpha;
  19212. texture.level = parsedTexture.level;
  19213. texture.coordinatesMode = parsedTexture.coordinatesMode;
  19214. return texture;
  19215. };
  19216. var loadTexture = function (rootUrl, parsedTexture, scene) {
  19217. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  19218. return null;
  19219. }
  19220. if (parsedTexture.isCube) {
  19221. return loadCubeTexture(rootUrl, parsedTexture, scene);
  19222. }
  19223. var texture;
  19224. if (parsedTexture.mirrorPlane) {
  19225. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19226. texture._waitingRenderList = parsedTexture.renderList;
  19227. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  19228. }
  19229. else if (parsedTexture.isRenderTarget) {
  19230. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19231. texture._waitingRenderList = parsedTexture.renderList;
  19232. }
  19233. else {
  19234. texture = new BABYLON.Texture(rootUrl + parsedTexture.name, scene);
  19235. }
  19236. texture.name = parsedTexture.name;
  19237. texture.hasAlpha = parsedTexture.hasAlpha;
  19238. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  19239. texture.level = parsedTexture.level;
  19240. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  19241. texture.coordinatesMode = parsedTexture.coordinatesMode;
  19242. texture.uOffset = parsedTexture.uOffset;
  19243. texture.vOffset = parsedTexture.vOffset;
  19244. texture.uScale = parsedTexture.uScale;
  19245. texture.vScale = parsedTexture.vScale;
  19246. texture.uAng = parsedTexture.uAng;
  19247. texture.vAng = parsedTexture.vAng;
  19248. texture.wAng = parsedTexture.wAng;
  19249. texture.wrapU = parsedTexture.wrapU;
  19250. texture.wrapV = parsedTexture.wrapV;
  19251. // Animations
  19252. if (parsedTexture.animations) {
  19253. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  19254. var parsedAnimation = parsedTexture.animations[animationIndex];
  19255. texture.animations.push(parseAnimation(parsedAnimation));
  19256. }
  19257. }
  19258. return texture;
  19259. };
  19260. var parseSkeleton = function (parsedSkeleton, scene) {
  19261. var skeleton = new BABYLON.Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  19262. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  19263. var parsedBone = parsedSkeleton.bones[index];
  19264. var parentBone = null;
  19265. if (parsedBone.parentBoneIndex > -1) {
  19266. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  19267. }
  19268. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  19269. if (parsedBone.animation) {
  19270. bone.animations.push(parseAnimation(parsedBone.animation));
  19271. }
  19272. }
  19273. return skeleton;
  19274. };
  19275. var parseFresnelParameters = function (parsedFresnelParameters) {
  19276. var fresnelParameters = new BABYLON.FresnelParameters();
  19277. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  19278. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  19279. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  19280. fresnelParameters.bias = parsedFresnelParameters.bias;
  19281. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  19282. return fresnelParameters;
  19283. };
  19284. var parseMaterial = function (parsedMaterial, scene, rootUrl) {
  19285. var material;
  19286. material = new BABYLON.StandardMaterial(parsedMaterial.name, scene);
  19287. material.ambientColor = BABYLON.Color3.FromArray(parsedMaterial.ambient);
  19288. material.diffuseColor = BABYLON.Color3.FromArray(parsedMaterial.diffuse);
  19289. material.specularColor = BABYLON.Color3.FromArray(parsedMaterial.specular);
  19290. material.specularPower = parsedMaterial.specularPower;
  19291. material.emissiveColor = BABYLON.Color3.FromArray(parsedMaterial.emissive);
  19292. material.alpha = parsedMaterial.alpha;
  19293. material.id = parsedMaterial.id;
  19294. BABYLON.Tags.AddTagsTo(material, parsedMaterial.tags);
  19295. material.backFaceCulling = parsedMaterial.backFaceCulling;
  19296. material.wireframe = parsedMaterial.wireframe;
  19297. if (parsedMaterial.diffuseTexture) {
  19298. material.diffuseTexture = loadTexture(rootUrl, parsedMaterial.diffuseTexture, scene);
  19299. }
  19300. if (parsedMaterial.diffuseFresnelParameters) {
  19301. material.diffuseFresnelParameters = parseFresnelParameters(parsedMaterial.diffuseFresnelParameters);
  19302. }
  19303. if (parsedMaterial.ambientTexture) {
  19304. material.ambientTexture = loadTexture(rootUrl, parsedMaterial.ambientTexture, scene);
  19305. }
  19306. if (parsedMaterial.opacityTexture) {
  19307. material.opacityTexture = loadTexture(rootUrl, parsedMaterial.opacityTexture, scene);
  19308. }
  19309. if (parsedMaterial.opacityFresnelParameters) {
  19310. material.opacityFresnelParameters = parseFresnelParameters(parsedMaterial.opacityFresnelParameters);
  19311. }
  19312. if (parsedMaterial.reflectionTexture) {
  19313. material.reflectionTexture = loadTexture(rootUrl, parsedMaterial.reflectionTexture, scene);
  19314. }
  19315. if (parsedMaterial.reflectionFresnelParameters) {
  19316. material.reflectionFresnelParameters = parseFresnelParameters(parsedMaterial.reflectionFresnelParameters);
  19317. }
  19318. if (parsedMaterial.emissiveTexture) {
  19319. material.emissiveTexture = loadTexture(rootUrl, parsedMaterial.emissiveTexture, scene);
  19320. }
  19321. if (parsedMaterial.emissiveFresnelParameters) {
  19322. material.emissiveFresnelParameters = parseFresnelParameters(parsedMaterial.emissiveFresnelParameters);
  19323. }
  19324. if (parsedMaterial.specularTexture) {
  19325. material.specularTexture = loadTexture(rootUrl, parsedMaterial.specularTexture, scene);
  19326. }
  19327. if (parsedMaterial.bumpTexture) {
  19328. material.bumpTexture = loadTexture(rootUrl, parsedMaterial.bumpTexture, scene);
  19329. }
  19330. return material;
  19331. };
  19332. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  19333. for (var index = 0; index < parsedData.materials.length; index++) {
  19334. var parsedMaterial = parsedData.materials[index];
  19335. if (parsedMaterial.id === id) {
  19336. return parseMaterial(parsedMaterial, scene, rootUrl);
  19337. }
  19338. }
  19339. return null;
  19340. };
  19341. var parseMultiMaterial = function (parsedMultiMaterial, scene) {
  19342. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  19343. multiMaterial.id = parsedMultiMaterial.id;
  19344. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  19345. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  19346. var subMatId = parsedMultiMaterial.materials[matIndex];
  19347. if (subMatId) {
  19348. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  19349. }
  19350. else {
  19351. multiMaterial.subMaterials.push(null);
  19352. }
  19353. }
  19354. return multiMaterial;
  19355. };
  19356. var parseLensFlareSystem = function (parsedLensFlareSystem, scene, rootUrl) {
  19357. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  19358. var lensFlareSystem = new BABYLON.LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  19359. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  19360. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  19361. var parsedFlare = parsedLensFlareSystem.flares[index];
  19362. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  19363. }
  19364. return lensFlareSystem;
  19365. };
  19366. var parseParticleSystem = function (parsedParticleSystem, scene, rootUrl) {
  19367. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  19368. var particleSystem = new BABYLON.ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  19369. if (parsedParticleSystem.textureName) {
  19370. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  19371. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  19372. }
  19373. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  19374. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  19375. particleSystem.minSize = parsedParticleSystem.minSize;
  19376. particleSystem.maxSize = parsedParticleSystem.maxSize;
  19377. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  19378. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  19379. particleSystem.emitter = emitter;
  19380. particleSystem.emitRate = parsedParticleSystem.emitRate;
  19381. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  19382. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  19383. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  19384. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  19385. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  19386. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  19387. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  19388. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  19389. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  19390. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  19391. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  19392. particleSystem.blendMode = parsedParticleSystem.blendMode;
  19393. particleSystem.start();
  19394. return particleSystem;
  19395. };
  19396. var parseShadowGenerator = function (parsedShadowGenerator, scene) {
  19397. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  19398. var shadowGenerator = new BABYLON.ShadowGenerator(parsedShadowGenerator.mapSize, light);
  19399. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  19400. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  19401. shadowGenerator.getShadowMap().renderList.push(mesh);
  19402. }
  19403. if (parsedShadowGenerator.usePoissonSampling) {
  19404. shadowGenerator.usePoissonSampling = true;
  19405. }
  19406. else if (parsedShadowGenerator.useVarianceShadowMap) {
  19407. shadowGenerator.useVarianceShadowMap = true;
  19408. }
  19409. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  19410. shadowGenerator.useBlurVarianceShadowMap = true;
  19411. if (parsedShadowGenerator.blurScale) {
  19412. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  19413. }
  19414. if (parsedShadowGenerator.blurBoxOffset) {
  19415. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  19416. }
  19417. }
  19418. if (parsedShadowGenerator.bias !== undefined) {
  19419. shadowGenerator.bias = parsedShadowGenerator.bias;
  19420. }
  19421. return shadowGenerator;
  19422. };
  19423. var parseAnimation = function (parsedAnimation) {
  19424. var animation = new BABYLON.Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  19425. var dataType = parsedAnimation.dataType;
  19426. var keys = [];
  19427. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  19428. var key = parsedAnimation.keys[index];
  19429. var data;
  19430. switch (dataType) {
  19431. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  19432. data = key.values[0];
  19433. break;
  19434. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  19435. data = BABYLON.Quaternion.FromArray(key.values);
  19436. break;
  19437. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  19438. data = BABYLON.Matrix.FromArray(key.values);
  19439. break;
  19440. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  19441. default:
  19442. data = BABYLON.Vector3.FromArray(key.values);
  19443. break;
  19444. }
  19445. keys.push({
  19446. frame: key.frame,
  19447. value: data
  19448. });
  19449. }
  19450. animation.setKeys(keys);
  19451. return animation;
  19452. };
  19453. var parseLight = function (parsedLight, scene) {
  19454. var light;
  19455. switch (parsedLight.type) {
  19456. case 0:
  19457. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  19458. break;
  19459. case 1:
  19460. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  19461. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  19462. break;
  19463. case 2:
  19464. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  19465. break;
  19466. case 3:
  19467. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  19468. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  19469. break;
  19470. }
  19471. light.id = parsedLight.id;
  19472. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  19473. if (parsedLight.intensity !== undefined) {
  19474. light.intensity = parsedLight.intensity;
  19475. }
  19476. if (parsedLight.range) {
  19477. light.range = parsedLight.range;
  19478. }
  19479. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  19480. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  19481. if (parsedLight.excludedMeshesIds) {
  19482. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  19483. }
  19484. // Parent
  19485. if (parsedLight.parentId) {
  19486. light._waitingParentId = parsedLight.parentId;
  19487. }
  19488. if (parsedLight.includedOnlyMeshesIds) {
  19489. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  19490. }
  19491. // Animations
  19492. if (parsedLight.animations) {
  19493. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  19494. var parsedAnimation = parsedLight.animations[animationIndex];
  19495. light.animations.push(parseAnimation(parsedAnimation));
  19496. }
  19497. }
  19498. if (parsedLight.autoAnimate) {
  19499. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  19500. }
  19501. };
  19502. var parseCamera = function (parsedCamera, scene) {
  19503. var camera;
  19504. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  19505. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  19506. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  19507. var alpha = parsedCamera.alpha;
  19508. var beta = parsedCamera.beta;
  19509. var radius = parsedCamera.radius;
  19510. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  19511. var eye_space = parsedCamera.eye_space;
  19512. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, eye_space, scene);
  19513. }
  19514. else {
  19515. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  19516. }
  19517. }
  19518. else if (parsedCamera.type === "AnaglyphFreeCamera") {
  19519. eye_space = parsedCamera.eye_space;
  19520. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, eye_space, scene);
  19521. }
  19522. else if (parsedCamera.type === "DeviceOrientationCamera") {
  19523. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  19524. }
  19525. else if (parsedCamera.type === "FollowCamera") {
  19526. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  19527. camera.heightOffset = parsedCamera.heightOffset;
  19528. camera.radius = parsedCamera.radius;
  19529. camera.rotationOffset = parsedCamera.rotationOffset;
  19530. if (lockedTargetMesh)
  19531. camera.target = lockedTargetMesh;
  19532. }
  19533. else if (parsedCamera.type === "GamepadCamera") {
  19534. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  19535. }
  19536. else if (parsedCamera.type === "OculusCamera") {
  19537. camera = new BABYLON.OculusCamera(parsedCamera.name, position, scene);
  19538. }
  19539. else if (parsedCamera.type === "OculusGamepadCamera") {
  19540. camera = new BABYLON.OculusGamepadCamera(parsedCamera.name, position, scene);
  19541. }
  19542. else if (parsedCamera.type === "TouchCamera") {
  19543. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  19544. }
  19545. else if (parsedCamera.type === "VirtualJoysticksCamera") {
  19546. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  19547. }
  19548. else if (parsedCamera.type === "WebVRCamera") {
  19549. camera = new BABYLON.WebVRCamera(parsedCamera.name, position, scene);
  19550. }
  19551. else if (parsedCamera.type === "VRDeviceOrientationCamera") {
  19552. camera = new BABYLON.VRDeviceOrientationCamera(parsedCamera.name, position, scene);
  19553. }
  19554. else {
  19555. // Free Camera is the default value
  19556. camera = new BABYLON.FreeCamera(parsedCamera.name, position, scene);
  19557. }
  19558. // Test for lockedTargetMesh & FreeCamera outside of if-else-if nest, since things like GamepadCamera extend FreeCamera
  19559. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  19560. camera.lockedTarget = lockedTargetMesh;
  19561. }
  19562. camera.id = parsedCamera.id;
  19563. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  19564. // Parent
  19565. if (parsedCamera.parentId) {
  19566. camera._waitingParentId = parsedCamera.parentId;
  19567. }
  19568. // Target
  19569. if (parsedCamera.target) {
  19570. if (camera.setTarget) {
  19571. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  19572. }
  19573. else {
  19574. //For ArcRotate
  19575. camera.target = BABYLON.Vector3.FromArray(parsedCamera.target);
  19576. }
  19577. }
  19578. else {
  19579. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  19580. }
  19581. camera.fov = parsedCamera.fov;
  19582. camera.minZ = parsedCamera.minZ;
  19583. camera.maxZ = parsedCamera.maxZ;
  19584. camera.speed = parsedCamera.speed;
  19585. camera.inertia = parsedCamera.inertia;
  19586. camera.checkCollisions = parsedCamera.checkCollisions;
  19587. camera.applyGravity = parsedCamera.applyGravity;
  19588. if (parsedCamera.ellipsoid) {
  19589. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  19590. }
  19591. // Animations
  19592. if (parsedCamera.animations) {
  19593. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  19594. var parsedAnimation = parsedCamera.animations[animationIndex];
  19595. camera.animations.push(parseAnimation(parsedAnimation));
  19596. }
  19597. }
  19598. if (parsedCamera.autoAnimate) {
  19599. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  19600. }
  19601. // Layer Mask
  19602. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  19603. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  19604. }
  19605. else {
  19606. camera.layerMask = 0xFFFFFFFF;
  19607. }
  19608. return camera;
  19609. };
  19610. var parseGeometry = function (parsedGeometry, scene) {
  19611. var id = parsedGeometry.id;
  19612. return scene.getGeometryByID(id);
  19613. };
  19614. var parseBox = function (parsedBox, scene) {
  19615. if (parseGeometry(parsedBox, scene)) {
  19616. return null; // null since geometry could be something else than a box...
  19617. }
  19618. var box = new BABYLON.Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  19619. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  19620. scene.pushGeometry(box, true);
  19621. return box;
  19622. };
  19623. var parseSphere = function (parsedSphere, scene) {
  19624. if (parseGeometry(parsedSphere, scene)) {
  19625. return null; // null since geometry could be something else than a sphere...
  19626. }
  19627. var sphere = new BABYLON.Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  19628. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  19629. scene.pushGeometry(sphere, true);
  19630. return sphere;
  19631. };
  19632. var parseCylinder = function (parsedCylinder, scene) {
  19633. if (parseGeometry(parsedCylinder, scene)) {
  19634. return null; // null since geometry could be something else than a cylinder...
  19635. }
  19636. var cylinder = new BABYLON.Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  19637. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  19638. scene.pushGeometry(cylinder, true);
  19639. return cylinder;
  19640. };
  19641. var parseTorus = function (parsedTorus, scene) {
  19642. if (parseGeometry(parsedTorus, scene)) {
  19643. return null; // null since geometry could be something else than a torus...
  19644. }
  19645. var torus = new BABYLON.Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  19646. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  19647. scene.pushGeometry(torus, true);
  19648. return torus;
  19649. };
  19650. var parseGround = function (parsedGround, scene) {
  19651. if (parseGeometry(parsedGround, scene)) {
  19652. return null; // null since geometry could be something else than a ground...
  19653. }
  19654. var ground = new BABYLON.Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  19655. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  19656. scene.pushGeometry(ground, true);
  19657. return ground;
  19658. };
  19659. var parsePlane = function (parsedPlane, scene) {
  19660. if (parseGeometry(parsedPlane, scene)) {
  19661. return null; // null since geometry could be something else than a plane...
  19662. }
  19663. var plane = new BABYLON.Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  19664. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  19665. scene.pushGeometry(plane, true);
  19666. return plane;
  19667. };
  19668. var parseTorusKnot = function (parsedTorusKnot, scene) {
  19669. if (parseGeometry(parsedTorusKnot, scene)) {
  19670. return null; // null since geometry could be something else than a torusKnot...
  19671. }
  19672. 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);
  19673. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  19674. scene.pushGeometry(torusKnot, true);
  19675. return torusKnot;
  19676. };
  19677. var parseVertexData = function (parsedVertexData, scene, rootUrl) {
  19678. if (parseGeometry(parsedVertexData, scene)) {
  19679. return null; // null since geometry could be a primitive
  19680. }
  19681. var geometry = new BABYLON.Geometry(parsedVertexData.id, scene);
  19682. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  19683. if (parsedVertexData.delayLoadingFile) {
  19684. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19685. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  19686. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  19687. geometry._delayInfo = [];
  19688. if (parsedVertexData.hasUVs) {
  19689. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  19690. }
  19691. if (parsedVertexData.hasUVs2) {
  19692. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  19693. }
  19694. if (parsedVertexData.hasColors) {
  19695. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  19696. }
  19697. if (parsedVertexData.hasMatricesIndices) {
  19698. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  19699. }
  19700. if (parsedVertexData.hasMatricesWeights) {
  19701. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  19702. }
  19703. geometry._delayLoadingFunction = importVertexData;
  19704. }
  19705. else {
  19706. importVertexData(parsedVertexData, geometry);
  19707. }
  19708. scene.pushGeometry(geometry, true);
  19709. return geometry;
  19710. };
  19711. var parseMesh = function (parsedMesh, scene, rootUrl) {
  19712. var mesh = new BABYLON.Mesh(parsedMesh.name, scene);
  19713. mesh.id = parsedMesh.id;
  19714. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  19715. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  19716. if (parsedMesh.rotationQuaternion) {
  19717. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  19718. }
  19719. else if (parsedMesh.rotation) {
  19720. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  19721. }
  19722. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  19723. if (parsedMesh.localMatrix) {
  19724. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  19725. }
  19726. else if (parsedMesh.pivotMatrix) {
  19727. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  19728. }
  19729. mesh.setEnabled(parsedMesh.isEnabled);
  19730. mesh.isVisible = parsedMesh.isVisible;
  19731. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  19732. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  19733. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  19734. if (parsedMesh.applyFog !== undefined) {
  19735. mesh.applyFog = parsedMesh.applyFog;
  19736. }
  19737. if (parsedMesh.pickable !== undefined) {
  19738. mesh.isPickable = parsedMesh.pickable;
  19739. }
  19740. if (parsedMesh.alphaIndex !== undefined) {
  19741. mesh.alphaIndex = parsedMesh.alphaIndex;
  19742. }
  19743. mesh.receiveShadows = parsedMesh.receiveShadows;
  19744. mesh.billboardMode = parsedMesh.billboardMode;
  19745. if (parsedMesh.visibility !== undefined) {
  19746. mesh.visibility = parsedMesh.visibility;
  19747. }
  19748. mesh.checkCollisions = parsedMesh.checkCollisions;
  19749. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  19750. // Parent
  19751. if (parsedMesh.parentId) {
  19752. mesh._waitingParentId = parsedMesh.parentId;
  19753. }
  19754. // Actions
  19755. if (parsedMesh.actions !== undefined) {
  19756. mesh._waitingActions = parsedMesh.actions;
  19757. }
  19758. // Geometry
  19759. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  19760. if (parsedMesh.delayLoadingFile) {
  19761. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19762. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  19763. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  19764. if (parsedMesh._binaryInfo) {
  19765. mesh._binaryInfo = parsedMesh._binaryInfo;
  19766. }
  19767. mesh._delayInfo = [];
  19768. if (parsedMesh.hasUVs) {
  19769. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  19770. }
  19771. if (parsedMesh.hasUVs2) {
  19772. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  19773. }
  19774. if (parsedMesh.hasColors) {
  19775. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  19776. }
  19777. if (parsedMesh.hasMatricesIndices) {
  19778. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  19779. }
  19780. if (parsedMesh.hasMatricesWeights) {
  19781. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  19782. }
  19783. mesh._delayLoadingFunction = importGeometry;
  19784. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  19785. mesh._checkDelayState();
  19786. }
  19787. }
  19788. else {
  19789. importGeometry(parsedMesh, mesh);
  19790. }
  19791. // Material
  19792. if (parsedMesh.materialId) {
  19793. mesh.setMaterialByID(parsedMesh.materialId);
  19794. }
  19795. else {
  19796. mesh.material = null;
  19797. }
  19798. // Skeleton
  19799. if (parsedMesh.skeletonId > -1) {
  19800. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  19801. }
  19802. // Physics
  19803. if (parsedMesh.physicsImpostor) {
  19804. if (!scene.isPhysicsEnabled()) {
  19805. scene.enablePhysics();
  19806. }
  19807. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  19808. }
  19809. // Animations
  19810. if (parsedMesh.animations) {
  19811. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  19812. var parsedAnimation = parsedMesh.animations[animationIndex];
  19813. mesh.animations.push(parseAnimation(parsedAnimation));
  19814. }
  19815. }
  19816. if (parsedMesh.autoAnimate) {
  19817. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  19818. }
  19819. // Layer Mask
  19820. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  19821. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  19822. }
  19823. else {
  19824. mesh.layerMask = 0xFFFFFFFF;
  19825. }
  19826. // Instances
  19827. if (parsedMesh.instances) {
  19828. for (var index = 0; index < parsedMesh.instances.length; index++) {
  19829. var parsedInstance = parsedMesh.instances[index];
  19830. var instance = mesh.createInstance(parsedInstance.name);
  19831. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  19832. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  19833. if (parsedInstance.rotationQuaternion) {
  19834. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  19835. }
  19836. else if (parsedInstance.rotation) {
  19837. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  19838. }
  19839. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  19840. instance.checkCollisions = mesh.checkCollisions;
  19841. if (parsedMesh.animations) {
  19842. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  19843. parsedAnimation = parsedMesh.animations[animationIndex];
  19844. instance.animations.push(parseAnimation(parsedAnimation));
  19845. }
  19846. }
  19847. }
  19848. }
  19849. return mesh;
  19850. };
  19851. var parseActions = function (parsedActions, object, scene) {
  19852. var actionManager = new BABYLON.ActionManager(scene);
  19853. if (object === null)
  19854. scene.actionManager = actionManager;
  19855. else
  19856. object.actionManager = actionManager;
  19857. // instanciate a new object
  19858. var instanciate = function (name, params) {
  19859. var newInstance = Object.create(BABYLON[name].prototype);
  19860. newInstance.constructor.apply(newInstance, params);
  19861. return newInstance;
  19862. };
  19863. var parseParameter = function (name, value, target, propertyPath) {
  19864. if (propertyPath === null) {
  19865. // String, boolean or float
  19866. var floatValue = parseFloat(value);
  19867. if (value === "true" || value === "false")
  19868. return value === "true";
  19869. else
  19870. return isNaN(floatValue) ? value : floatValue;
  19871. }
  19872. var effectiveTarget = propertyPath.split(".");
  19873. var values = value.split(",");
  19874. for (var i = 0; i < effectiveTarget.length; i++) {
  19875. target = target[effectiveTarget[i]];
  19876. }
  19877. // Return appropriate value with its type
  19878. if (target instanceof Boolean)
  19879. return values[0] === "true";
  19880. if (target instanceof String)
  19881. return values[0];
  19882. // Parameters with multiple values such as Vector3 etc.
  19883. var split = new Array();
  19884. for (var i = 0; i < values.length; i++)
  19885. split.push(parseFloat(values[i]));
  19886. if (target instanceof BABYLON.Vector3)
  19887. return BABYLON.Vector3.FromArray(split);
  19888. if (target instanceof BABYLON.Vector4)
  19889. return BABYLON.Vector4.FromArray(split);
  19890. if (target instanceof BABYLON.Color3)
  19891. return BABYLON.Color3.FromArray(split);
  19892. if (target instanceof BABYLON.Color4)
  19893. return BABYLON.Color4.FromArray(split);
  19894. return parseFloat(values[0]);
  19895. };
  19896. // traverse graph per trigger
  19897. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  19898. if (combineArray === void 0) { combineArray = null; }
  19899. if (parsedAction.detached)
  19900. return;
  19901. var parameters = new Array();
  19902. var target = null;
  19903. var propertyPath = null;
  19904. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  19905. // Parameters
  19906. if (parsedAction.type === 2)
  19907. parameters.push(actionManager);
  19908. else
  19909. parameters.push(trigger);
  19910. if (combine) {
  19911. var actions = new Array();
  19912. for (var j = 0; j < parsedAction.combine.length; j++) {
  19913. traverse(parsedAction.combine[j], BABYLON.ActionManager.NothingTrigger, condition, action, actions);
  19914. }
  19915. parameters.push(actions);
  19916. }
  19917. else {
  19918. for (var i = 0; i < parsedAction.properties.length; i++) {
  19919. var value = parsedAction.properties[i].value;
  19920. var name = parsedAction.properties[i].name;
  19921. if (name === "target")
  19922. value = target = scene.getNodeByName(value);
  19923. else if (name === "parent")
  19924. value = scene.getNodeByName(value);
  19925. else if (name === "sound")
  19926. value = scene.getSoundByName(value);
  19927. else if (name !== "propertyPath") {
  19928. if (parsedAction.type === 2 && name === "operator")
  19929. value = BABYLON.ValueCondition[value];
  19930. else
  19931. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  19932. }
  19933. else {
  19934. propertyPath = value;
  19935. }
  19936. parameters.push(value);
  19937. }
  19938. }
  19939. parameters.push(condition);
  19940. // If interpolate value action
  19941. if (parsedAction.name === "InterpolateValueAction") {
  19942. var param = parameters[parameters.length - 2];
  19943. parameters[parameters.length - 1] = param;
  19944. parameters[parameters.length - 2] = condition;
  19945. }
  19946. // Action or condition(s) and not CombineAction
  19947. var newAction = instanciate(parsedAction.name, parameters);
  19948. if (combineArray === null) {
  19949. if (newAction instanceof BABYLON.Condition) {
  19950. condition = newAction;
  19951. newAction = action;
  19952. }
  19953. else {
  19954. condition = null;
  19955. if (action)
  19956. action.then(newAction);
  19957. else
  19958. actionManager.registerAction(newAction);
  19959. }
  19960. }
  19961. else {
  19962. combineArray.push(newAction);
  19963. }
  19964. for (var i = 0; i < parsedAction.children.length; i++)
  19965. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  19966. };
  19967. for (var i = 0; i < parsedActions.children.length; i++) {
  19968. var triggerParams;
  19969. var trigger = parsedActions.children[i];
  19970. if (trigger.properties.length > 0) {
  19971. var param = trigger.properties[0].value;
  19972. var value = trigger.properties[0].targetType == null ? param : scene.getMeshByName(param);
  19973. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  19974. }
  19975. else
  19976. triggerParams = BABYLON.ActionManager[trigger.name];
  19977. for (var j = 0; j < trigger.children.length; j++) {
  19978. if (!trigger.detached)
  19979. traverse(trigger.children[j], triggerParams, null, null);
  19980. }
  19981. }
  19982. };
  19983. var parseSound = function (parsedSound, scene, rootUrl) {
  19984. var soundName = parsedSound.name;
  19985. var soundUrl = rootUrl + soundName;
  19986. var options = {
  19987. autoplay: parsedSound.autoplay,
  19988. loop: parsedSound.loop,
  19989. volume: parsedSound.volume,
  19990. spatialSound: parsedSound.spatialSound,
  19991. maxDistance: parsedSound.maxDistance,
  19992. rolloffFactor: parsedSound.rolloffFactor,
  19993. refDistance: parsedSound.refDistance,
  19994. distanceModel: parsedSound.distanceModel,
  19995. playbackRate: parsedSound.playbackRate
  19996. };
  19997. var newSound = new BABYLON.Sound(soundName, soundUrl, scene, function () {
  19998. scene._removePendingData(newSound);
  19999. }, options);
  20000. scene._addPendingData(newSound);
  20001. if (parsedSound.position) {
  20002. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  20003. newSound.setPosition(soundPosition);
  20004. }
  20005. if (parsedSound.isDirectional) {
  20006. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  20007. if (parsedSound.localDirectionToMesh) {
  20008. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  20009. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  20010. }
  20011. }
  20012. if (parsedSound.connectedMeshId) {
  20013. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  20014. if (connectedMesh) {
  20015. newSound.attachToMesh(connectedMesh);
  20016. }
  20017. }
  20018. };
  20019. var isDescendantOf = function (mesh, names, hierarchyIds) {
  20020. names = (names instanceof Array) ? names : [names];
  20021. for (var i in names) {
  20022. if (mesh.name === names[i]) {
  20023. hierarchyIds.push(mesh.id);
  20024. return true;
  20025. }
  20026. }
  20027. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  20028. hierarchyIds.push(mesh.id);
  20029. return true;
  20030. }
  20031. return false;
  20032. };
  20033. var importVertexData = function (parsedVertexData, geometry) {
  20034. var vertexData = new BABYLON.VertexData();
  20035. // positions
  20036. var positions = parsedVertexData.positions;
  20037. if (positions) {
  20038. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  20039. }
  20040. // normals
  20041. var normals = parsedVertexData.normals;
  20042. if (normals) {
  20043. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  20044. }
  20045. // uvs
  20046. var uvs = parsedVertexData.uvs;
  20047. if (uvs) {
  20048. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  20049. }
  20050. // uv2s
  20051. var uv2s = parsedVertexData.uv2s;
  20052. if (uv2s) {
  20053. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  20054. }
  20055. // colors
  20056. var colors = parsedVertexData.colors;
  20057. if (colors) {
  20058. vertexData.set(checkColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  20059. }
  20060. // matricesIndices
  20061. var matricesIndices = parsedVertexData.matricesIndices;
  20062. if (matricesIndices) {
  20063. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  20064. }
  20065. // matricesWeights
  20066. var matricesWeights = parsedVertexData.matricesWeights;
  20067. if (matricesWeights) {
  20068. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  20069. }
  20070. // indices
  20071. var indices = parsedVertexData.indices;
  20072. if (indices) {
  20073. vertexData.indices = indices;
  20074. }
  20075. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  20076. };
  20077. var importGeometry = function (parsedGeometry, mesh) {
  20078. var scene = mesh.getScene();
  20079. // Geometry
  20080. var geometryId = parsedGeometry.geometryId;
  20081. if (geometryId) {
  20082. var geometry = scene.getGeometryByID(geometryId);
  20083. if (geometry) {
  20084. geometry.applyToMesh(mesh);
  20085. }
  20086. }
  20087. else if (parsedGeometry instanceof ArrayBuffer) {
  20088. var binaryInfo = mesh._binaryInfo;
  20089. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  20090. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  20091. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  20092. }
  20093. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  20094. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  20095. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  20096. }
  20097. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  20098. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  20099. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  20100. }
  20101. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  20102. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  20103. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  20104. }
  20105. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  20106. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  20107. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false);
  20108. }
  20109. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  20110. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  20111. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  20112. }
  20113. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  20114. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  20115. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  20116. }
  20117. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  20118. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  20119. mesh.setIndices(indicesData);
  20120. }
  20121. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  20122. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  20123. mesh.subMeshes = [];
  20124. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  20125. var materialIndex = subMeshesData[(i * 5) + 0];
  20126. var verticesStart = subMeshesData[(i * 5) + 1];
  20127. var verticesCount = subMeshesData[(i * 5) + 2];
  20128. var indexStart = subMeshesData[(i * 5) + 3];
  20129. var indexCount = subMeshesData[(i * 5) + 4];
  20130. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  20131. }
  20132. }
  20133. }
  20134. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  20135. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  20136. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  20137. if (parsedGeometry.uvs) {
  20138. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  20139. }
  20140. if (parsedGeometry.uvs2) {
  20141. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  20142. }
  20143. if (parsedGeometry.colors) {
  20144. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, checkColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  20145. }
  20146. if (parsedGeometry.matricesIndices) {
  20147. if (!parsedGeometry.matricesIndices._isExpanded) {
  20148. var floatIndices = [];
  20149. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  20150. var matricesIndex = parsedGeometry.matricesIndices[i];
  20151. floatIndices.push(matricesIndex & 0x000000FF);
  20152. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  20153. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  20154. floatIndices.push(matricesIndex >> 24);
  20155. }
  20156. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  20157. }
  20158. else {
  20159. delete parsedGeometry.matricesIndices._isExpanded;
  20160. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  20161. }
  20162. }
  20163. if (parsedGeometry.matricesWeights) {
  20164. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  20165. }
  20166. mesh.setIndices(parsedGeometry.indices);
  20167. // SubMeshes
  20168. if (parsedGeometry.subMeshes) {
  20169. mesh.subMeshes = [];
  20170. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  20171. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  20172. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  20173. }
  20174. }
  20175. }
  20176. // Flat shading
  20177. if (mesh._shouldGenerateFlatShading) {
  20178. mesh.convertToFlatShadedMesh();
  20179. delete mesh._shouldGenerateFlatShading;
  20180. }
  20181. // Update
  20182. mesh.computeWorldMatrix(true);
  20183. // Octree
  20184. if (scene._selectionOctree) {
  20185. scene._selectionOctree.addMesh(mesh);
  20186. }
  20187. };
  20188. BABYLON.SceneLoader.RegisterPlugin({
  20189. extensions: ".babylon",
  20190. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  20191. var parsedData = JSON.parse(data);
  20192. var loadedSkeletonsIds = [];
  20193. var loadedMaterialsIds = [];
  20194. var hierarchyIds = [];
  20195. for (var index = 0; index < parsedData.meshes.length; index++) {
  20196. var parsedMesh = parsedData.meshes[index];
  20197. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  20198. if (meshesNames instanceof Array) {
  20199. // Remove found mesh name from list.
  20200. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  20201. }
  20202. // Material ?
  20203. if (parsedMesh.materialId) {
  20204. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  20205. if (!materialFound) {
  20206. for (var multimatIndex = 0; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
  20207. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  20208. if (parsedMultiMaterial.id == parsedMesh.materialId) {
  20209. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  20210. var subMatId = parsedMultiMaterial.materials[matIndex];
  20211. loadedMaterialsIds.push(subMatId);
  20212. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  20213. }
  20214. loadedMaterialsIds.push(parsedMultiMaterial.id);
  20215. parseMultiMaterial(parsedMultiMaterial, scene);
  20216. materialFound = true;
  20217. break;
  20218. }
  20219. }
  20220. }
  20221. if (!materialFound) {
  20222. loadedMaterialsIds.push(parsedMesh.materialId);
  20223. parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  20224. }
  20225. }
  20226. // Skeleton ?
  20227. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  20228. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  20229. if (!skeletonAlreadyLoaded) {
  20230. for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
  20231. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  20232. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  20233. skeletons.push(parseSkeleton(parsedSkeleton, scene));
  20234. loadedSkeletonsIds.push(parsedSkeleton.id);
  20235. }
  20236. }
  20237. }
  20238. }
  20239. var mesh = parseMesh(parsedMesh, scene, rootUrl);
  20240. meshes.push(mesh);
  20241. }
  20242. }
  20243. for (index = 0; index < scene.meshes.length; index++) {
  20244. var currentMesh = scene.meshes[index];
  20245. if (currentMesh._waitingParentId) {
  20246. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  20247. currentMesh._waitingParentId = undefined;
  20248. }
  20249. }
  20250. // Particles
  20251. if (parsedData.particleSystems) {
  20252. for (index = 0; index < parsedData.particleSystems.length; index++) {
  20253. var parsedParticleSystem = parsedData.particleSystems[index];
  20254. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  20255. particleSystems.push(parseParticleSystem(parsedParticleSystem, scene, rootUrl));
  20256. }
  20257. }
  20258. }
  20259. return true;
  20260. },
  20261. load: function (scene, data, rootUrl) {
  20262. var parsedData = JSON.parse(data);
  20263. // Scene
  20264. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  20265. scene.autoClear = parsedData.autoClear;
  20266. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  20267. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  20268. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  20269. // Fog
  20270. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  20271. scene.fogMode = parsedData.fogMode;
  20272. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  20273. scene.fogStart = parsedData.fogStart;
  20274. scene.fogEnd = parsedData.fogEnd;
  20275. scene.fogDensity = parsedData.fogDensity;
  20276. }
  20277. for (var index = 0; index < parsedData.lights.length; index++) {
  20278. var parsedLight = parsedData.lights[index];
  20279. parseLight(parsedLight, scene);
  20280. }
  20281. // Materials
  20282. if (parsedData.materials) {
  20283. for (index = 0; index < parsedData.materials.length; index++) {
  20284. var parsedMaterial = parsedData.materials[index];
  20285. parseMaterial(parsedMaterial, scene, rootUrl);
  20286. }
  20287. }
  20288. if (parsedData.multiMaterials) {
  20289. for (index = 0; index < parsedData.multiMaterials.length; index++) {
  20290. var parsedMultiMaterial = parsedData.multiMaterials[index];
  20291. parseMultiMaterial(parsedMultiMaterial, scene);
  20292. }
  20293. }
  20294. // Skeletons
  20295. if (parsedData.skeletons) {
  20296. for (index = 0; index < parsedData.skeletons.length; index++) {
  20297. var parsedSkeleton = parsedData.skeletons[index];
  20298. parseSkeleton(parsedSkeleton, scene);
  20299. }
  20300. }
  20301. // Geometries
  20302. var geometries = parsedData.geometries;
  20303. if (geometries) {
  20304. // Boxes
  20305. var boxes = geometries.boxes;
  20306. if (boxes) {
  20307. for (index = 0; index < boxes.length; index++) {
  20308. var parsedBox = boxes[index];
  20309. parseBox(parsedBox, scene);
  20310. }
  20311. }
  20312. // Spheres
  20313. var spheres = geometries.spheres;
  20314. if (spheres) {
  20315. for (index = 0; index < spheres.length; index++) {
  20316. var parsedSphere = spheres[index];
  20317. parseSphere(parsedSphere, scene);
  20318. }
  20319. }
  20320. // Cylinders
  20321. var cylinders = geometries.cylinders;
  20322. if (cylinders) {
  20323. for (index = 0; index < cylinders.length; index++) {
  20324. var parsedCylinder = cylinders[index];
  20325. parseCylinder(parsedCylinder, scene);
  20326. }
  20327. }
  20328. // Toruses
  20329. var toruses = geometries.toruses;
  20330. if (toruses) {
  20331. for (index = 0; index < toruses.length; index++) {
  20332. var parsedTorus = toruses[index];
  20333. parseTorus(parsedTorus, scene);
  20334. }
  20335. }
  20336. // Grounds
  20337. var grounds = geometries.grounds;
  20338. if (grounds) {
  20339. for (index = 0; index < grounds.length; index++) {
  20340. var parsedGround = grounds[index];
  20341. parseGround(parsedGround, scene);
  20342. }
  20343. }
  20344. // Planes
  20345. var planes = geometries.planes;
  20346. if (planes) {
  20347. for (index = 0; index < planes.length; index++) {
  20348. var parsedPlane = planes[index];
  20349. parsePlane(parsedPlane, scene);
  20350. }
  20351. }
  20352. // TorusKnots
  20353. var torusKnots = geometries.torusKnots;
  20354. if (torusKnots) {
  20355. for (index = 0; index < torusKnots.length; index++) {
  20356. var parsedTorusKnot = torusKnots[index];
  20357. parseTorusKnot(parsedTorusKnot, scene);
  20358. }
  20359. }
  20360. // VertexData
  20361. var vertexData = geometries.vertexData;
  20362. if (vertexData) {
  20363. for (index = 0; index < vertexData.length; index++) {
  20364. var parsedVertexData = vertexData[index];
  20365. parseVertexData(parsedVertexData, scene, rootUrl);
  20366. }
  20367. }
  20368. }
  20369. for (index = 0; index < parsedData.meshes.length; index++) {
  20370. var parsedMesh = parsedData.meshes[index];
  20371. parseMesh(parsedMesh, scene, rootUrl);
  20372. }
  20373. for (index = 0; index < parsedData.cameras.length; index++) {
  20374. var parsedCamera = parsedData.cameras[index];
  20375. parseCamera(parsedCamera, scene);
  20376. }
  20377. if (parsedData.activeCameraID) {
  20378. scene.setActiveCameraByID(parsedData.activeCameraID);
  20379. }
  20380. for (index = 0; index < scene.cameras.length; index++) {
  20381. var camera = scene.cameras[index];
  20382. if (camera._waitingParentId) {
  20383. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  20384. camera._waitingParentId = undefined;
  20385. }
  20386. }
  20387. for (index = 0; index < scene.lights.length; index++) {
  20388. var light = scene.lights[index];
  20389. if (light._waitingParentId) {
  20390. light.parent = scene.getLastEntryByID(light._waitingParentId);
  20391. light._waitingParentId = undefined;
  20392. }
  20393. }
  20394. // Sounds
  20395. if (parsedData.sounds) {
  20396. for (index = 0; index < parsedData.sounds.length; index++) {
  20397. var parsedSound = parsedData.sounds[index];
  20398. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  20399. parseSound(parsedSound, scene, rootUrl);
  20400. }
  20401. else {
  20402. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  20403. }
  20404. }
  20405. }
  20406. for (index = 0; index < scene.meshes.length; index++) {
  20407. var mesh = scene.meshes[index];
  20408. if (mesh._waitingParentId) {
  20409. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  20410. mesh._waitingParentId = undefined;
  20411. }
  20412. if (mesh._waitingActions) {
  20413. parseActions(mesh._waitingActions, mesh, scene);
  20414. mesh._waitingActions = undefined;
  20415. }
  20416. }
  20417. // Particles Systems
  20418. if (parsedData.particleSystems) {
  20419. for (index = 0; index < parsedData.particleSystems.length; index++) {
  20420. var parsedParticleSystem = parsedData.particleSystems[index];
  20421. parseParticleSystem(parsedParticleSystem, scene, rootUrl);
  20422. }
  20423. }
  20424. // Lens flares
  20425. if (parsedData.lensFlareSystems) {
  20426. for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
  20427. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  20428. parseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
  20429. }
  20430. }
  20431. // Shadows
  20432. if (parsedData.shadowGenerators) {
  20433. for (index = 0; index < parsedData.shadowGenerators.length; index++) {
  20434. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  20435. parseShadowGenerator(parsedShadowGenerator, scene);
  20436. }
  20437. }
  20438. // Actions (scene)
  20439. if (parsedData.actions) {
  20440. parseActions(parsedData.actions, null, scene);
  20441. }
  20442. // Finish
  20443. return true;
  20444. }
  20445. });
  20446. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  20447. })(BABYLON || (BABYLON = {}));
  20448. //# sourceMappingURL=babylon.babylonFileLoader.js.mapvar BABYLON;
  20449. (function (BABYLON) {
  20450. // Unique ID when we import meshes from Babylon to CSG
  20451. var currentCSGMeshId = 0;
  20452. // # class Vertex
  20453. // Represents a vertex of a polygon. Use your own vertex class instead of this
  20454. // one to provide additional features like texture coordinates and vertex
  20455. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  20456. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  20457. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  20458. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  20459. // is not used anywhere else.
  20460. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  20461. var Vertex = (function () {
  20462. function Vertex(pos, normal, uv) {
  20463. this.pos = pos;
  20464. this.normal = normal;
  20465. this.uv = uv;
  20466. }
  20467. Vertex.prototype.clone = function () {
  20468. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  20469. };
  20470. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  20471. // orientation of a polygon is flipped.
  20472. Vertex.prototype.flip = function () {
  20473. this.normal = this.normal.scale(-1);
  20474. };
  20475. // Create a new vertex between this vertex and `other` by linearly
  20476. // interpolating all properties using a parameter of `t`. Subclasses should
  20477. // override this to interpolate additional properties.
  20478. Vertex.prototype.interpolate = function (other, t) {
  20479. 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));
  20480. };
  20481. return Vertex;
  20482. })();
  20483. // # class Plane
  20484. // Represents a plane in 3D space.
  20485. var Plane = (function () {
  20486. function Plane(normal, w) {
  20487. this.normal = normal;
  20488. this.w = w;
  20489. }
  20490. Plane.FromPoints = function (a, b, c) {
  20491. var v0 = c.subtract(a);
  20492. var v1 = b.subtract(a);
  20493. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  20494. return null;
  20495. }
  20496. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  20497. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  20498. };
  20499. Plane.prototype.clone = function () {
  20500. return new Plane(this.normal.clone(), this.w);
  20501. };
  20502. Plane.prototype.flip = function () {
  20503. this.normal.scaleInPlace(-1);
  20504. this.w = -this.w;
  20505. };
  20506. // Split `polygon` by this plane if needed, then put the polygon or polygon
  20507. // fragments in the appropriate lists. Coplanar polygons go into either
  20508. // `coplanarFront` or `coplanarBack` depending on their orientation with
  20509. // respect to this plane. Polygons in front or in back of this plane go into
  20510. // either `front` or `back`.
  20511. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  20512. var COPLANAR = 0;
  20513. var FRONT = 1;
  20514. var BACK = 2;
  20515. var SPANNING = 3;
  20516. // Classify each point as well as the entire polygon into one of the above
  20517. // four classes.
  20518. var polygonType = 0;
  20519. var types = [];
  20520. for (var i = 0; i < polygon.vertices.length; i++) {
  20521. var t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  20522. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  20523. polygonType |= type;
  20524. types.push(type);
  20525. }
  20526. switch (polygonType) {
  20527. case COPLANAR:
  20528. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  20529. break;
  20530. case FRONT:
  20531. front.push(polygon);
  20532. break;
  20533. case BACK:
  20534. back.push(polygon);
  20535. break;
  20536. case SPANNING:
  20537. var f = [], b = [];
  20538. for (i = 0; i < polygon.vertices.length; i++) {
  20539. var j = (i + 1) % polygon.vertices.length;
  20540. var ti = types[i], tj = types[j];
  20541. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  20542. if (ti != BACK)
  20543. f.push(vi);
  20544. if (ti != FRONT)
  20545. b.push(ti != BACK ? vi.clone() : vi);
  20546. if ((ti | tj) == SPANNING) {
  20547. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  20548. var v = vi.interpolate(vj, t);
  20549. f.push(v);
  20550. b.push(v.clone());
  20551. }
  20552. }
  20553. if (f.length >= 3) {
  20554. var poly = new Polygon(f, polygon.shared);
  20555. if (poly.plane)
  20556. front.push(poly);
  20557. }
  20558. if (b.length >= 3) {
  20559. poly = new Polygon(b, polygon.shared);
  20560. if (poly.plane)
  20561. back.push(poly);
  20562. }
  20563. break;
  20564. }
  20565. };
  20566. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  20567. // point is on the plane.
  20568. Plane.EPSILON = 1e-5;
  20569. return Plane;
  20570. })();
  20571. // # class Polygon
  20572. // Represents a convex polygon. The vertices used to initialize a polygon must
  20573. // be coplanar and form a convex loop.
  20574. //
  20575. // Each convex polygon has a `shared` property, which is shared between all
  20576. // polygons that are clones of each other or were split from the same polygon.
  20577. // This can be used to define per-polygon properties (such as surface color).
  20578. var Polygon = (function () {
  20579. function Polygon(vertices, shared) {
  20580. this.vertices = vertices;
  20581. this.shared = shared;
  20582. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  20583. }
  20584. Polygon.prototype.clone = function () {
  20585. var vertices = this.vertices.map(function (v) { return v.clone(); });
  20586. return new Polygon(vertices, this.shared);
  20587. };
  20588. Polygon.prototype.flip = function () {
  20589. this.vertices.reverse().map(function (v) {
  20590. v.flip();
  20591. });
  20592. this.plane.flip();
  20593. };
  20594. return Polygon;
  20595. })();
  20596. // # class Node
  20597. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  20598. // by picking a polygon to split along. That polygon (and all other coplanar
  20599. // polygons) are added directly to that node and the other polygons are added to
  20600. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  20601. // no distinction between internal and leaf nodes.
  20602. var Node = (function () {
  20603. function Node(polygons) {
  20604. this.plane = null;
  20605. this.front = null;
  20606. this.back = null;
  20607. this.polygons = [];
  20608. if (polygons) {
  20609. this.build(polygons);
  20610. }
  20611. }
  20612. Node.prototype.clone = function () {
  20613. var node = new Node();
  20614. node.plane = this.plane && this.plane.clone();
  20615. node.front = this.front && this.front.clone();
  20616. node.back = this.back && this.back.clone();
  20617. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  20618. return node;
  20619. };
  20620. // Convert solid space to empty space and empty space to solid space.
  20621. Node.prototype.invert = function () {
  20622. for (var i = 0; i < this.polygons.length; i++) {
  20623. this.polygons[i].flip();
  20624. }
  20625. if (this.plane) {
  20626. this.plane.flip();
  20627. }
  20628. if (this.front) {
  20629. this.front.invert();
  20630. }
  20631. if (this.back) {
  20632. this.back.invert();
  20633. }
  20634. var temp = this.front;
  20635. this.front = this.back;
  20636. this.back = temp;
  20637. };
  20638. // Recursively remove all polygons in `polygons` that are inside this BSP
  20639. // tree.
  20640. Node.prototype.clipPolygons = function (polygons) {
  20641. if (!this.plane)
  20642. return polygons.slice();
  20643. var front = [], back = [];
  20644. for (var i = 0; i < polygons.length; i++) {
  20645. this.plane.splitPolygon(polygons[i], front, back, front, back);
  20646. }
  20647. if (this.front) {
  20648. front = this.front.clipPolygons(front);
  20649. }
  20650. if (this.back) {
  20651. back = this.back.clipPolygons(back);
  20652. }
  20653. else {
  20654. back = [];
  20655. }
  20656. return front.concat(back);
  20657. };
  20658. // Remove all polygons in this BSP tree that are inside the other BSP tree
  20659. // `bsp`.
  20660. Node.prototype.clipTo = function (bsp) {
  20661. this.polygons = bsp.clipPolygons(this.polygons);
  20662. if (this.front)
  20663. this.front.clipTo(bsp);
  20664. if (this.back)
  20665. this.back.clipTo(bsp);
  20666. };
  20667. // Return a list of all polygons in this BSP tree.
  20668. Node.prototype.allPolygons = function () {
  20669. var polygons = this.polygons.slice();
  20670. if (this.front)
  20671. polygons = polygons.concat(this.front.allPolygons());
  20672. if (this.back)
  20673. polygons = polygons.concat(this.back.allPolygons());
  20674. return polygons;
  20675. };
  20676. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  20677. // new polygons are filtered down to the bottom of the tree and become new
  20678. // nodes there. Each set of polygons is partitioned using the first polygon
  20679. // (no heuristic is used to pick a good split).
  20680. Node.prototype.build = function (polygons) {
  20681. if (!polygons.length)
  20682. return;
  20683. if (!this.plane)
  20684. this.plane = polygons[0].plane.clone();
  20685. var front = [], back = [];
  20686. for (var i = 0; i < polygons.length; i++) {
  20687. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  20688. }
  20689. if (front.length) {
  20690. if (!this.front)
  20691. this.front = new Node();
  20692. this.front.build(front);
  20693. }
  20694. if (back.length) {
  20695. if (!this.back)
  20696. this.back = new Node();
  20697. this.back.build(back);
  20698. }
  20699. };
  20700. return Node;
  20701. })();
  20702. var CSG = (function () {
  20703. function CSG() {
  20704. this.polygons = new Array();
  20705. }
  20706. // Convert BABYLON.Mesh to BABYLON.CSG
  20707. CSG.FromMesh = function (mesh) {
  20708. var vertex, normal, uv, position, polygon, polygons = [], vertices;
  20709. if (mesh instanceof BABYLON.Mesh) {
  20710. mesh.computeWorldMatrix(true);
  20711. var matrix = mesh.getWorldMatrix();
  20712. var meshPosition = mesh.position.clone();
  20713. var meshRotation = mesh.rotation.clone();
  20714. var meshScaling = mesh.scaling.clone();
  20715. }
  20716. else {
  20717. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  20718. }
  20719. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  20720. var subMeshes = mesh.subMeshes;
  20721. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  20722. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  20723. vertices = [];
  20724. for (var j = 0; j < 3; j++) {
  20725. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  20726. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  20727. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  20728. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  20729. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  20730. vertex = new Vertex(position, normal, uv);
  20731. vertices.push(vertex);
  20732. }
  20733. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  20734. // To handle the case of degenerated triangle
  20735. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  20736. if (polygon.plane)
  20737. polygons.push(polygon);
  20738. }
  20739. }
  20740. var csg = CSG.FromPolygons(polygons);
  20741. csg.matrix = matrix;
  20742. csg.position = meshPosition;
  20743. csg.rotation = meshRotation;
  20744. csg.scaling = meshScaling;
  20745. currentCSGMeshId++;
  20746. return csg;
  20747. };
  20748. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  20749. CSG.FromPolygons = function (polygons) {
  20750. var csg = new BABYLON.CSG();
  20751. csg.polygons = polygons;
  20752. return csg;
  20753. };
  20754. CSG.prototype.clone = function () {
  20755. var csg = new BABYLON.CSG();
  20756. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  20757. csg.copyTransformAttributes(this);
  20758. return csg;
  20759. };
  20760. CSG.prototype.toPolygons = function () {
  20761. return this.polygons;
  20762. };
  20763. CSG.prototype.union = function (csg) {
  20764. var a = new Node(this.clone().polygons);
  20765. var b = new Node(csg.clone().polygons);
  20766. a.clipTo(b);
  20767. b.clipTo(a);
  20768. b.invert();
  20769. b.clipTo(a);
  20770. b.invert();
  20771. a.build(b.allPolygons());
  20772. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  20773. };
  20774. CSG.prototype.unionInPlace = function (csg) {
  20775. var a = new Node(this.polygons);
  20776. var b = new Node(csg.polygons);
  20777. a.clipTo(b);
  20778. b.clipTo(a);
  20779. b.invert();
  20780. b.clipTo(a);
  20781. b.invert();
  20782. a.build(b.allPolygons());
  20783. this.polygons = a.allPolygons();
  20784. };
  20785. CSG.prototype.subtract = function (csg) {
  20786. var a = new Node(this.clone().polygons);
  20787. var b = new Node(csg.clone().polygons);
  20788. a.invert();
  20789. a.clipTo(b);
  20790. b.clipTo(a);
  20791. b.invert();
  20792. b.clipTo(a);
  20793. b.invert();
  20794. a.build(b.allPolygons());
  20795. a.invert();
  20796. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  20797. };
  20798. CSG.prototype.subtractInPlace = function (csg) {
  20799. var a = new Node(this.polygons);
  20800. var b = new Node(csg.polygons);
  20801. a.invert();
  20802. a.clipTo(b);
  20803. b.clipTo(a);
  20804. b.invert();
  20805. b.clipTo(a);
  20806. b.invert();
  20807. a.build(b.allPolygons());
  20808. a.invert();
  20809. this.polygons = a.allPolygons();
  20810. };
  20811. CSG.prototype.intersect = function (csg) {
  20812. var a = new Node(this.clone().polygons);
  20813. var b = new Node(csg.clone().polygons);
  20814. a.invert();
  20815. b.clipTo(a);
  20816. b.invert();
  20817. a.clipTo(b);
  20818. b.clipTo(a);
  20819. a.build(b.allPolygons());
  20820. a.invert();
  20821. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  20822. };
  20823. CSG.prototype.intersectInPlace = function (csg) {
  20824. var a = new Node(this.polygons);
  20825. var b = new Node(csg.polygons);
  20826. a.invert();
  20827. b.clipTo(a);
  20828. b.invert();
  20829. a.clipTo(b);
  20830. b.clipTo(a);
  20831. a.build(b.allPolygons());
  20832. a.invert();
  20833. this.polygons = a.allPolygons();
  20834. };
  20835. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  20836. // not modified.
  20837. CSG.prototype.inverse = function () {
  20838. var csg = this.clone();
  20839. csg.inverseInPlace();
  20840. return csg;
  20841. };
  20842. CSG.prototype.inverseInPlace = function () {
  20843. this.polygons.map(function (p) {
  20844. p.flip();
  20845. });
  20846. };
  20847. // This is used to keep meshes transformations so they can be restored
  20848. // when we build back a Babylon Mesh
  20849. // NB : All CSG operations are performed in world coordinates
  20850. CSG.prototype.copyTransformAttributes = function (csg) {
  20851. this.matrix = csg.matrix;
  20852. this.position = csg.position;
  20853. this.rotation = csg.rotation;
  20854. this.scaling = csg.scaling;
  20855. return this;
  20856. };
  20857. // Build Raw mesh from CSG
  20858. // Coordinates here are in world space
  20859. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  20860. var matrix = this.matrix.clone();
  20861. matrix.invert();
  20862. 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;
  20863. if (keepSubMeshes) {
  20864. // Sort Polygons, since subMeshes are indices range
  20865. polygons.sort(function (a, b) {
  20866. if (a.shared.meshId === b.shared.meshId) {
  20867. return a.shared.subMeshId - b.shared.subMeshId;
  20868. }
  20869. else {
  20870. return a.shared.meshId - b.shared.meshId;
  20871. }
  20872. });
  20873. }
  20874. for (var i = 0, il = polygons.length; i < il; i++) {
  20875. polygon = polygons[i];
  20876. // Building SubMeshes
  20877. if (!subMesh_dict[polygon.shared.meshId]) {
  20878. subMesh_dict[polygon.shared.meshId] = {};
  20879. }
  20880. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  20881. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  20882. indexStart: +Infinity,
  20883. indexEnd: -Infinity,
  20884. materialIndex: polygon.shared.materialIndex
  20885. };
  20886. }
  20887. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  20888. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  20889. polygonIndices[0] = 0;
  20890. polygonIndices[1] = j - 1;
  20891. polygonIndices[2] = j;
  20892. for (var k = 0; k < 3; k++) {
  20893. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  20894. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  20895. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  20896. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  20897. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  20898. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  20899. // Check if 2 points can be merged
  20900. 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)) {
  20901. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  20902. uvs.push(uv.x, uv.y);
  20903. normals.push(normal.x, normal.y, normal.z);
  20904. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  20905. }
  20906. indices.push(vertex_idx);
  20907. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  20908. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  20909. currentIndex++;
  20910. }
  20911. }
  20912. }
  20913. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  20914. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  20915. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  20916. mesh.setIndices(indices);
  20917. if (keepSubMeshes) {
  20918. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  20919. var materialIndexOffset = 0, materialMaxIndex;
  20920. mesh.subMeshes.length = 0;
  20921. for (var m in subMesh_dict) {
  20922. materialMaxIndex = -1;
  20923. for (var sm in subMesh_dict[m]) {
  20924. subMesh_obj = subMesh_dict[m][sm];
  20925. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  20926. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  20927. }
  20928. materialIndexOffset += ++materialMaxIndex;
  20929. }
  20930. }
  20931. return mesh;
  20932. };
  20933. // Build Mesh from CSG taking material and transforms into account
  20934. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  20935. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  20936. mesh.material = material;
  20937. mesh.position.copyFrom(this.position);
  20938. mesh.rotation.copyFrom(this.rotation);
  20939. mesh.scaling.copyFrom(this.scaling);
  20940. mesh.computeWorldMatrix(true);
  20941. return mesh;
  20942. };
  20943. return CSG;
  20944. })();
  20945. BABYLON.CSG = CSG;
  20946. })(BABYLON || (BABYLON = {}));
  20947. //# sourceMappingURL=babylon.csg.js.map
  20948. var BABYLON;
  20949. (function (BABYLON) {
  20950. var OculusDistortionCorrectionPostProcess = (function (_super) {
  20951. __extends(OculusDistortionCorrectionPostProcess, _super);
  20952. //ANY
  20953. function OculusDistortionCorrectionPostProcess(name, camera, isRightEye, cameraSettings) {
  20954. var _this = this;
  20955. _super.call(this, name, "oculusDistortionCorrection", [
  20956. 'LensCenter',
  20957. 'Scale',
  20958. 'ScaleIn',
  20959. 'HmdWarpParam'
  20960. ], null, cameraSettings.PostProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  20961. this._isRightEye = isRightEye;
  20962. this._distortionFactors = cameraSettings.DistortionK;
  20963. this._postProcessScaleFactor = cameraSettings.PostProcessScaleFactor;
  20964. this._lensCenterOffset = cameraSettings.LensCenterOffset;
  20965. this.onSizeChanged = function () {
  20966. _this.aspectRatio = _this.width * .5 / _this.height;
  20967. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  20968. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  20969. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  20970. };
  20971. this.onApply = function (effect) {
  20972. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  20973. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  20974. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  20975. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  20976. };
  20977. }
  20978. return OculusDistortionCorrectionPostProcess;
  20979. })(BABYLON.PostProcess);
  20980. BABYLON.OculusDistortionCorrectionPostProcess = OculusDistortionCorrectionPostProcess;
  20981. })(BABYLON || (BABYLON = {}));
  20982. //# sourceMappingURL=babylon.oculusDistortionCorrectionPostProcess.js.map// Mainly based on these 2 articles :
  20983. // 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
  20984. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  20985. var BABYLON;
  20986. (function (BABYLON) {
  20987. (function (JoystickAxis) {
  20988. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  20989. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  20990. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  20991. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  20992. var JoystickAxis = BABYLON.JoystickAxis;
  20993. var VirtualJoystick = (function () {
  20994. function VirtualJoystick(leftJoystick) {
  20995. var _this = this;
  20996. if (leftJoystick) {
  20997. this._leftJoystick = true;
  20998. }
  20999. else {
  21000. this._leftJoystick = false;
  21001. }
  21002. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  21003. VirtualJoystick._globalJoystickIndex++;
  21004. // By default left & right arrow keys are moving the X
  21005. // and up & down keys are moving the Y
  21006. this._axisTargetedByLeftAndRight = 0 /* X */;
  21007. this._axisTargetedByUpAndDown = 1 /* Y */;
  21008. this.reverseLeftRight = false;
  21009. this.reverseUpDown = false;
  21010. // collections of pointers
  21011. this._touches = new BABYLON.VirtualJoystick.Collection();
  21012. this.deltaPosition = BABYLON.Vector3.Zero();
  21013. this._joystickSensibility = 25;
  21014. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  21015. this._rotationSpeed = 25;
  21016. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  21017. this._rotateOnAxisRelativeToMesh = false;
  21018. // injecting a canvas element on top of the canvas 3D game
  21019. if (!VirtualJoystick.vjCanvas) {
  21020. window.addEventListener("resize", function () {
  21021. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  21022. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  21023. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  21024. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  21025. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  21026. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  21027. }, false);
  21028. VirtualJoystick.vjCanvas = document.createElement("canvas");
  21029. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  21030. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  21031. VirtualJoystick.vjCanvas.width = window.innerWidth;
  21032. VirtualJoystick.vjCanvas.height = window.innerHeight;
  21033. VirtualJoystick.vjCanvas.style.width = "100%";
  21034. VirtualJoystick.vjCanvas.style.height = "100%";
  21035. VirtualJoystick.vjCanvas.style.position = "absolute";
  21036. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  21037. VirtualJoystick.vjCanvas.style.top = "0px";
  21038. VirtualJoystick.vjCanvas.style.left = "0px";
  21039. VirtualJoystick.vjCanvas.style.zIndex = "5";
  21040. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  21041. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  21042. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  21043. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  21044. document.body.appendChild(VirtualJoystick.vjCanvas);
  21045. }
  21046. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  21047. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  21048. this.pressed = false;
  21049. // default joystick color
  21050. this._joystickColor = "cyan";
  21051. this._joystickPointerID = -1;
  21052. // current joystick position
  21053. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  21054. // origin joystick position
  21055. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  21056. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  21057. VirtualJoystick.vjCanvas.addEventListener('pointerdown', function (evt) {
  21058. _this._onPointerDown(evt);
  21059. }, false);
  21060. VirtualJoystick.vjCanvas.addEventListener('pointermove', function (evt) {
  21061. _this._onPointerMove(evt);
  21062. }, false);
  21063. VirtualJoystick.vjCanvas.addEventListener('pointerup', function (evt) {
  21064. _this._onPointerUp(evt);
  21065. }, false);
  21066. VirtualJoystick.vjCanvas.addEventListener('pointerout', function (evt) {
  21067. _this._onPointerUp(evt);
  21068. }, false);
  21069. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  21070. evt.preventDefault(); // Disables system menu
  21071. }, false);
  21072. requestAnimationFrame(function () {
  21073. _this._drawVirtualJoystick();
  21074. });
  21075. }
  21076. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  21077. this._joystickSensibility = newJoystickSensibility;
  21078. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  21079. };
  21080. VirtualJoystick.prototype._onPointerDown = function (e) {
  21081. var positionOnScreenCondition;
  21082. e.preventDefault();
  21083. if (this._leftJoystick === true) {
  21084. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  21085. }
  21086. else {
  21087. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  21088. }
  21089. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  21090. // First contact will be dedicated to the virtual joystick
  21091. this._joystickPointerID = e.pointerId;
  21092. this._joystickPointerStartPos.x = e.clientX;
  21093. this._joystickPointerStartPos.y = e.clientY;
  21094. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  21095. this._deltaJoystickVector.x = 0;
  21096. this._deltaJoystickVector.y = 0;
  21097. this.pressed = true;
  21098. this._touches.add(e.pointerId.toString(), e);
  21099. }
  21100. else {
  21101. // You can only trigger the action buttons with a joystick declared
  21102. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  21103. this._action();
  21104. this._touches.add(e.pointerId.toString(), e);
  21105. }
  21106. }
  21107. };
  21108. VirtualJoystick.prototype._onPointerMove = function (e) {
  21109. // If the current pointer is the one associated to the joystick (first touch contact)
  21110. if (this._joystickPointerID == e.pointerId) {
  21111. this._joystickPointerPos.x = e.clientX;
  21112. this._joystickPointerPos.y = e.clientY;
  21113. this._deltaJoystickVector = this._joystickPointerPos.clone();
  21114. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  21115. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  21116. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  21117. switch (this._axisTargetedByLeftAndRight) {
  21118. case 0 /* X */:
  21119. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  21120. break;
  21121. case 1 /* Y */:
  21122. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  21123. break;
  21124. case 2 /* Z */:
  21125. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  21126. break;
  21127. }
  21128. var directionUpDown = this.reverseUpDown ? 1 : -1;
  21129. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  21130. switch (this._axisTargetedByUpAndDown) {
  21131. case 0 /* X */:
  21132. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  21133. break;
  21134. case 1 /* Y */:
  21135. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  21136. break;
  21137. case 2 /* Z */:
  21138. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  21139. break;
  21140. }
  21141. }
  21142. else {
  21143. if (this._touches.item(e.pointerId.toString())) {
  21144. this._touches.item(e.pointerId.toString()).x = e.clientX;
  21145. this._touches.item(e.pointerId.toString()).y = e.clientY;
  21146. }
  21147. }
  21148. };
  21149. VirtualJoystick.prototype._onPointerUp = function (e) {
  21150. this._clearCanvas();
  21151. if (this._joystickPointerID == e.pointerId) {
  21152. this._joystickPointerID = -1;
  21153. this.pressed = false;
  21154. }
  21155. this._deltaJoystickVector.x = 0;
  21156. this._deltaJoystickVector.y = 0;
  21157. this._touches.remove(e.pointerId.toString());
  21158. };
  21159. /**
  21160. * Change the color of the virtual joystick
  21161. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  21162. */
  21163. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  21164. this._joystickColor = newColor;
  21165. };
  21166. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  21167. this._action = action;
  21168. };
  21169. // Define which axis you'd like to control for left & right
  21170. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  21171. switch (axis) {
  21172. case 0 /* X */:
  21173. case 1 /* Y */:
  21174. case 2 /* Z */:
  21175. this._axisTargetedByLeftAndRight = axis;
  21176. break;
  21177. default:
  21178. this._axisTargetedByLeftAndRight = 0 /* X */;
  21179. break;
  21180. }
  21181. };
  21182. // Define which axis you'd like to control for up & down
  21183. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  21184. switch (axis) {
  21185. case 0 /* X */:
  21186. case 1 /* Y */:
  21187. case 2 /* Z */:
  21188. this._axisTargetedByUpAndDown = axis;
  21189. break;
  21190. default:
  21191. this._axisTargetedByUpAndDown = 1 /* Y */;
  21192. break;
  21193. }
  21194. };
  21195. VirtualJoystick.prototype._clearCanvas = function () {
  21196. if (this._leftJoystick) {
  21197. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  21198. }
  21199. else {
  21200. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  21201. }
  21202. };
  21203. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  21204. var _this = this;
  21205. if (this.pressed) {
  21206. this._clearCanvas();
  21207. this._touches.forEach(function (touch) {
  21208. if (touch.pointerId === _this._joystickPointerID) {
  21209. VirtualJoystick.vjCanvasContext.beginPath();
  21210. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  21211. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  21212. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  21213. VirtualJoystick.vjCanvasContext.stroke();
  21214. VirtualJoystick.vjCanvasContext.beginPath();
  21215. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  21216. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  21217. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  21218. VirtualJoystick.vjCanvasContext.stroke();
  21219. VirtualJoystick.vjCanvasContext.beginPath();
  21220. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  21221. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  21222. VirtualJoystick.vjCanvasContext.stroke();
  21223. }
  21224. else {
  21225. VirtualJoystick.vjCanvasContext.beginPath();
  21226. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  21227. VirtualJoystick.vjCanvasContext.beginPath();
  21228. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  21229. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  21230. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  21231. VirtualJoystick.vjCanvasContext.stroke();
  21232. }
  21233. ;
  21234. });
  21235. }
  21236. requestAnimationFrame(function () {
  21237. _this._drawVirtualJoystick();
  21238. });
  21239. };
  21240. VirtualJoystick.prototype.releaseCanvas = function () {
  21241. if (VirtualJoystick.vjCanvas) {
  21242. document.body.removeChild(VirtualJoystick.vjCanvas);
  21243. VirtualJoystick.vjCanvas = null;
  21244. }
  21245. };
  21246. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  21247. VirtualJoystick._globalJoystickIndex = 0;
  21248. return VirtualJoystick;
  21249. })();
  21250. BABYLON.VirtualJoystick = VirtualJoystick;
  21251. })(BABYLON || (BABYLON = {}));
  21252. var BABYLON;
  21253. (function (BABYLON) {
  21254. var VirtualJoystick;
  21255. (function (VirtualJoystick) {
  21256. var Collection = (function () {
  21257. function Collection() {
  21258. this._count = 0;
  21259. this._collection = new Array();
  21260. }
  21261. Collection.prototype.Count = function () {
  21262. return this._count;
  21263. };
  21264. Collection.prototype.add = function (key, item) {
  21265. if (this._collection[key] != undefined) {
  21266. return undefined;
  21267. }
  21268. this._collection[key] = item;
  21269. return ++this._count;
  21270. };
  21271. Collection.prototype.remove = function (key) {
  21272. if (this._collection[key] == undefined) {
  21273. return undefined;
  21274. }
  21275. delete this._collection[key];
  21276. return --this._count;
  21277. };
  21278. Collection.prototype.item = function (key) {
  21279. return this._collection[key];
  21280. };
  21281. Collection.prototype.forEach = function (block) {
  21282. var key;
  21283. for (key in this._collection) {
  21284. if (this._collection.hasOwnProperty(key)) {
  21285. block(this._collection[key]);
  21286. }
  21287. }
  21288. };
  21289. return Collection;
  21290. })();
  21291. VirtualJoystick.Collection = Collection;
  21292. })(VirtualJoystick = BABYLON.VirtualJoystick || (BABYLON.VirtualJoystick = {}));
  21293. })(BABYLON || (BABYLON = {}));
  21294. //# sourceMappingURL=babylon.virtualJoystick.js.map
  21295. var BABYLON;
  21296. (function (BABYLON) {
  21297. var OculusRiftDevKit2013_Metric = {
  21298. HResolution: 1280,
  21299. VResolution: 800,
  21300. HScreenSize: 0.149759993,
  21301. VScreenSize: 0.0935999975,
  21302. VScreenCenter: 0.0467999987,
  21303. EyeToScreenDistance: 0.0410000011,
  21304. LensSeparationDistance: 0.0635000020,
  21305. InterpupillaryDistance: 0.0640000030,
  21306. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  21307. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  21308. PostProcessScaleFactor: 1.714605507808412,
  21309. LensCenterOffset: 0.151976421
  21310. };
  21311. var _OculusInnerCamera = (function (_super) {
  21312. __extends(_OculusInnerCamera, _super);
  21313. function _OculusInnerCamera(name, position, scene, isLeftEye) {
  21314. _super.call(this, name, position, scene);
  21315. this._workMatrix = new BABYLON.Matrix();
  21316. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  21317. // Constants
  21318. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  21319. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  21320. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  21321. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  21322. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  21323. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  21324. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  21325. // Postprocess
  21326. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  21327. }
  21328. _OculusInnerCamera.prototype.getProjectionMatrix = function () {
  21329. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  21330. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  21331. return this._projectionMatrix;
  21332. };
  21333. _OculusInnerCamera.prototype._getViewMatrix = function () {
  21334. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  21335. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  21336. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  21337. // Computing target and final matrix
  21338. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  21339. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  21340. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  21341. return this._viewMatrix;
  21342. };
  21343. return _OculusInnerCamera;
  21344. })(BABYLON.FreeCamera);
  21345. var OculusCamera = (function (_super) {
  21346. __extends(OculusCamera, _super);
  21347. function OculusCamera(name, position, scene) {
  21348. _super.call(this, name, position, scene);
  21349. this._leftCamera = new _OculusInnerCamera(name + "_left", position.clone(), scene, true);
  21350. this._rightCamera = new _OculusInnerCamera(name + "_right", position.clone(), scene, false);
  21351. this.subCameras.push(this._leftCamera);
  21352. this.subCameras.push(this._rightCamera);
  21353. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  21354. }
  21355. OculusCamera.prototype._update = function () {
  21356. this._leftCamera.position.copyFrom(this.position);
  21357. this._rightCamera.position.copyFrom(this.position);
  21358. this._updateCamera(this._leftCamera);
  21359. this._updateCamera(this._rightCamera);
  21360. _super.prototype._update.call(this);
  21361. };
  21362. OculusCamera.prototype._updateCamera = function (camera) {
  21363. camera.minZ = this.minZ;
  21364. camera.maxZ = this.maxZ;
  21365. camera.rotation.x = this.rotation.x;
  21366. camera.rotation.y = this.rotation.y;
  21367. camera.rotation.z = this.rotation.z;
  21368. };
  21369. // Oculus events
  21370. OculusCamera.prototype._onOrientationEvent = function (evt) {
  21371. var yaw = evt.alpha / 180 * Math.PI;
  21372. var pitch = evt.beta / 180 * Math.PI;
  21373. var roll = evt.gamma / 180 * Math.PI;
  21374. if (!this._offsetOrientation) {
  21375. this._offsetOrientation = {
  21376. yaw: yaw,
  21377. pitch: pitch,
  21378. roll: roll
  21379. };
  21380. return;
  21381. }
  21382. else {
  21383. this.rotation.y += yaw - this._offsetOrientation.yaw;
  21384. this.rotation.x += pitch - this._offsetOrientation.pitch;
  21385. this.rotation.z += this._offsetOrientation.roll - roll;
  21386. this._offsetOrientation.yaw = yaw;
  21387. this._offsetOrientation.pitch = pitch;
  21388. this._offsetOrientation.roll = roll;
  21389. }
  21390. };
  21391. OculusCamera.prototype.attachControl = function (element, noPreventDefault) {
  21392. _super.prototype.attachControl.call(this, element, noPreventDefault);
  21393. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  21394. };
  21395. OculusCamera.prototype.detachControl = function (element) {
  21396. _super.prototype.detachControl.call(this, element);
  21397. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  21398. };
  21399. return OculusCamera;
  21400. })(BABYLON.FreeCamera);
  21401. BABYLON.OculusCamera = OculusCamera;
  21402. })(BABYLON || (BABYLON = {}));
  21403. //# sourceMappingURL=babylon.oculusCamera.js.map
  21404. var BABYLON;
  21405. (function (BABYLON) {
  21406. var OculusRiftDevKit2013_Metric = {
  21407. HResolution: 1280,
  21408. VResolution: 800,
  21409. HScreenSize: 0.149759993,
  21410. VScreenSize: 0.0935999975,
  21411. VScreenCenter: 0.0467999987,
  21412. EyeToScreenDistance: 0.0410000011,
  21413. LensSeparationDistance: 0.0635000020,
  21414. InterpupillaryDistance: 0.0640000030,
  21415. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  21416. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  21417. PostProcessScaleFactor: 1.714605507808412,
  21418. LensCenterOffset: 0.151976421
  21419. };
  21420. var _OculusInnerGamepadCamera = (function (_super) {
  21421. __extends(_OculusInnerGamepadCamera, _super);
  21422. function _OculusInnerGamepadCamera(name, position, scene, isLeftEye) {
  21423. _super.call(this, name, position, scene);
  21424. this._workMatrix = new BABYLON.Matrix();
  21425. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  21426. // Constants
  21427. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  21428. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  21429. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  21430. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  21431. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  21432. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  21433. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  21434. // Postprocess
  21435. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  21436. }
  21437. _OculusInnerGamepadCamera.prototype.getProjectionMatrix = function () {
  21438. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  21439. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  21440. return this._projectionMatrix;
  21441. };
  21442. _OculusInnerGamepadCamera.prototype._getViewMatrix = function () {
  21443. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  21444. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  21445. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  21446. // Computing target and final matrix
  21447. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  21448. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  21449. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  21450. return this._viewMatrix;
  21451. };
  21452. return _OculusInnerGamepadCamera;
  21453. })(BABYLON.FreeCamera);
  21454. var OculusGamepadCamera = (function (_super) {
  21455. __extends(OculusGamepadCamera, _super);
  21456. function OculusGamepadCamera(name, position, scene) {
  21457. var _this = this;
  21458. _super.call(this, name, position, scene);
  21459. this.angularSensibility = 200;
  21460. this.moveSensibility = 75;
  21461. this._leftCamera = new _OculusInnerGamepadCamera(name + "_left", position.clone(), scene, true);
  21462. this._rightCamera = new _OculusInnerGamepadCamera(name + "_right", position.clone(), scene, false);
  21463. this.subCameras.push(this._leftCamera);
  21464. this.subCameras.push(this._rightCamera);
  21465. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  21466. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  21467. _this._onNewGameConnected(gamepad);
  21468. });
  21469. }
  21470. OculusGamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  21471. // Only the first gamepad can control the camera
  21472. if (gamepad.index === 0) {
  21473. this._gamepad = gamepad;
  21474. }
  21475. };
  21476. OculusGamepadCamera.prototype._update = function () {
  21477. this._leftCamera.position.copyFrom(this.position);
  21478. this._rightCamera.position.copyFrom(this.position);
  21479. this._updateCamera(this._leftCamera);
  21480. this._updateCamera(this._rightCamera);
  21481. _super.prototype._update.call(this);
  21482. };
  21483. OculusGamepadCamera.prototype._checkInputs = function () {
  21484. if (!this._gamepad) {
  21485. return;
  21486. }
  21487. var LSValues = this._gamepad.leftStick;
  21488. var normalizedLX = LSValues.x / this.moveSensibility;
  21489. var normalizedLY = LSValues.y / this.moveSensibility;
  21490. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  21491. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  21492. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  21493. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x, 0, -LSValues.y), cameraTransform);
  21494. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  21495. };
  21496. OculusGamepadCamera.prototype._updateCamera = function (camera) {
  21497. camera.minZ = this.minZ;
  21498. camera.maxZ = this.maxZ;
  21499. camera.rotation.x = this.rotation.x;
  21500. camera.rotation.y = this.rotation.y;
  21501. camera.rotation.z = this.rotation.z;
  21502. };
  21503. // Oculus events
  21504. OculusGamepadCamera.prototype._onOrientationEvent = function (evt) {
  21505. var yaw = evt.alpha / 180 * Math.PI;
  21506. var pitch = evt.beta / 180 * Math.PI;
  21507. var roll = evt.gamma / 180 * Math.PI;
  21508. if (!this._offsetOrientation) {
  21509. this._offsetOrientation = {
  21510. yaw: yaw,
  21511. pitch: pitch,
  21512. roll: roll
  21513. };
  21514. return;
  21515. }
  21516. else {
  21517. this.rotation.y += yaw - this._offsetOrientation.yaw;
  21518. this.rotation.x += pitch - this._offsetOrientation.pitch;
  21519. this.rotation.z += this._offsetOrientation.roll - roll;
  21520. this._offsetOrientation.yaw = yaw;
  21521. this._offsetOrientation.pitch = pitch;
  21522. this._offsetOrientation.roll = roll;
  21523. }
  21524. };
  21525. OculusGamepadCamera.prototype.attachControl = function (element, noPreventDefault) {
  21526. _super.prototype.attachControl.call(this, element, noPreventDefault);
  21527. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  21528. };
  21529. OculusGamepadCamera.prototype.detachControl = function (element) {
  21530. _super.prototype.detachControl.call(this, element);
  21531. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  21532. };
  21533. OculusGamepadCamera.prototype.dispose = function () {
  21534. this._gamepads.dispose();
  21535. _super.prototype.dispose.call(this);
  21536. };
  21537. return OculusGamepadCamera;
  21538. })(BABYLON.FreeCamera);
  21539. BABYLON.OculusGamepadCamera = OculusGamepadCamera;
  21540. })(BABYLON || (BABYLON = {}));
  21541. //# sourceMappingURL=babylon.oculusGamepadCamera.js.map
  21542. var BABYLON;
  21543. (function (BABYLON) {
  21544. // We're mainly based on the logic defined into the FreeCamera code
  21545. var VirtualJoysticksCamera = (function (_super) {
  21546. __extends(VirtualJoysticksCamera, _super);
  21547. function VirtualJoysticksCamera(name, position, scene) {
  21548. _super.call(this, name, position, scene);
  21549. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  21550. this._leftjoystick.setAxisForUpDown(2 /* Z */);
  21551. this._leftjoystick.setAxisForLeftRight(0 /* X */);
  21552. this._leftjoystick.setJoystickSensibility(0.15);
  21553. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  21554. this._rightjoystick.setAxisForUpDown(0 /* X */);
  21555. this._rightjoystick.setAxisForLeftRight(1 /* Y */);
  21556. this._rightjoystick.reverseUpDown = true;
  21557. this._rightjoystick.setJoystickSensibility(0.05);
  21558. this._rightjoystick.setJoystickColor("yellow");
  21559. }
  21560. VirtualJoysticksCamera.prototype._checkInputs = function () {
  21561. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  21562. var deltaTransform = BABYLON.Vector3.TransformCoordinates(this._leftjoystick.deltaPosition, cameraTransform);
  21563. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  21564. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  21565. if (!this._leftjoystick.pressed) {
  21566. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  21567. }
  21568. if (!this._rightjoystick.pressed) {
  21569. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  21570. }
  21571. };
  21572. VirtualJoysticksCamera.prototype.dispose = function () {
  21573. this._leftjoystick.releaseCanvas();
  21574. _super.prototype.dispose.call(this);
  21575. };
  21576. return VirtualJoysticksCamera;
  21577. })(BABYLON.FreeCamera);
  21578. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  21579. })(BABYLON || (BABYLON = {}));
  21580. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  21581. var BABYLON;
  21582. (function (BABYLON) {
  21583. var ShaderMaterial = (function (_super) {
  21584. __extends(ShaderMaterial, _super);
  21585. function ShaderMaterial(name, scene, shaderPath, options) {
  21586. _super.call(this, name, scene);
  21587. this._textures = new Array();
  21588. this._floats = new Array();
  21589. this._floatsArrays = {};
  21590. this._colors3 = new Array();
  21591. this._colors4 = new Array();
  21592. this._vectors2 = new Array();
  21593. this._vectors3 = new Array();
  21594. this._matrices = new Array();
  21595. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  21596. this._shaderPath = shaderPath;
  21597. options.needAlphaBlending = options.needAlphaBlending || false;
  21598. options.needAlphaTesting = options.needAlphaTesting || false;
  21599. options.attributes = options.attributes || ["position", "normal", "uv"];
  21600. options.uniforms = options.uniforms || ["worldViewProjection"];
  21601. options.samplers = options.samplers || [];
  21602. this._options = options;
  21603. }
  21604. ShaderMaterial.prototype.needAlphaBlending = function () {
  21605. return this._options.needAlphaBlending;
  21606. };
  21607. ShaderMaterial.prototype.needAlphaTesting = function () {
  21608. return this._options.needAlphaTesting;
  21609. };
  21610. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  21611. if (this._options.uniforms.indexOf(uniformName) === -1) {
  21612. this._options.uniforms.push(uniformName);
  21613. }
  21614. };
  21615. ShaderMaterial.prototype.setTexture = function (name, texture) {
  21616. if (this._options.samplers.indexOf(name) === -1) {
  21617. this._options.samplers.push(name);
  21618. }
  21619. this._textures[name] = texture;
  21620. return this;
  21621. };
  21622. ShaderMaterial.prototype.setFloat = function (name, value) {
  21623. this._checkUniform(name);
  21624. this._floats[name] = value;
  21625. return this;
  21626. };
  21627. ShaderMaterial.prototype.setFloats = function (name, value) {
  21628. this._checkUniform(name);
  21629. this._floatsArrays[name] = value;
  21630. return this;
  21631. };
  21632. ShaderMaterial.prototype.setColor3 = function (name, value) {
  21633. this._checkUniform(name);
  21634. this._colors3[name] = value;
  21635. return this;
  21636. };
  21637. ShaderMaterial.prototype.setColor4 = function (name, value) {
  21638. this._checkUniform(name);
  21639. this._colors4[name] = value;
  21640. return this;
  21641. };
  21642. ShaderMaterial.prototype.setVector2 = function (name, value) {
  21643. this._checkUniform(name);
  21644. this._vectors2[name] = value;
  21645. return this;
  21646. };
  21647. ShaderMaterial.prototype.setVector3 = function (name, value) {
  21648. this._checkUniform(name);
  21649. this._vectors3[name] = value;
  21650. return this;
  21651. };
  21652. ShaderMaterial.prototype.setMatrix = function (name, value) {
  21653. this._checkUniform(name);
  21654. this._matrices[name] = value;
  21655. return this;
  21656. };
  21657. ShaderMaterial.prototype.isReady = function () {
  21658. var scene = this.getScene();
  21659. var engine = scene.getEngine();
  21660. if (!this.checkReadyOnEveryCall) {
  21661. if (this._renderId === scene.getRenderId()) {
  21662. return true;
  21663. }
  21664. }
  21665. var previousEffect = this._effect;
  21666. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, "", null, this.onCompiled, this.onError);
  21667. if (!this._effect.isReady()) {
  21668. return false;
  21669. }
  21670. if (previousEffect !== this._effect) {
  21671. scene.resetCachedMaterial();
  21672. }
  21673. this._renderId = scene.getRenderId();
  21674. return true;
  21675. };
  21676. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  21677. var scene = this.getScene();
  21678. if (this._options.uniforms.indexOf("world") !== -1) {
  21679. this._effect.setMatrix("world", world);
  21680. }
  21681. if (this._options.uniforms.indexOf("worldView") !== -1) {
  21682. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  21683. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  21684. }
  21685. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  21686. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  21687. }
  21688. };
  21689. ShaderMaterial.prototype.bind = function (world) {
  21690. // Std values
  21691. this.bindOnlyWorldMatrix(world);
  21692. if (this.getScene().getCachedMaterial() !== this) {
  21693. if (this._options.uniforms.indexOf("view") !== -1) {
  21694. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  21695. }
  21696. if (this._options.uniforms.indexOf("projection") !== -1) {
  21697. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  21698. }
  21699. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  21700. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  21701. }
  21702. for (var name in this._textures) {
  21703. this._effect.setTexture(name, this._textures[name]);
  21704. }
  21705. for (name in this._floats) {
  21706. this._effect.setFloat(name, this._floats[name]);
  21707. }
  21708. for (name in this._floatsArrays) {
  21709. this._effect.setArray(name, this._floatsArrays[name]);
  21710. }
  21711. for (name in this._colors3) {
  21712. this._effect.setColor3(name, this._colors3[name]);
  21713. }
  21714. for (name in this._colors4) {
  21715. var color = this._colors4[name];
  21716. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  21717. }
  21718. for (name in this._vectors2) {
  21719. this._effect.setVector2(name, this._vectors2[name]);
  21720. }
  21721. for (name in this._vectors3) {
  21722. this._effect.setVector3(name, this._vectors3[name]);
  21723. }
  21724. for (name in this._matrices) {
  21725. this._effect.setMatrix(name, this._matrices[name]);
  21726. }
  21727. }
  21728. _super.prototype.bind.call(this, world, null);
  21729. };
  21730. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  21731. for (var name in this._textures) {
  21732. this._textures[name].dispose();
  21733. }
  21734. this._textures = [];
  21735. _super.prototype.dispose.call(this, forceDisposeEffect);
  21736. };
  21737. return ShaderMaterial;
  21738. })(BABYLON.Material);
  21739. BABYLON.ShaderMaterial = ShaderMaterial;
  21740. })(BABYLON || (BABYLON = {}));
  21741. //# sourceMappingURL=babylon.shaderMaterial.js.mapvar BABYLON;
  21742. (function (BABYLON) {
  21743. var VertexData = (function () {
  21744. function VertexData() {
  21745. }
  21746. VertexData.prototype.set = function (data, kind) {
  21747. switch (kind) {
  21748. case BABYLON.VertexBuffer.PositionKind:
  21749. this.positions = data;
  21750. break;
  21751. case BABYLON.VertexBuffer.NormalKind:
  21752. this.normals = data;
  21753. break;
  21754. case BABYLON.VertexBuffer.UVKind:
  21755. this.uvs = data;
  21756. break;
  21757. case BABYLON.VertexBuffer.UV2Kind:
  21758. this.uv2s = data;
  21759. break;
  21760. case BABYLON.VertexBuffer.ColorKind:
  21761. this.colors = data;
  21762. break;
  21763. case BABYLON.VertexBuffer.MatricesIndicesKind:
  21764. this.matricesIndices = data;
  21765. break;
  21766. case BABYLON.VertexBuffer.MatricesWeightsKind:
  21767. this.matricesWeights = data;
  21768. break;
  21769. }
  21770. };
  21771. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  21772. this._applyTo(mesh, updatable);
  21773. };
  21774. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  21775. this._applyTo(geometry, updatable);
  21776. };
  21777. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  21778. this._update(mesh);
  21779. };
  21780. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  21781. this._update(geometry);
  21782. };
  21783. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  21784. if (this.positions) {
  21785. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  21786. }
  21787. if (this.normals) {
  21788. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  21789. }
  21790. if (this.uvs) {
  21791. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  21792. }
  21793. if (this.uv2s) {
  21794. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updatable);
  21795. }
  21796. if (this.colors) {
  21797. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  21798. }
  21799. if (this.matricesIndices) {
  21800. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  21801. }
  21802. if (this.matricesWeights) {
  21803. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  21804. }
  21805. if (this.indices) {
  21806. meshOrGeometry.setIndices(this.indices);
  21807. }
  21808. };
  21809. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  21810. if (this.positions) {
  21811. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  21812. }
  21813. if (this.normals) {
  21814. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  21815. }
  21816. if (this.uvs) {
  21817. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  21818. }
  21819. if (this.uv2s) {
  21820. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updateExtends, makeItUnique);
  21821. }
  21822. if (this.colors) {
  21823. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  21824. }
  21825. if (this.matricesIndices) {
  21826. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  21827. }
  21828. if (this.matricesWeights) {
  21829. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  21830. }
  21831. if (this.indices) {
  21832. meshOrGeometry.setIndices(this.indices);
  21833. }
  21834. };
  21835. VertexData.prototype.transform = function (matrix) {
  21836. var transformed = BABYLON.Vector3.Zero();
  21837. if (this.positions) {
  21838. var position = BABYLON.Vector3.Zero();
  21839. for (var index = 0; index < this.positions.length; index += 3) {
  21840. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  21841. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  21842. this.positions[index] = transformed.x;
  21843. this.positions[index + 1] = transformed.y;
  21844. this.positions[index + 2] = transformed.z;
  21845. }
  21846. }
  21847. if (this.normals) {
  21848. var normal = BABYLON.Vector3.Zero();
  21849. for (index = 0; index < this.normals.length; index += 3) {
  21850. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  21851. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  21852. this.normals[index] = transformed.x;
  21853. this.normals[index + 1] = transformed.y;
  21854. this.normals[index + 2] = transformed.z;
  21855. }
  21856. }
  21857. };
  21858. VertexData.prototype.merge = function (other) {
  21859. if (other.indices) {
  21860. if (!this.indices) {
  21861. this.indices = [];
  21862. }
  21863. var offset = this.positions ? this.positions.length / 3 : 0;
  21864. for (var index = 0; index < other.indices.length; index++) {
  21865. this.indices.push(other.indices[index] + offset);
  21866. }
  21867. }
  21868. if (other.positions) {
  21869. if (!this.positions) {
  21870. this.positions = [];
  21871. }
  21872. for (index = 0; index < other.positions.length; index++) {
  21873. this.positions.push(other.positions[index]);
  21874. }
  21875. }
  21876. if (other.normals) {
  21877. if (!this.normals) {
  21878. this.normals = [];
  21879. }
  21880. for (index = 0; index < other.normals.length; index++) {
  21881. this.normals.push(other.normals[index]);
  21882. }
  21883. }
  21884. if (other.uvs) {
  21885. if (!this.uvs) {
  21886. this.uvs = [];
  21887. }
  21888. for (index = 0; index < other.uvs.length; index++) {
  21889. this.uvs.push(other.uvs[index]);
  21890. }
  21891. }
  21892. if (other.uv2s) {
  21893. if (!this.uv2s) {
  21894. this.uv2s = [];
  21895. }
  21896. for (index = 0; index < other.uv2s.length; index++) {
  21897. this.uv2s.push(other.uv2s[index]);
  21898. }
  21899. }
  21900. if (other.matricesIndices) {
  21901. if (!this.matricesIndices) {
  21902. this.matricesIndices = [];
  21903. }
  21904. for (index = 0; index < other.matricesIndices.length; index++) {
  21905. this.matricesIndices.push(other.matricesIndices[index]);
  21906. }
  21907. }
  21908. if (other.matricesWeights) {
  21909. if (!this.matricesWeights) {
  21910. this.matricesWeights = [];
  21911. }
  21912. for (index = 0; index < other.matricesWeights.length; index++) {
  21913. this.matricesWeights.push(other.matricesWeights[index]);
  21914. }
  21915. }
  21916. if (other.colors) {
  21917. if (!this.colors) {
  21918. this.colors = [];
  21919. }
  21920. for (index = 0; index < other.colors.length; index++) {
  21921. this.colors.push(other.colors[index]);
  21922. }
  21923. }
  21924. };
  21925. // Statics
  21926. VertexData.ExtractFromMesh = function (mesh) {
  21927. return VertexData._ExtractFrom(mesh);
  21928. };
  21929. VertexData.ExtractFromGeometry = function (geometry) {
  21930. return VertexData._ExtractFrom(geometry);
  21931. };
  21932. VertexData._ExtractFrom = function (meshOrGeometry) {
  21933. var result = new VertexData();
  21934. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  21935. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21936. }
  21937. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21938. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21939. }
  21940. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  21941. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind);
  21942. }
  21943. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  21944. result.uv2s = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  21945. }
  21946. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  21947. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  21948. }
  21949. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  21950. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  21951. }
  21952. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  21953. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  21954. }
  21955. result.indices = meshOrGeometry.getIndices();
  21956. return result;
  21957. };
  21958. VertexData.CreateRibbon = function (pathArray, closeArray, closePath, offset, sideOrientation) {
  21959. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  21960. closeArray = closeArray || false;
  21961. closePath = closePath || false;
  21962. var defaultOffset = Math.floor(pathArray[0].length / 2);
  21963. offset = offset || defaultOffset;
  21964. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  21965. var positions = [];
  21966. var indices = [];
  21967. var normals = [];
  21968. var uvs = [];
  21969. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  21970. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  21971. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  21972. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  21973. var minlg; // minimal length among all paths from pathArray
  21974. var lg = []; // array of path lengths : nb of vertex per path
  21975. var idx = []; // array of path indexes : index of each path (first vertex) in positions array
  21976. var p; // path iterator
  21977. var i; // point iterator
  21978. var j; // point iterator
  21979. // if single path in pathArray
  21980. if (pathArray.length < 2) {
  21981. var ar1 = [];
  21982. var ar2 = [];
  21983. for (i = 0; i < pathArray[0].length - offset; i++) {
  21984. ar1.push(pathArray[0][i]);
  21985. ar2.push(pathArray[0][i + offset]);
  21986. }
  21987. pathArray = [ar1, ar2];
  21988. }
  21989. // positions and horizontal distances (u)
  21990. var idc = 0;
  21991. minlg = pathArray[0].length;
  21992. for (p = 0; p < pathArray.length; p++) {
  21993. uTotalDistance[p] = 0;
  21994. us[p] = [0];
  21995. var path = pathArray[p];
  21996. var l = path.length;
  21997. minlg = (minlg < l) ? minlg : l;
  21998. lg[p] = l;
  21999. idx[p] = idc;
  22000. j = 0;
  22001. while (j < l) {
  22002. positions.push(path[j].x, path[j].y, path[j].z);
  22003. if (j > 0) {
  22004. var vectlg = path[j].subtract(path[j - 1]).length();
  22005. var dist = vectlg + uTotalDistance[p];
  22006. us[p].push(dist);
  22007. uTotalDistance[p] = dist;
  22008. }
  22009. j++;
  22010. }
  22011. if (closePath) {
  22012. vectlg = path[0].subtract(path[j - 1]).length();
  22013. dist = vectlg + uTotalDistance[p];
  22014. uTotalDistance[p] = dist;
  22015. }
  22016. idc += l;
  22017. }
  22018. for (i = 0; i < minlg; i++) {
  22019. vTotalDistance[i] = 0;
  22020. vs[i] = [0];
  22021. var path1;
  22022. var path2;
  22023. for (p = 0; p < pathArray.length - 1; p++) {
  22024. path1 = pathArray[p];
  22025. path2 = pathArray[p + 1];
  22026. vectlg = path2[i].subtract(path1[i]).length();
  22027. dist = vectlg + vTotalDistance[i];
  22028. vs[i].push(dist);
  22029. vTotalDistance[i] = dist;
  22030. }
  22031. if (closeArray) {
  22032. path1 = pathArray[p];
  22033. path2 = pathArray[0];
  22034. vectlg = path2[i].subtract(path1[i]).length();
  22035. dist = vectlg + vTotalDistance[i];
  22036. vTotalDistance[i] = dist;
  22037. }
  22038. }
  22039. // uvs
  22040. var u;
  22041. var v;
  22042. for (p = 0; p < pathArray.length; p++) {
  22043. for (i = 0; i < minlg; i++) {
  22044. u = us[p][i] / uTotalDistance[p];
  22045. v = vs[i][p] / vTotalDistance[i];
  22046. uvs.push(u, v);
  22047. }
  22048. }
  22049. // indices
  22050. p = 0; // path index
  22051. var pi = 0; // positions array index
  22052. var l1 = lg[p] - 1; // path1 length
  22053. var l2 = lg[p + 1] - 1; // path2 length
  22054. var min = (l1 < l2) ? l1 : l2; // current path stop index
  22055. var shft = idx[1] - idx[0]; // shift
  22056. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate
  22057. var t1; // two consecutive triangles, so 4 points : point1
  22058. var t2; // point2
  22059. var t3; // point3
  22060. var t4; // point4
  22061. while (pi <= min && p < path1nb) {
  22062. // 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
  22063. t1 = pi;
  22064. t2 = pi + shft;
  22065. t3 = pi + 1;
  22066. t4 = pi + shft + 1;
  22067. indices.push(pi, pi + shft, pi + 1);
  22068. indices.push(pi + shft + 1, pi + 1, pi + shft);
  22069. pi += 1;
  22070. if (pi === min) {
  22071. if (closePath) {
  22072. indices.push(pi, pi + shft, idx[p]);
  22073. indices.push(idx[p] + shft, idx[p], pi + shft);
  22074. t3 = idx[p];
  22075. t4 = idx[p] + shft;
  22076. }
  22077. p++;
  22078. if (p === lg.length - 1) {
  22079. shft = idx[0] - idx[p];
  22080. l1 = lg[p] - 1;
  22081. l2 = lg[0] - 1;
  22082. }
  22083. else {
  22084. shft = idx[p + 1] - idx[p];
  22085. l1 = lg[p] - 1;
  22086. l2 = lg[p + 1] - 1;
  22087. }
  22088. pi = idx[p];
  22089. min = (l1 < l2) ? l1 + pi : l2 + pi;
  22090. }
  22091. }
  22092. // normals
  22093. VertexData.ComputeNormals(positions, indices, normals);
  22094. // sides
  22095. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  22096. // Result
  22097. var vertexData = new VertexData();
  22098. vertexData.indices = indices;
  22099. vertexData.positions = positions;
  22100. vertexData.normals = normals;
  22101. vertexData.uvs = uvs;
  22102. return vertexData;
  22103. };
  22104. VertexData.CreateBox = function (size, sideOrientation) {
  22105. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  22106. var normalsSource = [
  22107. new BABYLON.Vector3(0, 0, 1),
  22108. new BABYLON.Vector3(0, 0, -1),
  22109. new BABYLON.Vector3(1, 0, 0),
  22110. new BABYLON.Vector3(-1, 0, 0),
  22111. new BABYLON.Vector3(0, 1, 0),
  22112. new BABYLON.Vector3(0, -1, 0)
  22113. ];
  22114. var indices = [];
  22115. var positions = [];
  22116. var normals = [];
  22117. var uvs = [];
  22118. size = size || 1;
  22119. for (var index = 0; index < normalsSource.length; index++) {
  22120. var normal = normalsSource[index];
  22121. // Get two vectors perpendicular to the face normal and to each other.
  22122. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  22123. var side2 = BABYLON.Vector3.Cross(normal, side1);
  22124. // Six indices (two triangles) per face.
  22125. var verticesLength = positions.length / 3;
  22126. indices.push(verticesLength);
  22127. indices.push(verticesLength + 1);
  22128. indices.push(verticesLength + 2);
  22129. indices.push(verticesLength);
  22130. indices.push(verticesLength + 2);
  22131. indices.push(verticesLength + 3);
  22132. // Four vertices per face.
  22133. var vertex = normal.subtract(side1).subtract(side2).scale(size / 2);
  22134. positions.push(vertex.x, vertex.y, vertex.z);
  22135. normals.push(normal.x, normal.y, normal.z);
  22136. uvs.push(1.0, 1.0);
  22137. vertex = normal.subtract(side1).add(side2).scale(size / 2);
  22138. positions.push(vertex.x, vertex.y, vertex.z);
  22139. normals.push(normal.x, normal.y, normal.z);
  22140. uvs.push(0.0, 1.0);
  22141. vertex = normal.add(side1).add(side2).scale(size / 2);
  22142. positions.push(vertex.x, vertex.y, vertex.z);
  22143. normals.push(normal.x, normal.y, normal.z);
  22144. uvs.push(0.0, 0.0);
  22145. vertex = normal.add(side1).subtract(side2).scale(size / 2);
  22146. positions.push(vertex.x, vertex.y, vertex.z);
  22147. normals.push(normal.x, normal.y, normal.z);
  22148. uvs.push(1.0, 0.0);
  22149. }
  22150. // sides
  22151. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  22152. // Result
  22153. var vertexData = new VertexData();
  22154. vertexData.indices = indices;
  22155. vertexData.positions = positions;
  22156. vertexData.normals = normals;
  22157. vertexData.uvs = uvs;
  22158. return vertexData;
  22159. };
  22160. VertexData.CreateSphere = function (segments, diameter, sideOrientation) {
  22161. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  22162. segments = segments || 32;
  22163. diameter = diameter || 1;
  22164. var radius = diameter / 2;
  22165. var totalZRotationSteps = 2 + segments;
  22166. var totalYRotationSteps = 2 * totalZRotationSteps;
  22167. var indices = [];
  22168. var positions = [];
  22169. var normals = [];
  22170. var uvs = [];
  22171. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  22172. var normalizedZ = zRotationStep / totalZRotationSteps;
  22173. var angleZ = (normalizedZ * Math.PI);
  22174. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  22175. var normalizedY = yRotationStep / totalYRotationSteps;
  22176. var angleY = normalizedY * Math.PI * 2;
  22177. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  22178. var rotationY = BABYLON.Matrix.RotationY(angleY);
  22179. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  22180. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  22181. var vertex = complete.scale(radius);
  22182. var normal = BABYLON.Vector3.Normalize(vertex);
  22183. positions.push(vertex.x, vertex.y, vertex.z);
  22184. normals.push(normal.x, normal.y, normal.z);
  22185. uvs.push(normalizedZ, normalizedY);
  22186. }
  22187. if (zRotationStep > 0) {
  22188. var verticesCount = positions.length / 3;
  22189. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  22190. indices.push((firstIndex));
  22191. indices.push((firstIndex + 1));
  22192. indices.push(firstIndex + totalYRotationSteps + 1);
  22193. indices.push((firstIndex + totalYRotationSteps + 1));
  22194. indices.push((firstIndex + 1));
  22195. indices.push((firstIndex + totalYRotationSteps + 2));
  22196. }
  22197. }
  22198. }
  22199. // Sides
  22200. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  22201. // Result
  22202. var vertexData = new VertexData();
  22203. vertexData.indices = indices;
  22204. vertexData.positions = positions;
  22205. vertexData.normals = normals;
  22206. vertexData.uvs = uvs;
  22207. return vertexData;
  22208. };
  22209. VertexData.CreateCylinder = function (height, diameterTop, diameterBottom, tessellation, subdivisions, sideOrientation) {
  22210. if (subdivisions === void 0) { subdivisions = 1; }
  22211. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  22212. var radiusTop = diameterTop / 2;
  22213. var radiusBottom = diameterBottom / 2;
  22214. var indices = [];
  22215. var positions = [];
  22216. var normals = [];
  22217. var uvs = [];
  22218. height = height || 1;
  22219. diameterTop = diameterTop || 0.5;
  22220. diameterBottom = diameterBottom || 1;
  22221. tessellation = tessellation || 16;
  22222. subdivisions = subdivisions || 1;
  22223. subdivisions = (subdivisions < 1) ? 1 : subdivisions;
  22224. var getCircleVector = function (i) {
  22225. var angle = (i * 2.0 * Math.PI / tessellation);
  22226. var dx = Math.cos(angle);
  22227. var dz = Math.sin(angle);
  22228. return new BABYLON.Vector3(dx, 0, dz);
  22229. };
  22230. var createCylinderCap = function (isTop) {
  22231. var radius = isTop ? radiusTop : radiusBottom;
  22232. if (radius === 0) {
  22233. return;
  22234. }
  22235. var vbase = positions.length / 3;
  22236. var offset = new BABYLON.Vector3(0, height / 2, 0);
  22237. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  22238. if (!isTop) {
  22239. offset.scaleInPlace(-1);
  22240. textureScale.x = -textureScale.x;
  22241. }
  22242. for (var i = 0; i < tessellation; i++) {
  22243. var circleVector = getCircleVector(i);
  22244. var position = circleVector.scale(radius).add(offset);
  22245. var textureCoordinate = new BABYLON.Vector2(circleVector.x * textureScale.x + 0.5, circleVector.z * textureScale.y + 0.5);
  22246. positions.push(position.x, position.y, position.z);
  22247. uvs.push(textureCoordinate.x, textureCoordinate.y);
  22248. }
  22249. for (i = 0; i < tessellation - 2; i++) {
  22250. if (!isTop) {
  22251. indices.push(vbase);
  22252. indices.push(vbase + (i + 2) % tessellation);
  22253. indices.push(vbase + (i + 1) % tessellation);
  22254. }
  22255. else {
  22256. indices.push(vbase);
  22257. indices.push(vbase + (i + 1) % tessellation);
  22258. indices.push(vbase + (i + 2) % tessellation);
  22259. }
  22260. }
  22261. };
  22262. var base = new BABYLON.Vector3(0, -1, 0).scale(height / 2);
  22263. var offset = new BABYLON.Vector3(0, 1, 0).scale(height / subdivisions);
  22264. var stride = tessellation + 1;
  22265. for (var i = 0; i <= tessellation; i++) {
  22266. var circleVector = getCircleVector(i);
  22267. var textureCoordinate = new BABYLON.Vector2(i / tessellation, 0);
  22268. var position, radius = radiusBottom;
  22269. for (var s = 0; s <= subdivisions; s++) {
  22270. // Update variables
  22271. position = circleVector.scale(radius);
  22272. position.addInPlace(base.add(offset.scale(s)));
  22273. textureCoordinate.y += 1 / subdivisions;
  22274. radius += (radiusTop - radiusBottom) / subdivisions;
  22275. // Push in arrays
  22276. positions.push(position.x, position.y, position.z);
  22277. uvs.push(textureCoordinate.x, textureCoordinate.y);
  22278. }
  22279. }
  22280. subdivisions += 1;
  22281. for (s = 0; s < subdivisions - 1; s++) {
  22282. for (i = 0; i <= tessellation; i++) {
  22283. indices.push(i * subdivisions + s);
  22284. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  22285. indices.push(i * subdivisions + (s + 1));
  22286. indices.push(i * subdivisions + (s + 1));
  22287. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  22288. indices.push((i * subdivisions + (s + subdivisions + 1)) % (stride * subdivisions));
  22289. }
  22290. }
  22291. // Create flat triangle fan caps to seal the top and bottom.
  22292. createCylinderCap(true);
  22293. createCylinderCap(false);
  22294. // Normals
  22295. VertexData.ComputeNormals(positions, indices, normals);
  22296. // Sides
  22297. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  22298. // Result
  22299. var vertexData = new VertexData();
  22300. vertexData.indices = indices;
  22301. vertexData.positions = positions;
  22302. vertexData.normals = normals;
  22303. vertexData.uvs = uvs;
  22304. return vertexData;
  22305. };
  22306. VertexData.CreateTorus = function (diameter, thickness, tessellation, sideOrientation) {
  22307. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  22308. var indices = [];
  22309. var positions = [];
  22310. var normals = [];
  22311. var uvs = [];
  22312. diameter = diameter || 1;
  22313. thickness = thickness || 0.5;
  22314. tessellation = tessellation || 16;
  22315. var stride = tessellation + 1;
  22316. for (var i = 0; i <= tessellation; i++) {
  22317. var u = i / tessellation;
  22318. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  22319. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  22320. for (var j = 0; j <= tessellation; j++) {
  22321. var v = 1 - j / tessellation;
  22322. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  22323. var dx = Math.cos(innerAngle);
  22324. var dy = Math.sin(innerAngle);
  22325. // Create a vertex.
  22326. var normal = new BABYLON.Vector3(dx, dy, 0);
  22327. var position = normal.scale(thickness / 2);
  22328. var textureCoordinate = new BABYLON.Vector2(u, v);
  22329. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  22330. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  22331. positions.push(position.x, position.y, position.z);
  22332. normals.push(normal.x, normal.y, normal.z);
  22333. uvs.push(textureCoordinate.x, textureCoordinate.y);
  22334. // And create indices for two triangles.
  22335. var nextI = (i + 1) % stride;
  22336. var nextJ = (j + 1) % stride;
  22337. indices.push(i * stride + j);
  22338. indices.push(i * stride + nextJ);
  22339. indices.push(nextI * stride + j);
  22340. indices.push(i * stride + nextJ);
  22341. indices.push(nextI * stride + nextJ);
  22342. indices.push(nextI * stride + j);
  22343. }
  22344. }
  22345. // Sides
  22346. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  22347. // Result
  22348. var vertexData = new VertexData();
  22349. vertexData.indices = indices;
  22350. vertexData.positions = positions;
  22351. vertexData.normals = normals;
  22352. vertexData.uvs = uvs;
  22353. return vertexData;
  22354. };
  22355. VertexData.CreateLines = function (points) {
  22356. var indices = [];
  22357. var positions = [];
  22358. for (var index = 0; index < points.length; index++) {
  22359. positions.push(points[index].x, points[index].y, points[index].z);
  22360. if (index > 0) {
  22361. indices.push(index - 1);
  22362. indices.push(index);
  22363. }
  22364. }
  22365. // Result
  22366. var vertexData = new VertexData();
  22367. vertexData.indices = indices;
  22368. vertexData.positions = positions;
  22369. return vertexData;
  22370. };
  22371. VertexData.CreateGround = function (width, height, subdivisions) {
  22372. var indices = [];
  22373. var positions = [];
  22374. var normals = [];
  22375. var uvs = [];
  22376. var row, col;
  22377. width = width || 1;
  22378. height = height || 1;
  22379. subdivisions = subdivisions || 1;
  22380. for (row = 0; row <= subdivisions; row++) {
  22381. for (col = 0; col <= subdivisions; col++) {
  22382. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  22383. var normal = new BABYLON.Vector3(0, 1.0, 0);
  22384. positions.push(position.x, position.y, position.z);
  22385. normals.push(normal.x, normal.y, normal.z);
  22386. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  22387. }
  22388. }
  22389. for (row = 0; row < subdivisions; row++) {
  22390. for (col = 0; col < subdivisions; col++) {
  22391. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  22392. indices.push(col + 1 + row * (subdivisions + 1));
  22393. indices.push(col + row * (subdivisions + 1));
  22394. indices.push(col + (row + 1) * (subdivisions + 1));
  22395. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  22396. indices.push(col + row * (subdivisions + 1));
  22397. }
  22398. }
  22399. // Result
  22400. var vertexData = new VertexData();
  22401. vertexData.indices = indices;
  22402. vertexData.positions = positions;
  22403. vertexData.normals = normals;
  22404. vertexData.uvs = uvs;
  22405. return vertexData;
  22406. };
  22407. VertexData.CreateTiledGround = function (xmin, zmin, xmax, zmax, subdivisions, precision) {
  22408. if (subdivisions === void 0) { subdivisions = { w: 1, h: 1 }; }
  22409. if (precision === void 0) { precision = { w: 1, h: 1 }; }
  22410. var indices = [];
  22411. var positions = [];
  22412. var normals = [];
  22413. var uvs = [];
  22414. var row, col, tileRow, tileCol;
  22415. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  22416. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  22417. precision.w = (precision.w < 1) ? 1 : precision.w;
  22418. precision.h = (precision.h < 1) ? 1 : precision.h;
  22419. var tileSize = {
  22420. 'w': (xmax - xmin) / subdivisions.w,
  22421. 'h': (zmax - zmin) / subdivisions.h
  22422. };
  22423. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  22424. // Indices
  22425. var base = positions.length / 3;
  22426. var rowLength = precision.w + 1;
  22427. for (row = 0; row < precision.h; row++) {
  22428. for (col = 0; col < precision.w; col++) {
  22429. var square = [
  22430. base + col + row * rowLength,
  22431. base + (col + 1) + row * rowLength,
  22432. base + (col + 1) + (row + 1) * rowLength,
  22433. base + col + (row + 1) * rowLength
  22434. ];
  22435. indices.push(square[1]);
  22436. indices.push(square[2]);
  22437. indices.push(square[3]);
  22438. indices.push(square[0]);
  22439. indices.push(square[1]);
  22440. indices.push(square[3]);
  22441. }
  22442. }
  22443. // Position, normals and uvs
  22444. var position = BABYLON.Vector3.Zero();
  22445. var normal = new BABYLON.Vector3(0, 1.0, 0);
  22446. for (row = 0; row <= precision.h; row++) {
  22447. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  22448. for (col = 0; col <= precision.w; col++) {
  22449. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  22450. position.y = 0;
  22451. positions.push(position.x, position.y, position.z);
  22452. normals.push(normal.x, normal.y, normal.z);
  22453. uvs.push(col / precision.w, row / precision.h);
  22454. }
  22455. }
  22456. }
  22457. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  22458. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  22459. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  22460. }
  22461. }
  22462. // Result
  22463. var vertexData = new VertexData();
  22464. vertexData.indices = indices;
  22465. vertexData.positions = positions;
  22466. vertexData.normals = normals;
  22467. vertexData.uvs = uvs;
  22468. return vertexData;
  22469. };
  22470. VertexData.CreateGroundFromHeightMap = function (width, height, subdivisions, minHeight, maxHeight, buffer, bufferWidth, bufferHeight) {
  22471. var indices = [];
  22472. var positions = [];
  22473. var normals = [];
  22474. var uvs = [];
  22475. var row, col;
  22476. for (row = 0; row <= subdivisions; row++) {
  22477. for (col = 0; col <= subdivisions; col++) {
  22478. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  22479. // Compute height
  22480. var heightMapX = (((position.x + width / 2) / width) * (bufferWidth - 1)) | 0;
  22481. var heightMapY = ((1.0 - (position.z + height / 2) / height) * (bufferHeight - 1)) | 0;
  22482. var pos = (heightMapX + heightMapY * bufferWidth) * 4;
  22483. var r = buffer[pos] / 255.0;
  22484. var g = buffer[pos + 1] / 255.0;
  22485. var b = buffer[pos + 2] / 255.0;
  22486. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  22487. position.y = minHeight + (maxHeight - minHeight) * gradient;
  22488. // Add vertex
  22489. positions.push(position.x, position.y, position.z);
  22490. normals.push(0, 0, 0);
  22491. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  22492. }
  22493. }
  22494. for (row = 0; row < subdivisions; row++) {
  22495. for (col = 0; col < subdivisions; col++) {
  22496. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  22497. indices.push(col + 1 + row * (subdivisions + 1));
  22498. indices.push(col + row * (subdivisions + 1));
  22499. indices.push(col + (row + 1) * (subdivisions + 1));
  22500. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  22501. indices.push(col + row * (subdivisions + 1));
  22502. }
  22503. }
  22504. // Normals
  22505. VertexData.ComputeNormals(positions, indices, normals);
  22506. // Result
  22507. var vertexData = new VertexData();
  22508. vertexData.indices = indices;
  22509. vertexData.positions = positions;
  22510. vertexData.normals = normals;
  22511. vertexData.uvs = uvs;
  22512. return vertexData;
  22513. };
  22514. VertexData.CreatePlane = function (size, sideOrientation) {
  22515. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  22516. var indices = [];
  22517. var positions = [];
  22518. var normals = [];
  22519. var uvs = [];
  22520. size = size || 1;
  22521. // Vertices
  22522. var halfSize = size / 2.0;
  22523. positions.push(-halfSize, -halfSize, 0);
  22524. normals.push(0, 0, -1.0);
  22525. uvs.push(0.0, 0.0);
  22526. positions.push(halfSize, -halfSize, 0);
  22527. normals.push(0, 0, -1.0);
  22528. uvs.push(1.0, 0.0);
  22529. positions.push(halfSize, halfSize, 0);
  22530. normals.push(0, 0, -1.0);
  22531. uvs.push(1.0, 1.0);
  22532. positions.push(-halfSize, halfSize, 0);
  22533. normals.push(0, 0, -1.0);
  22534. uvs.push(0.0, 1.0);
  22535. // Indices
  22536. indices.push(0);
  22537. indices.push(1);
  22538. indices.push(2);
  22539. indices.push(0);
  22540. indices.push(2);
  22541. indices.push(3);
  22542. // Sides
  22543. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  22544. // Result
  22545. var vertexData = new VertexData();
  22546. vertexData.indices = indices;
  22547. vertexData.positions = positions;
  22548. vertexData.normals = normals;
  22549. vertexData.uvs = uvs;
  22550. return vertexData;
  22551. };
  22552. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  22553. VertexData.CreateTorusKnot = function (radius, tube, radialSegments, tubularSegments, p, q, sideOrientation) {
  22554. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  22555. var indices = [];
  22556. var positions = [];
  22557. var normals = [];
  22558. var uvs = [];
  22559. radius = radius || 2;
  22560. tube = tube || 0.5;
  22561. radialSegments = radialSegments || 32;
  22562. tubularSegments = tubularSegments || 32;
  22563. p = p || 2;
  22564. q = q || 3;
  22565. // Helper
  22566. var getPos = function (angle) {
  22567. var cu = Math.cos(angle);
  22568. var su = Math.sin(angle);
  22569. var quOverP = q / p * angle;
  22570. var cs = Math.cos(quOverP);
  22571. var tx = radius * (2 + cs) * 0.5 * cu;
  22572. var ty = radius * (2 + cs) * su * 0.5;
  22573. var tz = radius * Math.sin(quOverP) * 0.5;
  22574. return new BABYLON.Vector3(tx, ty, tz);
  22575. };
  22576. for (var i = 0; i <= radialSegments; i++) {
  22577. var modI = i % radialSegments;
  22578. var u = modI / radialSegments * 2 * p * Math.PI;
  22579. var p1 = getPos(u);
  22580. var p2 = getPos(u + 0.01);
  22581. var tang = p2.subtract(p1);
  22582. var n = p2.add(p1);
  22583. var bitan = BABYLON.Vector3.Cross(tang, n);
  22584. n = BABYLON.Vector3.Cross(bitan, tang);
  22585. bitan.normalize();
  22586. n.normalize();
  22587. for (var j = 0; j < tubularSegments; j++) {
  22588. var modJ = j % tubularSegments;
  22589. var v = modJ / tubularSegments * 2 * Math.PI;
  22590. var cx = -tube * Math.cos(v);
  22591. var cy = tube * Math.sin(v);
  22592. positions.push(p1.x + cx * n.x + cy * bitan.x);
  22593. positions.push(p1.y + cx * n.y + cy * bitan.y);
  22594. positions.push(p1.z + cx * n.z + cy * bitan.z);
  22595. uvs.push(i / radialSegments);
  22596. uvs.push(j / tubularSegments);
  22597. }
  22598. }
  22599. for (i = 0; i < radialSegments; i++) {
  22600. for (j = 0; j < tubularSegments; j++) {
  22601. var jNext = (j + 1) % tubularSegments;
  22602. var a = i * tubularSegments + j;
  22603. var b = (i + 1) * tubularSegments + j;
  22604. var c = (i + 1) * tubularSegments + jNext;
  22605. var d = i * tubularSegments + jNext;
  22606. indices.push(d);
  22607. indices.push(b);
  22608. indices.push(a);
  22609. indices.push(d);
  22610. indices.push(c);
  22611. indices.push(b);
  22612. }
  22613. }
  22614. // Normals
  22615. VertexData.ComputeNormals(positions, indices, normals);
  22616. // Sides
  22617. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  22618. // Result
  22619. var vertexData = new VertexData();
  22620. vertexData.indices = indices;
  22621. vertexData.positions = positions;
  22622. vertexData.normals = normals;
  22623. vertexData.uvs = uvs;
  22624. return vertexData;
  22625. };
  22626. // Tools
  22627. VertexData.ComputeNormals = function (positions, indices, normals) {
  22628. var positionVectors = [];
  22629. var facesOfVertices = [];
  22630. var index;
  22631. for (index = 0; index < positions.length; index += 3) {
  22632. var vector3 = new BABYLON.Vector3(positions[index], positions[index + 1], positions[index + 2]);
  22633. positionVectors.push(vector3);
  22634. facesOfVertices.push([]);
  22635. }
  22636. // Compute normals
  22637. var facesNormals = [];
  22638. for (index = 0; index < indices.length / 3; index++) {
  22639. var i1 = indices[index * 3];
  22640. var i2 = indices[index * 3 + 1];
  22641. var i3 = indices[index * 3 + 2];
  22642. var p1 = positionVectors[i1];
  22643. var p2 = positionVectors[i2];
  22644. var p3 = positionVectors[i3];
  22645. var p1p2 = p1.subtract(p2);
  22646. var p3p2 = p3.subtract(p2);
  22647. facesNormals[index] = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  22648. facesOfVertices[i1].push(index);
  22649. facesOfVertices[i2].push(index);
  22650. facesOfVertices[i3].push(index);
  22651. }
  22652. for (index = 0; index < positionVectors.length; index++) {
  22653. var faces = facesOfVertices[index];
  22654. var normal = BABYLON.Vector3.Zero();
  22655. for (var faceIndex = 0; faceIndex < faces.length; faceIndex++) {
  22656. normal.addInPlace(facesNormals[faces[faceIndex]]);
  22657. }
  22658. normal = BABYLON.Vector3.Normalize(normal.scale(1.0 / faces.length));
  22659. normals[index * 3] = normal.x;
  22660. normals[index * 3 + 1] = normal.y;
  22661. normals[index * 3 + 2] = normal.z;
  22662. }
  22663. };
  22664. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  22665. var li = indices.length;
  22666. var ln = normals.length;
  22667. var i;
  22668. var n;
  22669. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  22670. switch (sideOrientation) {
  22671. case BABYLON.Mesh.FRONTSIDE:
  22672. break;
  22673. case BABYLON.Mesh.BACKSIDE:
  22674. var tmp;
  22675. for (i = 0; i < li; i += 3) {
  22676. tmp = indices[i];
  22677. indices[i] = indices[i + 2];
  22678. indices[i + 2] = tmp;
  22679. }
  22680. for (n = 0; n < ln; n++) {
  22681. normals[n] = -normals[n];
  22682. }
  22683. break;
  22684. case BABYLON.Mesh.DOUBLESIDE:
  22685. // positions
  22686. var lp = positions.length;
  22687. var l = lp / 3;
  22688. for (var p = 0; p < lp; p++) {
  22689. positions[lp + p] = positions[p];
  22690. }
  22691. for (i = 0; i < li; i += 3) {
  22692. indices[i + li] = indices[i + 2] + l;
  22693. indices[i + 1 + li] = indices[i + 1] + l;
  22694. indices[i + 2 + li] = indices[i] + l;
  22695. }
  22696. for (n = 0; n < ln; n++) {
  22697. normals[ln + n] = -normals[n];
  22698. }
  22699. // uvs
  22700. var lu = uvs.length;
  22701. for (var u = 0; u < lu; u++) {
  22702. uvs[u + lu] = uvs[u];
  22703. }
  22704. break;
  22705. }
  22706. };
  22707. return VertexData;
  22708. })();
  22709. BABYLON.VertexData = VertexData;
  22710. })(BABYLON || (BABYLON = {}));
  22711. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  22712. var BABYLON;
  22713. (function (BABYLON) {
  22714. var buildCamera = function (that, name) {
  22715. that._leftCamera.isIntermediate = true;
  22716. that.subCameras.push(that._leftCamera);
  22717. that.subCameras.push(that._rightCamera);
  22718. that._leftTexture = new BABYLON.PassPostProcess(name + "_leftTexture", 1.0, that._leftCamera);
  22719. that._anaglyphPostProcess = new BABYLON.AnaglyphPostProcess(name + "_anaglyph", 1.0, that._rightCamera);
  22720. that._anaglyphPostProcess.onApply = function (effect) {
  22721. effect.setTextureFromPostProcess("leftSampler", that._leftTexture);
  22722. };
  22723. that._update();
  22724. };
  22725. var AnaglyphArcRotateCamera = (function (_super) {
  22726. __extends(AnaglyphArcRotateCamera, _super);
  22727. // ANY
  22728. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, eyeSpace, scene) {
  22729. _super.call(this, name, alpha, beta, radius, target, scene);
  22730. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  22731. this._leftCamera = new BABYLON.ArcRotateCamera(name + "_left", alpha - this._eyeSpace, beta, radius, target, scene);
  22732. this._rightCamera = new BABYLON.ArcRotateCamera(name + "_right", alpha + this._eyeSpace, beta, radius, target, scene);
  22733. buildCamera(this, name);
  22734. }
  22735. AnaglyphArcRotateCamera.prototype._update = function () {
  22736. this._updateCamera(this._leftCamera);
  22737. this._updateCamera(this._rightCamera);
  22738. this._leftCamera.alpha = this.alpha - this._eyeSpace;
  22739. this._rightCamera.alpha = this.alpha + this._eyeSpace;
  22740. _super.prototype._update.call(this);
  22741. };
  22742. AnaglyphArcRotateCamera.prototype._updateCamera = function (camera) {
  22743. camera.beta = this.beta;
  22744. camera.radius = this.radius;
  22745. camera.minZ = this.minZ;
  22746. camera.maxZ = this.maxZ;
  22747. camera.fov = this.fov;
  22748. camera.target = this.target;
  22749. };
  22750. return AnaglyphArcRotateCamera;
  22751. })(BABYLON.ArcRotateCamera);
  22752. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  22753. var AnaglyphFreeCamera = (function (_super) {
  22754. __extends(AnaglyphFreeCamera, _super);
  22755. function AnaglyphFreeCamera(name, position, eyeSpace, scene) {
  22756. _super.call(this, name, position, scene);
  22757. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  22758. this._transformMatrix = new BABYLON.Matrix();
  22759. this._leftCamera = new BABYLON.FreeCamera(name + "_left", position.clone(), scene);
  22760. this._rightCamera = new BABYLON.FreeCamera(name + "_right", position.clone(), scene);
  22761. buildCamera(this, name);
  22762. }
  22763. AnaglyphFreeCamera.prototype._getSubCameraPosition = function (eyeSpace, result) {
  22764. var target = this.getTarget();
  22765. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(eyeSpace), this._transformMatrix);
  22766. this._transformMatrix = this._transformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  22767. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._transformMatrix, result);
  22768. };
  22769. AnaglyphFreeCamera.prototype._update = function () {
  22770. this._getSubCameraPosition(-this._eyeSpace, this._leftCamera.position);
  22771. this._getSubCameraPosition(this._eyeSpace, this._rightCamera.position);
  22772. this._updateCamera(this._leftCamera);
  22773. this._updateCamera(this._rightCamera);
  22774. _super.prototype._update.call(this);
  22775. };
  22776. AnaglyphFreeCamera.prototype._updateCamera = function (camera) {
  22777. camera.minZ = this.minZ;
  22778. camera.maxZ = this.maxZ;
  22779. camera.fov = this.fov;
  22780. camera.viewport = this.viewport;
  22781. camera.setTarget(this.getTarget());
  22782. };
  22783. return AnaglyphFreeCamera;
  22784. })(BABYLON.FreeCamera);
  22785. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  22786. })(BABYLON || (BABYLON = {}));
  22787. //# sourceMappingURL=babylon.anaglyphCamera.js.map
  22788. var BABYLON;
  22789. (function (BABYLON) {
  22790. var AnaglyphPostProcess = (function (_super) {
  22791. __extends(AnaglyphPostProcess, _super);
  22792. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  22793. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  22794. }
  22795. return AnaglyphPostProcess;
  22796. })(BABYLON.PostProcess);
  22797. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  22798. })(BABYLON || (BABYLON = {}));
  22799. //# sourceMappingURL=babylon.anaglyphPostProcess.js.mapvar BABYLON;
  22800. (function (BABYLON) {
  22801. var Tags = (function () {
  22802. function Tags() {
  22803. }
  22804. Tags.EnableFor = function (obj) {
  22805. obj._tags = obj._tags || {};
  22806. obj.hasTags = function () {
  22807. return Tags.HasTags(obj);
  22808. };
  22809. obj.addTags = function (tagsString) {
  22810. return Tags.AddTagsTo(obj, tagsString);
  22811. };
  22812. obj.removeTags = function (tagsString) {
  22813. return Tags.RemoveTagsFrom(obj, tagsString);
  22814. };
  22815. obj.matchesTagsQuery = function (tagsQuery) {
  22816. return Tags.MatchesQuery(obj, tagsQuery);
  22817. };
  22818. };
  22819. Tags.DisableFor = function (obj) {
  22820. delete obj._tags;
  22821. delete obj.hasTags;
  22822. delete obj.addTags;
  22823. delete obj.removeTags;
  22824. delete obj.matchesTagsQuery;
  22825. };
  22826. Tags.HasTags = function (obj) {
  22827. if (!obj._tags) {
  22828. return false;
  22829. }
  22830. return !BABYLON.Tools.IsEmpty(obj._tags);
  22831. };
  22832. Tags.GetTags = function (obj) {
  22833. if (!obj._tags) {
  22834. return null;
  22835. }
  22836. return obj._tags;
  22837. };
  22838. // the tags 'true' and 'false' are reserved and cannot be used as tags
  22839. // a tag cannot start with '||', '&&', and '!'
  22840. // it cannot contain whitespaces
  22841. Tags.AddTagsTo = function (obj, tagsString) {
  22842. if (!tagsString) {
  22843. return;
  22844. }
  22845. var tags = tagsString.split(" ");
  22846. for (var t in tags) {
  22847. Tags._AddTagTo(obj, tags[t]);
  22848. }
  22849. };
  22850. Tags._AddTagTo = function (obj, tag) {
  22851. tag = tag.trim();
  22852. if (tag === "" || tag === "true" || tag === "false") {
  22853. return;
  22854. }
  22855. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  22856. return;
  22857. }
  22858. Tags.EnableFor(obj);
  22859. obj._tags[tag] = true;
  22860. };
  22861. Tags.RemoveTagsFrom = function (obj, tagsString) {
  22862. if (!Tags.HasTags(obj)) {
  22863. return;
  22864. }
  22865. var tags = tagsString.split(" ");
  22866. for (var t in tags) {
  22867. Tags._RemoveTagFrom(obj, tags[t]);
  22868. }
  22869. };
  22870. Tags._RemoveTagFrom = function (obj, tag) {
  22871. delete obj._tags[tag];
  22872. };
  22873. Tags.MatchesQuery = function (obj, tagsQuery) {
  22874. if (tagsQuery === undefined) {
  22875. return true;
  22876. }
  22877. if (tagsQuery === "") {
  22878. return Tags.HasTags(obj);
  22879. }
  22880. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  22881. };
  22882. return Tags;
  22883. })();
  22884. BABYLON.Tags = Tags;
  22885. })(BABYLON || (BABYLON = {}));
  22886. //# sourceMappingURL=babylon.tags.js.mapvar BABYLON;
  22887. (function (BABYLON) {
  22888. var Internals;
  22889. (function (Internals) {
  22890. var AndOrNotEvaluator = (function () {
  22891. function AndOrNotEvaluator() {
  22892. }
  22893. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  22894. if (!query.match(/\([^\(\)]*\)/g)) {
  22895. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  22896. }
  22897. else {
  22898. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  22899. // remove parenthesis
  22900. r = r.slice(1, r.length - 1);
  22901. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  22902. });
  22903. }
  22904. if (query === "true") {
  22905. return true;
  22906. }
  22907. if (query === "false") {
  22908. return false;
  22909. }
  22910. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  22911. };
  22912. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  22913. evaluateCallback = evaluateCallback || (function (r) {
  22914. return r === "true" ? true : false;
  22915. });
  22916. var result;
  22917. var or = parenthesisContent.split("||");
  22918. for (var i in or) {
  22919. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  22920. var and = ori.split("&&");
  22921. if (and.length > 1) {
  22922. for (var j = 0; j < and.length; ++j) {
  22923. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  22924. if (andj !== "true" && andj !== "false") {
  22925. if (andj[0] === "!") {
  22926. result = !evaluateCallback(andj.substring(1));
  22927. }
  22928. else {
  22929. result = evaluateCallback(andj);
  22930. }
  22931. }
  22932. else {
  22933. result = andj === "true" ? true : false;
  22934. }
  22935. if (!result) {
  22936. ori = "false";
  22937. break;
  22938. }
  22939. }
  22940. }
  22941. if (result || ori === "true") {
  22942. result = true;
  22943. break;
  22944. }
  22945. // result equals false (or undefined)
  22946. if (ori !== "true" && ori !== "false") {
  22947. if (ori[0] === "!") {
  22948. result = !evaluateCallback(ori.substring(1));
  22949. }
  22950. else {
  22951. result = evaluateCallback(ori);
  22952. }
  22953. }
  22954. else {
  22955. result = ori === "true" ? true : false;
  22956. }
  22957. }
  22958. // the whole parenthesis scope is replaced by 'true' or 'false'
  22959. return result ? "true" : "false";
  22960. };
  22961. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  22962. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  22963. // remove whitespaces
  22964. r = r.replace(/[\s]/g, function () { return ""; });
  22965. return r.length % 2 ? "!" : "";
  22966. });
  22967. booleanString = booleanString.trim();
  22968. if (booleanString === "!true") {
  22969. booleanString = "false";
  22970. }
  22971. else if (booleanString === "!false") {
  22972. booleanString = "true";
  22973. }
  22974. return booleanString;
  22975. };
  22976. return AndOrNotEvaluator;
  22977. })();
  22978. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  22979. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  22980. })(BABYLON || (BABYLON = {}));
  22981. //# sourceMappingURL=babylon.andOrNotEvaluator.js.mapvar BABYLON;
  22982. (function (BABYLON) {
  22983. var PostProcessRenderPass = (function () {
  22984. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  22985. this._enabled = true;
  22986. this._refCount = 0;
  22987. this._name = name;
  22988. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  22989. this.setRenderList(renderList);
  22990. this._renderTexture.onBeforeRender = beforeRender;
  22991. this._renderTexture.onAfterRender = afterRender;
  22992. this._scene = scene;
  22993. this._renderList = renderList;
  22994. }
  22995. // private
  22996. PostProcessRenderPass.prototype._incRefCount = function () {
  22997. if (this._refCount === 0) {
  22998. this._scene.customRenderTargets.push(this._renderTexture);
  22999. }
  23000. return ++this._refCount;
  23001. };
  23002. PostProcessRenderPass.prototype._decRefCount = function () {
  23003. this._refCount--;
  23004. if (this._refCount <= 0) {
  23005. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  23006. }
  23007. return this._refCount;
  23008. };
  23009. PostProcessRenderPass.prototype._update = function () {
  23010. this.setRenderList(this._renderList);
  23011. };
  23012. // public
  23013. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  23014. this._renderTexture.renderList = renderList;
  23015. };
  23016. PostProcessRenderPass.prototype.getRenderTexture = function () {
  23017. return this._renderTexture;
  23018. };
  23019. return PostProcessRenderPass;
  23020. })();
  23021. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  23022. })(BABYLON || (BABYLON = {}));
  23023. //# sourceMappingURL=babylon.postProcessRenderPass.js.mapvar BABYLON;
  23024. (function (BABYLON) {
  23025. var PostProcessRenderEffect = (function () {
  23026. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  23027. this._engine = engine;
  23028. this._name = name;
  23029. this._singleInstance = singleInstance || true;
  23030. this._getPostProcess = getPostProcess;
  23031. this._cameras = [];
  23032. this._indicesForCamera = [];
  23033. this._postProcesses = {};
  23034. this._renderPasses = {};
  23035. this._renderEffectAsPasses = {};
  23036. }
  23037. PostProcessRenderEffect.prototype._update = function () {
  23038. for (var renderPassName in this._renderPasses) {
  23039. this._renderPasses[renderPassName]._update();
  23040. }
  23041. };
  23042. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  23043. this._renderPasses[renderPass._name] = renderPass;
  23044. this._linkParameters();
  23045. };
  23046. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  23047. delete this._renderPasses[renderPass._name];
  23048. this._linkParameters();
  23049. };
  23050. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  23051. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  23052. this._linkParameters();
  23053. };
  23054. PostProcessRenderEffect.prototype.getPass = function (passName) {
  23055. for (var renderPassName in this._renderPasses) {
  23056. if (renderPassName === passName) {
  23057. return this._renderPasses[passName];
  23058. }
  23059. }
  23060. };
  23061. PostProcessRenderEffect.prototype.emptyPasses = function () {
  23062. this._renderPasses = {};
  23063. this._linkParameters();
  23064. };
  23065. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  23066. var cameraKey;
  23067. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  23068. for (var i = 0; i < _cam.length; i++) {
  23069. var camera = _cam[i];
  23070. var cameraName = camera.name;
  23071. if (this._singleInstance) {
  23072. cameraKey = 0;
  23073. }
  23074. else {
  23075. cameraKey = cameraName;
  23076. }
  23077. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  23078. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  23079. if (!this._indicesForCamera[cameraName]) {
  23080. this._indicesForCamera[cameraName] = [];
  23081. }
  23082. this._indicesForCamera[cameraName].push(index);
  23083. if (this._cameras.indexOf(camera) === -1) {
  23084. this._cameras[cameraName] = camera;
  23085. }
  23086. for (var passName in this._renderPasses) {
  23087. this._renderPasses[passName]._incRefCount();
  23088. }
  23089. }
  23090. this._linkParameters();
  23091. };
  23092. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  23093. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  23094. for (var i = 0; i < _cam.length; i++) {
  23095. var camera = _cam[i];
  23096. var cameraName = camera.name;
  23097. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  23098. var index = this._cameras.indexOf(cameraName);
  23099. this._indicesForCamera.splice(index, 1);
  23100. this._cameras.splice(index, 1);
  23101. for (var passName in this._renderPasses) {
  23102. this._renderPasses[passName]._decRefCount();
  23103. }
  23104. }
  23105. };
  23106. PostProcessRenderEffect.prototype._enable = function (cameras) {
  23107. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  23108. for (var i = 0; i < _cam.length; i++) {
  23109. var camera = _cam[i];
  23110. var cameraName = camera.name;
  23111. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  23112. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  23113. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  23114. }
  23115. }
  23116. for (var passName in this._renderPasses) {
  23117. this._renderPasses[passName]._incRefCount();
  23118. }
  23119. }
  23120. };
  23121. PostProcessRenderEffect.prototype._disable = function (cameras) {
  23122. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  23123. for (var i = 0; i < _cam.length; i++) {
  23124. var camera = _cam[i];
  23125. var cameraName = camera.Name;
  23126. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  23127. for (var passName in this._renderPasses) {
  23128. this._renderPasses[passName]._decRefCount();
  23129. }
  23130. }
  23131. };
  23132. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  23133. if (this._singleInstance) {
  23134. return this._postProcesses[0];
  23135. }
  23136. else {
  23137. return this._postProcesses[camera.name];
  23138. }
  23139. };
  23140. PostProcessRenderEffect.prototype._linkParameters = function () {
  23141. var _this = this;
  23142. for (var index in this._postProcesses) {
  23143. if (this.applyParameters) {
  23144. this.applyParameters(this._postProcesses[index]);
  23145. }
  23146. this._postProcesses[index].onBeforeRender = function (effect) {
  23147. _this._linkTextures(effect);
  23148. };
  23149. }
  23150. };
  23151. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  23152. for (var renderPassName in this._renderPasses) {
  23153. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  23154. }
  23155. for (var renderEffectName in this._renderEffectAsPasses) {
  23156. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  23157. }
  23158. };
  23159. return PostProcessRenderEffect;
  23160. })();
  23161. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  23162. })(BABYLON || (BABYLON = {}));
  23163. //# sourceMappingURL=babylon.postProcessRenderEffect.js.mapvar BABYLON;
  23164. (function (BABYLON) {
  23165. var PostProcessRenderPipeline = (function () {
  23166. function PostProcessRenderPipeline(engine, name) {
  23167. this._engine = engine;
  23168. this._name = name;
  23169. this._renderEffects = {};
  23170. this._renderEffectsForIsolatedPass = {};
  23171. this._cameras = [];
  23172. }
  23173. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  23174. this._renderEffects[renderEffect._name] = renderEffect;
  23175. };
  23176. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  23177. var renderEffects = this._renderEffects[renderEffectName];
  23178. if (!renderEffects) {
  23179. return;
  23180. }
  23181. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  23182. };
  23183. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  23184. var renderEffects = this._renderEffects[renderEffectName];
  23185. if (!renderEffects) {
  23186. return;
  23187. }
  23188. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  23189. };
  23190. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  23191. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  23192. var indicesToDelete = [];
  23193. for (var i = 0; i < _cam.length; i++) {
  23194. var camera = _cam[i];
  23195. var cameraName = camera.name;
  23196. if (this._cameras.indexOf(camera) === -1) {
  23197. this._cameras[cameraName] = camera;
  23198. }
  23199. else if (unique) {
  23200. indicesToDelete.push(i);
  23201. }
  23202. }
  23203. for (var i = 0; i < indicesToDelete.length; i++) {
  23204. cameras.splice(indicesToDelete[i], 1);
  23205. }
  23206. for (var renderEffectName in this._renderEffects) {
  23207. this._renderEffects[renderEffectName]._attachCameras(_cam);
  23208. }
  23209. };
  23210. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  23211. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  23212. for (var renderEffectName in this._renderEffects) {
  23213. this._renderEffects[renderEffectName]._detachCameras(_cam);
  23214. }
  23215. for (var i = 0; i < _cam.length; i++) {
  23216. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  23217. }
  23218. };
  23219. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  23220. var _this = this;
  23221. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  23222. var pass = null;
  23223. for (var renderEffectName in this._renderEffects) {
  23224. pass = this._renderEffects[renderEffectName].getPass(passName);
  23225. if (pass != null) {
  23226. break;
  23227. }
  23228. }
  23229. if (pass === null) {
  23230. return;
  23231. }
  23232. for (var renderEffectName in this._renderEffects) {
  23233. this._renderEffects[renderEffectName]._disable(_cam);
  23234. }
  23235. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  23236. for (var i = 0; i < _cam.length; i++) {
  23237. var camera = _cam[i];
  23238. var cameraName = camera.name;
  23239. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  23240. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  23241. });
  23242. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  23243. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  23244. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  23245. }
  23246. };
  23247. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  23248. var _this = this;
  23249. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  23250. for (var i = 0; i < _cam.length; i++) {
  23251. var camera = _cam[i];
  23252. var cameraName = camera.name;
  23253. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  23254. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  23255. });
  23256. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  23257. }
  23258. for (var renderEffectName in this._renderEffects) {
  23259. this._renderEffects[renderEffectName]._enable(_cam);
  23260. }
  23261. };
  23262. PostProcessRenderPipeline.prototype._update = function () {
  23263. for (var renderEffectName in this._renderEffects) {
  23264. this._renderEffects[renderEffectName]._update();
  23265. }
  23266. for (var i = 0; i < this._cameras.length; i++) {
  23267. var cameraName = this._cameras[i].name;
  23268. if (this._renderEffectsForIsolatedPass[cameraName]) {
  23269. this._renderEffectsForIsolatedPass[cameraName]._update();
  23270. }
  23271. }
  23272. };
  23273. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  23274. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  23275. return PostProcessRenderPipeline;
  23276. })();
  23277. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  23278. })(BABYLON || (BABYLON = {}));
  23279. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.mapvar BABYLON;
  23280. (function (BABYLON) {
  23281. var PostProcessRenderPipelineManager = (function () {
  23282. function PostProcessRenderPipelineManager() {
  23283. this._renderPipelines = {};
  23284. }
  23285. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  23286. this._renderPipelines[renderPipeline._name] = renderPipeline;
  23287. };
  23288. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  23289. var renderPipeline = this._renderPipelines[renderPipelineName];
  23290. if (!renderPipeline) {
  23291. return;
  23292. }
  23293. renderPipeline._attachCameras(cameras, unique);
  23294. };
  23295. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  23296. var renderPipeline = this._renderPipelines[renderPipelineName];
  23297. if (!renderPipeline) {
  23298. return;
  23299. }
  23300. renderPipeline._detachCameras(cameras);
  23301. };
  23302. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  23303. var renderPipeline = this._renderPipelines[renderPipelineName];
  23304. if (!renderPipeline) {
  23305. return;
  23306. }
  23307. renderPipeline._enableEffect(renderEffectName, cameras);
  23308. };
  23309. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  23310. var renderPipeline = this._renderPipelines[renderPipelineName];
  23311. if (!renderPipeline) {
  23312. return;
  23313. }
  23314. renderPipeline._disableEffect(renderEffectName, cameras);
  23315. };
  23316. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  23317. var renderPipeline = this._renderPipelines[renderPipelineName];
  23318. if (!renderPipeline) {
  23319. return;
  23320. }
  23321. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  23322. };
  23323. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  23324. var renderPipeline = this._renderPipelines[renderPipelineName];
  23325. if (!renderPipeline) {
  23326. return;
  23327. }
  23328. renderPipeline._disableDisplayOnlyPass(cameras);
  23329. };
  23330. PostProcessRenderPipelineManager.prototype.update = function () {
  23331. for (var renderPipelineName in this._renderPipelines) {
  23332. this._renderPipelines[renderPipelineName]._update();
  23333. }
  23334. };
  23335. return PostProcessRenderPipelineManager;
  23336. })();
  23337. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  23338. })(BABYLON || (BABYLON = {}));
  23339. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  23340. var BABYLON;
  23341. (function (BABYLON) {
  23342. var DisplayPassPostProcess = (function (_super) {
  23343. __extends(DisplayPassPostProcess, _super);
  23344. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  23345. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  23346. }
  23347. return DisplayPassPostProcess;
  23348. })(BABYLON.PostProcess);
  23349. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  23350. })(BABYLON || (BABYLON = {}));
  23351. //# sourceMappingURL=babylon.displayPassPostProcess.js.mapvar BABYLON;
  23352. (function (BABYLON) {
  23353. var BoundingBoxRenderer = (function () {
  23354. function BoundingBoxRenderer(scene) {
  23355. this.frontColor = new BABYLON.Color3(1, 1, 1);
  23356. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  23357. this.showBackLines = true;
  23358. this.renderList = new BABYLON.SmartArray(32);
  23359. this._scene = scene;
  23360. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  23361. attributes: ["position"],
  23362. uniforms: ["worldViewProjection", "color"]
  23363. });
  23364. var engine = this._scene.getEngine();
  23365. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  23366. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  23367. 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]);
  23368. }
  23369. BoundingBoxRenderer.prototype.reset = function () {
  23370. this.renderList.reset();
  23371. };
  23372. BoundingBoxRenderer.prototype.render = function () {
  23373. if (this.renderList.length === 0 || !this._colorShader.isReady()) {
  23374. return;
  23375. }
  23376. var engine = this._scene.getEngine();
  23377. engine.setDepthWrite(false);
  23378. this._colorShader._preBind();
  23379. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  23380. var boundingBox = this.renderList.data[boundingBoxIndex];
  23381. var min = boundingBox.minimum;
  23382. var max = boundingBox.maximum;
  23383. var diff = max.subtract(min);
  23384. var median = min.add(diff.scale(0.5));
  23385. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z).multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z)).multiply(boundingBox.getWorldMatrix());
  23386. // VBOs
  23387. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  23388. if (this.showBackLines) {
  23389. // Back
  23390. engine.setDepthFunctionToGreaterOrEqual();
  23391. this._scene.resetCachedMaterial();
  23392. this._colorShader.setColor4("color", this.backColor.toColor4());
  23393. this._colorShader.bind(worldMatrix);
  23394. // Draw order
  23395. engine.draw(false, 0, 24);
  23396. }
  23397. // Front
  23398. engine.setDepthFunctionToLess();
  23399. this._scene.resetCachedMaterial();
  23400. this._colorShader.setColor4("color", this.frontColor.toColor4());
  23401. this._colorShader.bind(worldMatrix);
  23402. // Draw order
  23403. engine.draw(false, 0, 24);
  23404. }
  23405. this._colorShader.unbind();
  23406. engine.setDepthFunctionToLessOrEqual();
  23407. engine.setDepthWrite(true);
  23408. };
  23409. BoundingBoxRenderer.prototype.dispose = function () {
  23410. this._colorShader.dispose();
  23411. this._vb.dispose();
  23412. this._scene.getEngine()._releaseBuffer(this._ib);
  23413. };
  23414. return BoundingBoxRenderer;
  23415. })();
  23416. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  23417. })(BABYLON || (BABYLON = {}));
  23418. //# sourceMappingURL=babylon.boundingBoxRenderer.js.mapvar BABYLON;
  23419. (function (BABYLON) {
  23420. var Internals;
  23421. (function (Internals) {
  23422. /*
  23423. * Based on jsTGALoader - Javascript loader for TGA file
  23424. * By Vincent Thibault
  23425. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  23426. */
  23427. var TGATools = (function () {
  23428. function TGATools() {
  23429. }
  23430. TGATools.GetTGAHeader = function (data) {
  23431. var offset = 0;
  23432. var header = {
  23433. id_length: data[offset++],
  23434. colormap_type: data[offset++],
  23435. image_type: data[offset++],
  23436. colormap_index: data[offset++] | data[offset++] << 8,
  23437. colormap_length: data[offset++] | data[offset++] << 8,
  23438. colormap_size: data[offset++],
  23439. origin: [
  23440. data[offset++] | data[offset++] << 8,
  23441. data[offset++] | data[offset++] << 8
  23442. ],
  23443. width: data[offset++] | data[offset++] << 8,
  23444. height: data[offset++] | data[offset++] << 8,
  23445. pixel_size: data[offset++],
  23446. flags: data[offset++]
  23447. };
  23448. return header;
  23449. };
  23450. TGATools.UploadContent = function (gl, data) {
  23451. // Not enough data to contain header ?
  23452. if (data.length < 19) {
  23453. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  23454. return;
  23455. }
  23456. // Read Header
  23457. var offset = 18;
  23458. var header = TGATools.GetTGAHeader(data);
  23459. // Assume it's a valid Targa file.
  23460. if (header.id_length + offset > data.length) {
  23461. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  23462. return;
  23463. }
  23464. // Skip not needed data
  23465. offset += header.id_length;
  23466. var use_rle = false;
  23467. var use_pal = false;
  23468. var use_rgb = false;
  23469. var use_grey = false;
  23470. switch (header.image_type) {
  23471. case TGATools._TYPE_RLE_INDEXED:
  23472. use_rle = true;
  23473. case TGATools._TYPE_INDEXED:
  23474. use_pal = true;
  23475. break;
  23476. case TGATools._TYPE_RLE_RGB:
  23477. use_rle = true;
  23478. case TGATools._TYPE_RGB:
  23479. use_rgb = true;
  23480. break;
  23481. case TGATools._TYPE_RLE_GREY:
  23482. use_rle = true;
  23483. case TGATools._TYPE_GREY:
  23484. use_grey = true;
  23485. break;
  23486. }
  23487. var pixel_data;
  23488. var numAlphaBits = header.flags & 0xf;
  23489. var pixel_size = header.pixel_size >> 3;
  23490. var pixel_total = header.width * header.height * pixel_size;
  23491. // Read palettes
  23492. var palettes;
  23493. if (use_pal) {
  23494. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  23495. }
  23496. // Read LRE
  23497. if (use_rle) {
  23498. pixel_data = new Uint8Array(pixel_total);
  23499. var c, count, i;
  23500. var localOffset = 0;
  23501. var pixels = new Uint8Array(pixel_size);
  23502. while (offset < pixel_total && localOffset < pixel_total) {
  23503. c = data[offset++];
  23504. count = (c & 0x7f) + 1;
  23505. // RLE pixels
  23506. if (c & 0x80) {
  23507. for (i = 0; i < pixel_size; ++i) {
  23508. pixels[i] = data[offset++];
  23509. }
  23510. for (i = 0; i < count; ++i) {
  23511. pixel_data.set(pixels, localOffset + i * pixel_size);
  23512. }
  23513. localOffset += pixel_size * count;
  23514. }
  23515. else {
  23516. count *= pixel_size;
  23517. for (i = 0; i < count; ++i) {
  23518. pixel_data[localOffset + i] = data[offset++];
  23519. }
  23520. localOffset += count;
  23521. }
  23522. }
  23523. }
  23524. else {
  23525. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  23526. }
  23527. // Load to texture
  23528. var x_start, y_start, x_step, y_step, y_end, x_end;
  23529. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  23530. default:
  23531. case TGATools._ORIGIN_UL:
  23532. x_start = 0;
  23533. x_step = 1;
  23534. x_end = header.width;
  23535. y_start = 0;
  23536. y_step = 1;
  23537. y_end = header.height;
  23538. break;
  23539. case TGATools._ORIGIN_BL:
  23540. x_start = 0;
  23541. x_step = 1;
  23542. x_end = header.width;
  23543. y_start = header.height - 1;
  23544. y_step = -1;
  23545. y_end = -1;
  23546. break;
  23547. case TGATools._ORIGIN_UR:
  23548. x_start = header.width - 1;
  23549. x_step = -1;
  23550. x_end = -1;
  23551. y_start = 0;
  23552. y_step = 1;
  23553. y_end = header.height;
  23554. break;
  23555. case TGATools._ORIGIN_BR:
  23556. x_start = header.width - 1;
  23557. x_step = -1;
  23558. x_end = -1;
  23559. y_start = header.height - 1;
  23560. y_step = -1;
  23561. y_end = -1;
  23562. break;
  23563. }
  23564. // Load the specify method
  23565. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  23566. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  23567. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  23568. };
  23569. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  23570. var image = pixel_data, colormap = palettes;
  23571. var width = header.width, height = header.height;
  23572. var color, i = 0, x, y;
  23573. var imageData = new Uint8Array(width * height * 4);
  23574. for (y = y_start; y !== y_end; y += y_step) {
  23575. for (x = x_start; x !== x_end; x += x_step, i++) {
  23576. color = image[i];
  23577. imageData[(x + width * y) * 4 + 3] = 255;
  23578. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  23579. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  23580. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  23581. }
  23582. }
  23583. return imageData;
  23584. };
  23585. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  23586. var image = pixel_data;
  23587. var width = header.width, height = header.height;
  23588. var color, i = 0, x, y;
  23589. var imageData = new Uint8Array(width * height * 4);
  23590. for (y = y_start; y !== y_end; y += y_step) {
  23591. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  23592. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  23593. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  23594. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  23595. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  23596. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  23597. }
  23598. }
  23599. return imageData;
  23600. };
  23601. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  23602. var image = pixel_data;
  23603. var width = header.width, height = header.height;
  23604. var i = 0, x, y;
  23605. var imageData = new Uint8Array(width * height * 4);
  23606. for (y = y_start; y !== y_end; y += y_step) {
  23607. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  23608. imageData[(x + width * y) * 4 + 3] = 255;
  23609. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  23610. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  23611. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  23612. }
  23613. }
  23614. return imageData;
  23615. };
  23616. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  23617. var image = pixel_data;
  23618. var width = header.width, height = header.height;
  23619. var i = 0, x, y;
  23620. var imageData = new Uint8Array(width * height * 4);
  23621. for (y = y_start; y !== y_end; y += y_step) {
  23622. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  23623. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  23624. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  23625. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  23626. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  23627. }
  23628. }
  23629. return imageData;
  23630. };
  23631. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  23632. var image = pixel_data;
  23633. var width = header.width, height = header.height;
  23634. var color, i = 0, x, y;
  23635. var imageData = new Uint8Array(width * height * 4);
  23636. for (y = y_start; y !== y_end; y += y_step) {
  23637. for (x = x_start; x !== x_end; x += x_step, i++) {
  23638. color = image[i];
  23639. imageData[(x + width * y) * 4 + 0] = color;
  23640. imageData[(x + width * y) * 4 + 1] = color;
  23641. imageData[(x + width * y) * 4 + 2] = color;
  23642. imageData[(x + width * y) * 4 + 3] = 255;
  23643. }
  23644. }
  23645. return imageData;
  23646. };
  23647. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  23648. var image = pixel_data;
  23649. var width = header.width, height = header.height;
  23650. var i = 0, x, y;
  23651. var imageData = new Uint8Array(width * height * 4);
  23652. for (y = y_start; y !== y_end; y += y_step) {
  23653. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  23654. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  23655. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  23656. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  23657. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  23658. }
  23659. }
  23660. return imageData;
  23661. };
  23662. TGATools._TYPE_NO_DATA = 0;
  23663. TGATools._TYPE_INDEXED = 1;
  23664. TGATools._TYPE_RGB = 2;
  23665. TGATools._TYPE_GREY = 3;
  23666. TGATools._TYPE_RLE_INDEXED = 9;
  23667. TGATools._TYPE_RLE_RGB = 10;
  23668. TGATools._TYPE_RLE_GREY = 11;
  23669. TGATools._ORIGIN_MASK = 0x30;
  23670. TGATools._ORIGIN_SHIFT = 0x04;
  23671. TGATools._ORIGIN_BL = 0x00;
  23672. TGATools._ORIGIN_BR = 0x01;
  23673. TGATools._ORIGIN_UL = 0x02;
  23674. TGATools._ORIGIN_UR = 0x03;
  23675. return TGATools;
  23676. })();
  23677. Internals.TGATools = TGATools;
  23678. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  23679. })(BABYLON || (BABYLON = {}));
  23680. //# sourceMappingURL=babylon.tools.tga.js.mapvar BABYLON;
  23681. (function (BABYLON) {
  23682. var Internals;
  23683. (function (Internals) {
  23684. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  23685. // All values and structures referenced from:
  23686. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  23687. var DDS_MAGIC = 0x20534444;
  23688. 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;
  23689. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  23690. 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;
  23691. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  23692. function FourCCToInt32(value) {
  23693. return value.charCodeAt(0) + (value.charCodeAt(1) << 8) + (value.charCodeAt(2) << 16) + (value.charCodeAt(3) << 24);
  23694. }
  23695. function Int32ToFourCC(value) {
  23696. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  23697. }
  23698. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  23699. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  23700. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  23701. var headerLengthInt = 31; // The header length in 32 bit ints
  23702. // Offsets into the header array
  23703. var off_magic = 0;
  23704. var off_size = 1;
  23705. var off_flags = 2;
  23706. var off_height = 3;
  23707. var off_width = 4;
  23708. var off_mipmapCount = 7;
  23709. var off_pfFlags = 20;
  23710. var off_pfFourCC = 21;
  23711. var off_RGBbpp = 22;
  23712. var off_RMask = 23;
  23713. var off_GMask = 24;
  23714. var off_BMask = 25;
  23715. var off_AMask = 26;
  23716. var off_caps1 = 27;
  23717. var off_caps2 = 28;
  23718. ;
  23719. var DDSTools = (function () {
  23720. function DDSTools() {
  23721. }
  23722. DDSTools.GetDDSInfo = function (arrayBuffer) {
  23723. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  23724. var mipmapCount = 1;
  23725. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  23726. mipmapCount = Math.max(1, header[off_mipmapCount]);
  23727. }
  23728. return {
  23729. width: header[off_width],
  23730. height: header[off_height],
  23731. mipmapCount: mipmapCount,
  23732. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  23733. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  23734. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  23735. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  23736. };
  23737. };
  23738. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  23739. var byteArray = new Uint8Array(dataLength);
  23740. var srcData = new Uint8Array(arrayBuffer);
  23741. var index = 0;
  23742. for (var y = height - 1; y >= 0; y--) {
  23743. for (var x = 0; x < width; x++) {
  23744. var srcPos = dataOffset + (x + y * width) * 4;
  23745. byteArray[index + 2] = srcData[srcPos];
  23746. byteArray[index + 1] = srcData[srcPos + 1];
  23747. byteArray[index] = srcData[srcPos + 2];
  23748. byteArray[index + 3] = srcData[srcPos + 3];
  23749. index += 4;
  23750. }
  23751. }
  23752. return byteArray;
  23753. };
  23754. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  23755. var byteArray = new Uint8Array(dataLength);
  23756. var srcData = new Uint8Array(arrayBuffer);
  23757. var index = 0;
  23758. for (var y = height - 1; y >= 0; y--) {
  23759. for (var x = 0; x < width; x++) {
  23760. var srcPos = dataOffset + (x + y * width) * 3;
  23761. byteArray[index + 2] = srcData[srcPos];
  23762. byteArray[index + 1] = srcData[srcPos + 1];
  23763. byteArray[index] = srcData[srcPos + 2];
  23764. index += 3;
  23765. }
  23766. }
  23767. return byteArray;
  23768. };
  23769. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  23770. var byteArray = new Uint8Array(dataLength);
  23771. var srcData = new Uint8Array(arrayBuffer);
  23772. var index = 0;
  23773. for (var y = height - 1; y >= 0; y--) {
  23774. for (var x = 0; x < width; x++) {
  23775. var srcPos = dataOffset + (x + y * width);
  23776. byteArray[index] = srcData[srcPos];
  23777. index++;
  23778. }
  23779. }
  23780. return byteArray;
  23781. };
  23782. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  23783. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  23784. if (header[off_magic] != DDS_MAGIC) {
  23785. BABYLON.Tools.Error("Invalid magic number in DDS header");
  23786. return;
  23787. }
  23788. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  23789. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  23790. return;
  23791. }
  23792. if (info.isFourCC) {
  23793. fourCC = header[off_pfFourCC];
  23794. switch (fourCC) {
  23795. case FOURCC_DXT1:
  23796. blockBytes = 8;
  23797. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  23798. break;
  23799. case FOURCC_DXT3:
  23800. blockBytes = 16;
  23801. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  23802. break;
  23803. case FOURCC_DXT5:
  23804. blockBytes = 16;
  23805. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  23806. break;
  23807. default:
  23808. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  23809. return;
  23810. }
  23811. }
  23812. mipmapCount = 1;
  23813. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  23814. mipmapCount = Math.max(1, header[off_mipmapCount]);
  23815. }
  23816. var bpp = header[off_RGBbpp];
  23817. for (var face = 0; face < faces; face++) {
  23818. var sampler = faces == 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  23819. width = header[off_width];
  23820. height = header[off_height];
  23821. dataOffset = header[off_size] + 4;
  23822. for (i = 0; i < mipmapCount; ++i) {
  23823. if (info.isRGB) {
  23824. if (bpp == 24) {
  23825. dataLength = width * height * 3;
  23826. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  23827. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  23828. }
  23829. else {
  23830. dataLength = width * height * 4;
  23831. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  23832. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  23833. }
  23834. }
  23835. else if (info.isLuminance) {
  23836. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  23837. var unpaddedRowSize = width;
  23838. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  23839. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  23840. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  23841. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  23842. }
  23843. else {
  23844. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  23845. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  23846. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  23847. }
  23848. dataOffset += dataLength;
  23849. width *= 0.5;
  23850. height *= 0.5;
  23851. width = Math.max(1.0, width);
  23852. height = Math.max(1.0, height);
  23853. }
  23854. }
  23855. };
  23856. return DDSTools;
  23857. })();
  23858. Internals.DDSTools = DDSTools;
  23859. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  23860. })(BABYLON || (BABYLON = {}));
  23861. //# sourceMappingURL=babylon.tools.dds.js.mapvar BABYLON;
  23862. (function (BABYLON) {
  23863. var SmartArray = (function () {
  23864. function SmartArray(capacity) {
  23865. this.length = 0;
  23866. this._duplicateId = 0;
  23867. this.data = new Array(capacity);
  23868. this._id = SmartArray._GlobalId++;
  23869. }
  23870. SmartArray.prototype.push = function (value) {
  23871. this.data[this.length++] = value;
  23872. if (this.length > this.data.length) {
  23873. this.data.length *= 2;
  23874. }
  23875. if (!value.__smartArrayFlags) {
  23876. value.__smartArrayFlags = {};
  23877. }
  23878. value.__smartArrayFlags[this._id] = this._duplicateId;
  23879. };
  23880. SmartArray.prototype.pushNoDuplicate = function (value) {
  23881. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  23882. return;
  23883. }
  23884. this.push(value);
  23885. };
  23886. SmartArray.prototype.sort = function (compareFn) {
  23887. this.data.sort(compareFn);
  23888. };
  23889. SmartArray.prototype.reset = function () {
  23890. this.length = 0;
  23891. this._duplicateId++;
  23892. };
  23893. SmartArray.prototype.concat = function (array) {
  23894. if (array.length === 0) {
  23895. return;
  23896. }
  23897. if (this.length + array.length > this.data.length) {
  23898. this.data.length = (this.length + array.length) * 2;
  23899. }
  23900. for (var index = 0; index < array.length; index++) {
  23901. this.data[this.length++] = (array.data || array)[index];
  23902. }
  23903. };
  23904. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  23905. if (array.length === 0) {
  23906. return;
  23907. }
  23908. if (this.length + array.length > this.data.length) {
  23909. this.data.length = (this.length + array.length) * 2;
  23910. }
  23911. for (var index = 0; index < array.length; index++) {
  23912. var item = (array.data || array)[index];
  23913. this.pushNoDuplicate(item);
  23914. }
  23915. };
  23916. SmartArray.prototype.indexOf = function (value) {
  23917. var position = this.data.indexOf(value);
  23918. if (position >= this.length) {
  23919. return -1;
  23920. }
  23921. return position;
  23922. };
  23923. // Statics
  23924. SmartArray._GlobalId = 0;
  23925. return SmartArray;
  23926. })();
  23927. BABYLON.SmartArray = SmartArray;
  23928. })(BABYLON || (BABYLON = {}));
  23929. //# sourceMappingURL=babylon.smartArray.js.mapvar BABYLON;
  23930. (function (BABYLON) {
  23931. var CannonJSPlugin = (function () {
  23932. function CannonJSPlugin() {
  23933. this._registeredMeshes = [];
  23934. this._physicsMaterials = [];
  23935. this.updateBodyPosition = function (mesh) {
  23936. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23937. var registeredMesh = this._registeredMeshes[index];
  23938. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  23939. var body = registeredMesh.body;
  23940. var center = mesh.getBoundingInfo().boundingBox.center;
  23941. body.position.set(center.x, center.z, center.y);
  23942. body.quaternion.x = mesh.rotationQuaternion.x;
  23943. body.quaternion.z = mesh.rotationQuaternion.y;
  23944. body.quaternion.y = mesh.rotationQuaternion.z;
  23945. body.quaternion.w = -mesh.rotationQuaternion.w;
  23946. return;
  23947. }
  23948. }
  23949. };
  23950. }
  23951. CannonJSPlugin.prototype.initialize = function (iterations) {
  23952. if (iterations === void 0) { iterations = 10; }
  23953. this._world = new CANNON.World();
  23954. this._world.broadphase = new CANNON.NaiveBroadphase();
  23955. this._world.solver.iterations = iterations;
  23956. };
  23957. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  23958. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  23959. };
  23960. CannonJSPlugin.prototype.runOneStep = function (delta) {
  23961. this._world.step(delta);
  23962. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23963. var registeredMesh = this._registeredMeshes[index];
  23964. if (registeredMesh.isChild) {
  23965. continue;
  23966. }
  23967. // Body position
  23968. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  23969. var deltaPos = registeredMesh.delta;
  23970. if (deltaPos) {
  23971. registeredMesh.mesh.position.x = bodyX + deltaPos.x;
  23972. registeredMesh.mesh.position.y = bodyZ + deltaPos.y;
  23973. registeredMesh.mesh.position.z = bodyY + deltaPos.z;
  23974. }
  23975. else {
  23976. registeredMesh.mesh.position.x = bodyX;
  23977. registeredMesh.mesh.position.y = bodyZ;
  23978. registeredMesh.mesh.position.z = bodyY;
  23979. }
  23980. if (!registeredMesh.mesh.rotationQuaternion) {
  23981. registeredMesh.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  23982. }
  23983. registeredMesh.mesh.rotationQuaternion.x = registeredMesh.body.quaternion.x;
  23984. registeredMesh.mesh.rotationQuaternion.y = registeredMesh.body.quaternion.z;
  23985. registeredMesh.mesh.rotationQuaternion.z = registeredMesh.body.quaternion.y;
  23986. registeredMesh.mesh.rotationQuaternion.w = -registeredMesh.body.quaternion.w;
  23987. }
  23988. };
  23989. CannonJSPlugin.prototype.setGravity = function (gravity) {
  23990. this._world.gravity.set(gravity.x, gravity.z, gravity.y);
  23991. };
  23992. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  23993. this.unregisterMesh(mesh);
  23994. mesh.computeWorldMatrix(true);
  23995. switch (impostor) {
  23996. case BABYLON.PhysicsEngine.SphereImpostor:
  23997. var bbox = mesh.getBoundingInfo().boundingBox;
  23998. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  23999. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  24000. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  24001. return this._createSphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2, mesh, options);
  24002. case BABYLON.PhysicsEngine.BoxImpostor:
  24003. bbox = mesh.getBoundingInfo().boundingBox;
  24004. var min = bbox.minimumWorld;
  24005. var max = bbox.maximumWorld;
  24006. var box = max.subtract(min).scale(0.5);
  24007. return this._createBox(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z), mesh, options);
  24008. case BABYLON.PhysicsEngine.PlaneImpostor:
  24009. return this._createPlane(mesh, options);
  24010. case BABYLON.PhysicsEngine.MeshImpostor:
  24011. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24012. var rawFaces = mesh.getIndices();
  24013. return this._createConvexPolyhedron(rawVerts, rawFaces, mesh, options);
  24014. }
  24015. return null;
  24016. };
  24017. CannonJSPlugin.prototype._createSphere = function (radius, mesh, options) {
  24018. var shape = new CANNON.Sphere(radius);
  24019. if (!options) {
  24020. return shape;
  24021. }
  24022. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  24023. };
  24024. CannonJSPlugin.prototype._createBox = function (x, y, z, mesh, options) {
  24025. var shape = new CANNON.Box(new CANNON.Vec3(x, z, y));
  24026. if (!options) {
  24027. return shape;
  24028. }
  24029. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  24030. };
  24031. CannonJSPlugin.prototype._createPlane = function (mesh, options) {
  24032. var shape = new CANNON.Plane();
  24033. if (!options) {
  24034. return shape;
  24035. }
  24036. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  24037. };
  24038. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh, options) {
  24039. var verts = [], faces = [];
  24040. mesh.computeWorldMatrix(true);
  24041. for (var i = 0; i < rawVerts.length; i += 3) {
  24042. var transformed = BABYLON.Vector3.Zero();
  24043. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  24044. verts.push(new CANNON.Vec3(transformed.x, transformed.z, transformed.y));
  24045. }
  24046. for (var j = 0; j < rawFaces.length; j += 3) {
  24047. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  24048. }
  24049. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  24050. if (!options) {
  24051. return shape;
  24052. }
  24053. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  24054. };
  24055. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  24056. var index;
  24057. var mat;
  24058. for (index = 0; index < this._physicsMaterials.length; index++) {
  24059. mat = this._physicsMaterials[index];
  24060. if (mat.friction === friction && mat.restitution === restitution) {
  24061. return mat;
  24062. }
  24063. }
  24064. var currentMat = new CANNON.Material();
  24065. currentMat.friction = friction;
  24066. currentMat.restitution = restitution;
  24067. this._physicsMaterials.push(currentMat);
  24068. for (index = 0; index < this._physicsMaterials.length; index++) {
  24069. mat = this._physicsMaterials[index];
  24070. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, mat.friction * currentMat.friction, mat.restitution * currentMat.restitution);
  24071. contactMaterial.contactEquationStiffness = 1e10;
  24072. contactMaterial.contactEquationRegularizationTime = 10;
  24073. this._world.addContactMaterial(contactMaterial);
  24074. }
  24075. return currentMat;
  24076. };
  24077. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, mass, friction, restitution) {
  24078. var initialRotation = null;
  24079. if (mesh.rotationQuaternion) {
  24080. initialRotation = mesh.rotationQuaternion.clone();
  24081. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  24082. }
  24083. // The delta between the mesh position and the mesh bounding box center
  24084. var bbox = mesh.getBoundingInfo().boundingBox;
  24085. var deltaPosition = mesh.position.subtract(bbox.center);
  24086. var material = this._addMaterial(friction, restitution);
  24087. var body = new CANNON.RigidBody(mass, shape, material);
  24088. if (initialRotation) {
  24089. body.quaternion.x = initialRotation.x;
  24090. body.quaternion.z = initialRotation.y;
  24091. body.quaternion.y = initialRotation.z;
  24092. body.quaternion.w = -initialRotation.w;
  24093. }
  24094. body.position.set(bbox.center.x, bbox.center.z, bbox.center.y);
  24095. this._world.add(body);
  24096. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition });
  24097. return body;
  24098. };
  24099. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  24100. var compoundShape = new CANNON.Compound();
  24101. for (var index = 0; index < parts.length; index++) {
  24102. var mesh = parts[index].mesh;
  24103. var shape = this.registerMesh(mesh, parts[index].impostor);
  24104. if (index == 0) {
  24105. compoundShape.addChild(shape, new CANNON.Vec3(0, 0, 0));
  24106. }
  24107. else {
  24108. compoundShape.addChild(shape, new CANNON.Vec3(mesh.position.x, mesh.position.z, mesh.position.y));
  24109. }
  24110. }
  24111. var initialMesh = parts[0].mesh;
  24112. var body = this._createRigidBodyFromShape(compoundShape, initialMesh, options.mass, options.friction, options.restitution);
  24113. body.parts = parts;
  24114. return body;
  24115. };
  24116. CannonJSPlugin.prototype._unbindBody = function (body) {
  24117. for (var index = 0; index < this._registeredMeshes.length; index++) {
  24118. var registeredMesh = this._registeredMeshes[index];
  24119. if (registeredMesh.body === body) {
  24120. registeredMesh.body = null;
  24121. registeredMesh.delta = 0;
  24122. }
  24123. }
  24124. };
  24125. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  24126. for (var index = 0; index < this._registeredMeshes.length; index++) {
  24127. var registeredMesh = this._registeredMeshes[index];
  24128. if (registeredMesh.mesh === mesh) {
  24129. // Remove body
  24130. if (registeredMesh.body) {
  24131. this._world.remove(registeredMesh.body);
  24132. this._unbindBody(registeredMesh.body);
  24133. }
  24134. this._registeredMeshes.splice(index, 1);
  24135. return;
  24136. }
  24137. }
  24138. };
  24139. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  24140. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.z, contactPoint.y);
  24141. var impulse = new CANNON.Vec3(force.x, force.z, force.y);
  24142. for (var index = 0; index < this._registeredMeshes.length; index++) {
  24143. var registeredMesh = this._registeredMeshes[index];
  24144. if (registeredMesh.mesh === mesh) {
  24145. registeredMesh.body.applyImpulse(impulse, worldPoint);
  24146. return;
  24147. }
  24148. }
  24149. };
  24150. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  24151. var body1 = null, body2 = null;
  24152. for (var index = 0; index < this._registeredMeshes.length; index++) {
  24153. var registeredMesh = this._registeredMeshes[index];
  24154. if (registeredMesh.mesh === mesh1) {
  24155. body1 = registeredMesh.body;
  24156. }
  24157. else if (registeredMesh.mesh === mesh2) {
  24158. body2 = registeredMesh.body;
  24159. }
  24160. }
  24161. if (!body1 || !body2) {
  24162. return false;
  24163. }
  24164. 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));
  24165. this._world.addConstraint(constraint);
  24166. return true;
  24167. };
  24168. CannonJSPlugin.prototype.dispose = function () {
  24169. while (this._registeredMeshes.length) {
  24170. this.unregisterMesh(this._registeredMeshes[0].mesh);
  24171. }
  24172. };
  24173. CannonJSPlugin.prototype.isSupported = function () {
  24174. return window.CANNON !== undefined;
  24175. };
  24176. return CannonJSPlugin;
  24177. })();
  24178. BABYLON.CannonJSPlugin = CannonJSPlugin;
  24179. })(BABYLON || (BABYLON = {}));
  24180. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  24181. var BABYLON;
  24182. (function (BABYLON) {
  24183. var Condition = (function () {
  24184. function Condition(actionManager) {
  24185. this._actionManager = actionManager;
  24186. }
  24187. Condition.prototype.isValid = function () {
  24188. return true;
  24189. };
  24190. Condition.prototype._getProperty = function (propertyPath) {
  24191. return this._actionManager._getProperty(propertyPath);
  24192. };
  24193. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  24194. return this._actionManager._getEffectiveTarget(target, propertyPath);
  24195. };
  24196. return Condition;
  24197. })();
  24198. BABYLON.Condition = Condition;
  24199. var ValueCondition = (function (_super) {
  24200. __extends(ValueCondition, _super);
  24201. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  24202. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  24203. _super.call(this, actionManager);
  24204. this.propertyPath = propertyPath;
  24205. this.value = value;
  24206. this.operator = operator;
  24207. this._target = this._getEffectiveTarget(target, this.propertyPath);
  24208. this._property = this._getProperty(this.propertyPath);
  24209. }
  24210. Object.defineProperty(ValueCondition, "IsEqual", {
  24211. get: function () {
  24212. return ValueCondition._IsEqual;
  24213. },
  24214. enumerable: true,
  24215. configurable: true
  24216. });
  24217. Object.defineProperty(ValueCondition, "IsDifferent", {
  24218. get: function () {
  24219. return ValueCondition._IsDifferent;
  24220. },
  24221. enumerable: true,
  24222. configurable: true
  24223. });
  24224. Object.defineProperty(ValueCondition, "IsGreater", {
  24225. get: function () {
  24226. return ValueCondition._IsGreater;
  24227. },
  24228. enumerable: true,
  24229. configurable: true
  24230. });
  24231. Object.defineProperty(ValueCondition, "IsLesser", {
  24232. get: function () {
  24233. return ValueCondition._IsLesser;
  24234. },
  24235. enumerable: true,
  24236. configurable: true
  24237. });
  24238. // Methods
  24239. ValueCondition.prototype.isValid = function () {
  24240. switch (this.operator) {
  24241. case ValueCondition.IsGreater:
  24242. return this._target[this._property] > this.value;
  24243. case ValueCondition.IsLesser:
  24244. return this._target[this._property] < this.value;
  24245. case ValueCondition.IsEqual:
  24246. case ValueCondition.IsDifferent:
  24247. var check;
  24248. if (this.value.equals) {
  24249. check = this.value.equals(this._target[this._property]);
  24250. }
  24251. else {
  24252. check = this.value === this._target[this._property];
  24253. }
  24254. return this.operator === ValueCondition.IsEqual ? check : !check;
  24255. }
  24256. return false;
  24257. };
  24258. // Statics
  24259. ValueCondition._IsEqual = 0;
  24260. ValueCondition._IsDifferent = 1;
  24261. ValueCondition._IsGreater = 2;
  24262. ValueCondition._IsLesser = 3;
  24263. return ValueCondition;
  24264. })(Condition);
  24265. BABYLON.ValueCondition = ValueCondition;
  24266. var PredicateCondition = (function (_super) {
  24267. __extends(PredicateCondition, _super);
  24268. function PredicateCondition(actionManager, predicate) {
  24269. _super.call(this, actionManager);
  24270. this.predicate = predicate;
  24271. }
  24272. PredicateCondition.prototype.isValid = function () {
  24273. return this.predicate();
  24274. };
  24275. return PredicateCondition;
  24276. })(Condition);
  24277. BABYLON.PredicateCondition = PredicateCondition;
  24278. var StateCondition = (function (_super) {
  24279. __extends(StateCondition, _super);
  24280. function StateCondition(actionManager, target, value) {
  24281. _super.call(this, actionManager);
  24282. this.value = value;
  24283. this._target = target;
  24284. }
  24285. // Methods
  24286. StateCondition.prototype.isValid = function () {
  24287. return this._target.state === this.value;
  24288. };
  24289. return StateCondition;
  24290. })(Condition);
  24291. BABYLON.StateCondition = StateCondition;
  24292. })(BABYLON || (BABYLON = {}));
  24293. //# sourceMappingURL=babylon.condition.js.mapvar BABYLON;
  24294. (function (BABYLON) {
  24295. var Action = (function () {
  24296. function Action(triggerOptions, condition) {
  24297. this.triggerOptions = triggerOptions;
  24298. if (triggerOptions.parameter) {
  24299. this.trigger = triggerOptions.trigger;
  24300. this._triggerParameter = triggerOptions.parameter;
  24301. }
  24302. else {
  24303. this.trigger = triggerOptions;
  24304. }
  24305. this._nextActiveAction = this;
  24306. this._condition = condition;
  24307. }
  24308. // Methods
  24309. Action.prototype._prepare = function () {
  24310. };
  24311. Action.prototype.getTriggerParameter = function () {
  24312. return this._triggerParameter;
  24313. };
  24314. Action.prototype._executeCurrent = function (evt) {
  24315. if (this._nextActiveAction._condition) {
  24316. var condition = this._nextActiveAction._condition;
  24317. var currentRenderId = this._actionManager.getScene().getRenderId();
  24318. // We cache the current evaluation for the current frame
  24319. if (condition._evaluationId === currentRenderId) {
  24320. if (!condition._currentResult) {
  24321. return;
  24322. }
  24323. }
  24324. else {
  24325. condition._evaluationId = currentRenderId;
  24326. if (!condition.isValid()) {
  24327. condition._currentResult = false;
  24328. return;
  24329. }
  24330. condition._currentResult = true;
  24331. }
  24332. }
  24333. this._nextActiveAction.execute(evt);
  24334. if (this._nextActiveAction._child) {
  24335. if (!this._nextActiveAction._child._actionManager) {
  24336. this._nextActiveAction._child._actionManager = this._actionManager;
  24337. }
  24338. this._nextActiveAction = this._nextActiveAction._child;
  24339. }
  24340. else {
  24341. this._nextActiveAction = this;
  24342. }
  24343. };
  24344. Action.prototype.execute = function (evt) {
  24345. };
  24346. Action.prototype.then = function (action) {
  24347. this._child = action;
  24348. action._actionManager = this._actionManager;
  24349. action._prepare();
  24350. return action;
  24351. };
  24352. Action.prototype._getProperty = function (propertyPath) {
  24353. return this._actionManager._getProperty(propertyPath);
  24354. };
  24355. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  24356. return this._actionManager._getEffectiveTarget(target, propertyPath);
  24357. };
  24358. return Action;
  24359. })();
  24360. BABYLON.Action = Action;
  24361. })(BABYLON || (BABYLON = {}));
  24362. //# sourceMappingURL=babylon.action.js.mapvar BABYLON;
  24363. (function (BABYLON) {
  24364. /**
  24365. * ActionEvent is the event beint sent when an action is triggered.
  24366. */
  24367. var ActionEvent = (function () {
  24368. /**
  24369. * @constructor
  24370. * @param source The mesh that triggered the action.
  24371. * @param pointerX the X mouse cursor position at the time of the event
  24372. * @param pointerY the Y mouse cursor position at the time of the event
  24373. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  24374. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  24375. */
  24376. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent) {
  24377. this.source = source;
  24378. this.pointerX = pointerX;
  24379. this.pointerY = pointerY;
  24380. this.meshUnderPointer = meshUnderPointer;
  24381. this.sourceEvent = sourceEvent;
  24382. }
  24383. /**
  24384. * Helper function to auto-create an ActionEvent from a source mesh.
  24385. * @param source the source mesh that triggered the event
  24386. * @param evt {Event} The original (browser) event
  24387. */
  24388. ActionEvent.CreateNew = function (source, evt) {
  24389. var scene = source.getScene();
  24390. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  24391. };
  24392. /**
  24393. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  24394. * @param scene the scene where the event occurred
  24395. * @param evt {Event} The original (browser) event
  24396. */
  24397. ActionEvent.CreateNewFromScene = function (scene, evt) {
  24398. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  24399. };
  24400. return ActionEvent;
  24401. })();
  24402. BABYLON.ActionEvent = ActionEvent;
  24403. /**
  24404. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  24405. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  24406. */
  24407. var ActionManager = (function () {
  24408. function ActionManager(scene) {
  24409. // Members
  24410. this.actions = new Array();
  24411. this._scene = scene;
  24412. scene._actionManagers.push(this);
  24413. }
  24414. Object.defineProperty(ActionManager, "NothingTrigger", {
  24415. get: function () {
  24416. return ActionManager._NothingTrigger;
  24417. },
  24418. enumerable: true,
  24419. configurable: true
  24420. });
  24421. Object.defineProperty(ActionManager, "OnPickTrigger", {
  24422. get: function () {
  24423. return ActionManager._OnPickTrigger;
  24424. },
  24425. enumerable: true,
  24426. configurable: true
  24427. });
  24428. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  24429. get: function () {
  24430. return ActionManager._OnLeftPickTrigger;
  24431. },
  24432. enumerable: true,
  24433. configurable: true
  24434. });
  24435. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  24436. get: function () {
  24437. return ActionManager._OnRightPickTrigger;
  24438. },
  24439. enumerable: true,
  24440. configurable: true
  24441. });
  24442. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  24443. get: function () {
  24444. return ActionManager._OnCenterPickTrigger;
  24445. },
  24446. enumerable: true,
  24447. configurable: true
  24448. });
  24449. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  24450. get: function () {
  24451. return ActionManager._OnPointerOverTrigger;
  24452. },
  24453. enumerable: true,
  24454. configurable: true
  24455. });
  24456. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  24457. get: function () {
  24458. return ActionManager._OnPointerOutTrigger;
  24459. },
  24460. enumerable: true,
  24461. configurable: true
  24462. });
  24463. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  24464. get: function () {
  24465. return ActionManager._OnEveryFrameTrigger;
  24466. },
  24467. enumerable: true,
  24468. configurable: true
  24469. });
  24470. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  24471. get: function () {
  24472. return ActionManager._OnIntersectionEnterTrigger;
  24473. },
  24474. enumerable: true,
  24475. configurable: true
  24476. });
  24477. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  24478. get: function () {
  24479. return ActionManager._OnIntersectionExitTrigger;
  24480. },
  24481. enumerable: true,
  24482. configurable: true
  24483. });
  24484. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  24485. get: function () {
  24486. return ActionManager._OnKeyDownTrigger;
  24487. },
  24488. enumerable: true,
  24489. configurable: true
  24490. });
  24491. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  24492. get: function () {
  24493. return ActionManager._OnKeyUpTrigger;
  24494. },
  24495. enumerable: true,
  24496. configurable: true
  24497. });
  24498. // Methods
  24499. ActionManager.prototype.dispose = function () {
  24500. var index = this._scene._actionManagers.indexOf(this);
  24501. if (index > -1) {
  24502. this._scene._actionManagers.splice(index, 1);
  24503. }
  24504. };
  24505. ActionManager.prototype.getScene = function () {
  24506. return this._scene;
  24507. };
  24508. /**
  24509. * Does this action manager handles actions of any of the given triggers
  24510. * @param {number[]} triggers - the triggers to be tested
  24511. * @return {boolean} whether one (or more) of the triggers is handeled
  24512. */
  24513. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  24514. for (var index = 0; index < this.actions.length; index++) {
  24515. var action = this.actions[index];
  24516. if (triggers.indexOf(action.trigger) > -1) {
  24517. return true;
  24518. }
  24519. }
  24520. return false;
  24521. };
  24522. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  24523. /**
  24524. * Does this action manager has pointer triggers
  24525. * @return {boolean} whether or not it has pointer triggers
  24526. */
  24527. get: function () {
  24528. for (var index = 0; index < this.actions.length; index++) {
  24529. var action = this.actions[index];
  24530. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  24531. return true;
  24532. }
  24533. }
  24534. return false;
  24535. },
  24536. enumerable: true,
  24537. configurable: true
  24538. });
  24539. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  24540. /**
  24541. * Does this action manager has pick triggers
  24542. * @return {boolean} whether or not it has pick triggers
  24543. */
  24544. get: function () {
  24545. for (var index = 0; index < this.actions.length; index++) {
  24546. var action = this.actions[index];
  24547. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  24548. return true;
  24549. }
  24550. }
  24551. return false;
  24552. },
  24553. enumerable: true,
  24554. configurable: true
  24555. });
  24556. /**
  24557. * Registers an action to this action manager
  24558. * @param {BABYLON.Action} action - the action to be registered
  24559. * @return {BABYLON.Action} the action amended (prepared) after registration
  24560. */
  24561. ActionManager.prototype.registerAction = function (action) {
  24562. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  24563. if (this.getScene().actionManager !== this) {
  24564. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  24565. return null;
  24566. }
  24567. }
  24568. this.actions.push(action);
  24569. action._actionManager = this;
  24570. action._prepare();
  24571. return action;
  24572. };
  24573. /**
  24574. * Process a specific trigger
  24575. * @param {number} trigger - the trigger to process
  24576. * @param evt {BABYLON.ActionEvent} the event details to be processed
  24577. */
  24578. ActionManager.prototype.processTrigger = function (trigger, evt) {
  24579. for (var index = 0; index < this.actions.length; index++) {
  24580. var action = this.actions[index];
  24581. if (action.trigger === trigger) {
  24582. if (trigger === ActionManager.OnKeyUpTrigger || trigger === ActionManager.OnKeyDownTrigger) {
  24583. var parameter = action.getTriggerParameter();
  24584. if (parameter) {
  24585. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  24586. var actualkey = String.fromCharCode(unicode).toLowerCase();
  24587. if (actualkey !== parameter.toLowerCase()) {
  24588. continue;
  24589. }
  24590. }
  24591. }
  24592. action._executeCurrent(evt);
  24593. }
  24594. }
  24595. };
  24596. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  24597. var properties = propertyPath.split(".");
  24598. for (var index = 0; index < properties.length - 1; index++) {
  24599. target = target[properties[index]];
  24600. }
  24601. return target;
  24602. };
  24603. ActionManager.prototype._getProperty = function (propertyPath) {
  24604. var properties = propertyPath.split(".");
  24605. return properties[properties.length - 1];
  24606. };
  24607. // Statics
  24608. ActionManager._NothingTrigger = 0;
  24609. ActionManager._OnPickTrigger = 1;
  24610. ActionManager._OnLeftPickTrigger = 2;
  24611. ActionManager._OnRightPickTrigger = 3;
  24612. ActionManager._OnCenterPickTrigger = 4;
  24613. ActionManager._OnPointerOverTrigger = 5;
  24614. ActionManager._OnPointerOutTrigger = 6;
  24615. ActionManager._OnEveryFrameTrigger = 7;
  24616. ActionManager._OnIntersectionEnterTrigger = 8;
  24617. ActionManager._OnIntersectionExitTrigger = 9;
  24618. ActionManager._OnKeyDownTrigger = 10;
  24619. ActionManager._OnKeyUpTrigger = 11;
  24620. return ActionManager;
  24621. })();
  24622. BABYLON.ActionManager = ActionManager;
  24623. })(BABYLON || (BABYLON = {}));
  24624. //# sourceMappingURL=babylon.actionManager.js.map
  24625. var BABYLON;
  24626. (function (BABYLON) {
  24627. var InterpolateValueAction = (function (_super) {
  24628. __extends(InterpolateValueAction, _super);
  24629. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations) {
  24630. if (duration === void 0) { duration = 1000; }
  24631. _super.call(this, triggerOptions, condition);
  24632. this.propertyPath = propertyPath;
  24633. this.value = value;
  24634. this.duration = duration;
  24635. this.stopOtherAnimations = stopOtherAnimations;
  24636. this._target = target;
  24637. }
  24638. InterpolateValueAction.prototype._prepare = function () {
  24639. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  24640. this._property = this._getProperty(this.propertyPath);
  24641. };
  24642. InterpolateValueAction.prototype.execute = function () {
  24643. var scene = this._actionManager.getScene();
  24644. var keys = [
  24645. {
  24646. frame: 0,
  24647. value: this._target[this._property]
  24648. },
  24649. {
  24650. frame: 100,
  24651. value: this.value
  24652. }
  24653. ];
  24654. var dataType;
  24655. if (typeof this.value === "number") {
  24656. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  24657. }
  24658. else if (this.value instanceof BABYLON.Color3) {
  24659. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  24660. }
  24661. else if (this.value instanceof BABYLON.Vector3) {
  24662. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  24663. }
  24664. else if (this.value instanceof BABYLON.Matrix) {
  24665. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  24666. }
  24667. else if (this.value instanceof BABYLON.Quaternion) {
  24668. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  24669. }
  24670. else {
  24671. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  24672. return;
  24673. }
  24674. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  24675. animation.setKeys(keys);
  24676. if (this.stopOtherAnimations) {
  24677. scene.stopAnimation(this._target);
  24678. }
  24679. scene.beginDirectAnimation(this._target, [animation], 0, 100);
  24680. };
  24681. return InterpolateValueAction;
  24682. })(BABYLON.Action);
  24683. BABYLON.InterpolateValueAction = InterpolateValueAction;
  24684. })(BABYLON || (BABYLON = {}));
  24685. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  24686. var BABYLON;
  24687. (function (BABYLON) {
  24688. var SwitchBooleanAction = (function (_super) {
  24689. __extends(SwitchBooleanAction, _super);
  24690. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  24691. _super.call(this, triggerOptions, condition);
  24692. this.propertyPath = propertyPath;
  24693. this._target = target;
  24694. }
  24695. SwitchBooleanAction.prototype._prepare = function () {
  24696. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  24697. this._property = this._getProperty(this.propertyPath);
  24698. };
  24699. SwitchBooleanAction.prototype.execute = function () {
  24700. this._target[this._property] = !this._target[this._property];
  24701. };
  24702. return SwitchBooleanAction;
  24703. })(BABYLON.Action);
  24704. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  24705. var SetStateAction = (function (_super) {
  24706. __extends(SetStateAction, _super);
  24707. function SetStateAction(triggerOptions, target, value, condition) {
  24708. _super.call(this, triggerOptions, condition);
  24709. this.value = value;
  24710. this._target = target;
  24711. }
  24712. SetStateAction.prototype.execute = function () {
  24713. this._target.state = this.value;
  24714. };
  24715. return SetStateAction;
  24716. })(BABYLON.Action);
  24717. BABYLON.SetStateAction = SetStateAction;
  24718. var SetValueAction = (function (_super) {
  24719. __extends(SetValueAction, _super);
  24720. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  24721. _super.call(this, triggerOptions, condition);
  24722. this.propertyPath = propertyPath;
  24723. this.value = value;
  24724. this._target = target;
  24725. }
  24726. SetValueAction.prototype._prepare = function () {
  24727. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  24728. this._property = this._getProperty(this.propertyPath);
  24729. };
  24730. SetValueAction.prototype.execute = function () {
  24731. this._target[this._property] = this.value;
  24732. };
  24733. return SetValueAction;
  24734. })(BABYLON.Action);
  24735. BABYLON.SetValueAction = SetValueAction;
  24736. var IncrementValueAction = (function (_super) {
  24737. __extends(IncrementValueAction, _super);
  24738. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  24739. _super.call(this, triggerOptions, condition);
  24740. this.propertyPath = propertyPath;
  24741. this.value = value;
  24742. this._target = target;
  24743. }
  24744. IncrementValueAction.prototype._prepare = function () {
  24745. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  24746. this._property = this._getProperty(this.propertyPath);
  24747. if (typeof this._target[this._property] !== "number") {
  24748. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  24749. }
  24750. };
  24751. IncrementValueAction.prototype.execute = function () {
  24752. this._target[this._property] += this.value;
  24753. };
  24754. return IncrementValueAction;
  24755. })(BABYLON.Action);
  24756. BABYLON.IncrementValueAction = IncrementValueAction;
  24757. var PlayAnimationAction = (function (_super) {
  24758. __extends(PlayAnimationAction, _super);
  24759. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  24760. _super.call(this, triggerOptions, condition);
  24761. this.from = from;
  24762. this.to = to;
  24763. this.loop = loop;
  24764. this._target = target;
  24765. }
  24766. PlayAnimationAction.prototype._prepare = function () {
  24767. };
  24768. PlayAnimationAction.prototype.execute = function () {
  24769. var scene = this._actionManager.getScene();
  24770. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  24771. };
  24772. return PlayAnimationAction;
  24773. })(BABYLON.Action);
  24774. BABYLON.PlayAnimationAction = PlayAnimationAction;
  24775. var StopAnimationAction = (function (_super) {
  24776. __extends(StopAnimationAction, _super);
  24777. function StopAnimationAction(triggerOptions, target, condition) {
  24778. _super.call(this, triggerOptions, condition);
  24779. this._target = target;
  24780. }
  24781. StopAnimationAction.prototype._prepare = function () {
  24782. };
  24783. StopAnimationAction.prototype.execute = function () {
  24784. var scene = this._actionManager.getScene();
  24785. scene.stopAnimation(this._target);
  24786. };
  24787. return StopAnimationAction;
  24788. })(BABYLON.Action);
  24789. BABYLON.StopAnimationAction = StopAnimationAction;
  24790. var DoNothingAction = (function (_super) {
  24791. __extends(DoNothingAction, _super);
  24792. function DoNothingAction(triggerOptions, condition) {
  24793. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  24794. _super.call(this, triggerOptions, condition);
  24795. }
  24796. DoNothingAction.prototype.execute = function () {
  24797. };
  24798. return DoNothingAction;
  24799. })(BABYLON.Action);
  24800. BABYLON.DoNothingAction = DoNothingAction;
  24801. var CombineAction = (function (_super) {
  24802. __extends(CombineAction, _super);
  24803. function CombineAction(triggerOptions, children, condition) {
  24804. _super.call(this, triggerOptions, condition);
  24805. this.children = children;
  24806. }
  24807. CombineAction.prototype._prepare = function () {
  24808. for (var index = 0; index < this.children.length; index++) {
  24809. this.children[index]._actionManager = this._actionManager;
  24810. this.children[index]._prepare();
  24811. }
  24812. };
  24813. CombineAction.prototype.execute = function (evt) {
  24814. for (var index = 0; index < this.children.length; index++) {
  24815. this.children[index].execute(evt);
  24816. }
  24817. };
  24818. return CombineAction;
  24819. })(BABYLON.Action);
  24820. BABYLON.CombineAction = CombineAction;
  24821. var ExecuteCodeAction = (function (_super) {
  24822. __extends(ExecuteCodeAction, _super);
  24823. function ExecuteCodeAction(triggerOptions, func, condition) {
  24824. _super.call(this, triggerOptions, condition);
  24825. this.func = func;
  24826. }
  24827. ExecuteCodeAction.prototype.execute = function (evt) {
  24828. this.func(evt);
  24829. };
  24830. return ExecuteCodeAction;
  24831. })(BABYLON.Action);
  24832. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  24833. var SetParentAction = (function (_super) {
  24834. __extends(SetParentAction, _super);
  24835. function SetParentAction(triggerOptions, target, parent, condition) {
  24836. _super.call(this, triggerOptions, condition);
  24837. this._target = target;
  24838. this._parent = parent;
  24839. }
  24840. SetParentAction.prototype._prepare = function () {
  24841. };
  24842. SetParentAction.prototype.execute = function () {
  24843. if (this._target.parent === this._parent) {
  24844. return;
  24845. }
  24846. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  24847. invertParentWorldMatrix.invert();
  24848. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  24849. this._target.parent = this._parent;
  24850. };
  24851. return SetParentAction;
  24852. })(BABYLON.Action);
  24853. BABYLON.SetParentAction = SetParentAction;
  24854. var PlaySoundAction = (function (_super) {
  24855. __extends(PlaySoundAction, _super);
  24856. function PlaySoundAction(triggerOptions, sound, condition) {
  24857. _super.call(this, triggerOptions, condition);
  24858. this._sound = sound;
  24859. }
  24860. PlaySoundAction.prototype._prepare = function () {
  24861. };
  24862. PlaySoundAction.prototype.execute = function () {
  24863. if (this._sound !== undefined)
  24864. this._sound.play();
  24865. };
  24866. return PlaySoundAction;
  24867. })(BABYLON.Action);
  24868. BABYLON.PlaySoundAction = PlaySoundAction;
  24869. var StopSoundAction = (function (_super) {
  24870. __extends(StopSoundAction, _super);
  24871. function StopSoundAction(triggerOptions, sound, condition) {
  24872. _super.call(this, triggerOptions, condition);
  24873. this._sound = sound;
  24874. }
  24875. StopSoundAction.prototype._prepare = function () {
  24876. };
  24877. StopSoundAction.prototype.execute = function () {
  24878. if (this._sound !== undefined)
  24879. this._sound.stop();
  24880. };
  24881. return StopSoundAction;
  24882. })(BABYLON.Action);
  24883. BABYLON.StopSoundAction = StopSoundAction;
  24884. })(BABYLON || (BABYLON = {}));
  24885. //# sourceMappingURL=babylon.directActions.js.map
  24886. var BABYLON;
  24887. (function (BABYLON) {
  24888. var Geometry = (function () {
  24889. function Geometry(id, scene, vertexData, updatable, mesh) {
  24890. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  24891. this._totalVertices = 0;
  24892. this._indices = [];
  24893. this._isDisposed = false;
  24894. this.id = id;
  24895. this._engine = scene.getEngine();
  24896. this._meshes = [];
  24897. this._scene = scene;
  24898. // vertexData
  24899. if (vertexData) {
  24900. this.setAllVerticesData(vertexData, updatable);
  24901. }
  24902. else {
  24903. this._totalVertices = 0;
  24904. this._indices = [];
  24905. }
  24906. // applyToMesh
  24907. if (mesh) {
  24908. this.applyToMesh(mesh);
  24909. mesh.computeWorldMatrix(true);
  24910. }
  24911. }
  24912. Geometry.prototype.getScene = function () {
  24913. return this._scene;
  24914. };
  24915. Geometry.prototype.getEngine = function () {
  24916. return this._engine;
  24917. };
  24918. Geometry.prototype.isReady = function () {
  24919. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  24920. };
  24921. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  24922. vertexData.applyToGeometry(this, updatable);
  24923. };
  24924. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  24925. this._vertexBuffers = this._vertexBuffers || {};
  24926. if (this._vertexBuffers[kind]) {
  24927. this._vertexBuffers[kind].dispose();
  24928. }
  24929. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  24930. if (kind === BABYLON.VertexBuffer.PositionKind) {
  24931. stride = this._vertexBuffers[kind].getStrideSize();
  24932. this._totalVertices = data.length / stride;
  24933. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  24934. var meshes = this._meshes;
  24935. var numOfMeshes = meshes.length;
  24936. for (var index = 0; index < numOfMeshes; index++) {
  24937. var mesh = meshes[index];
  24938. mesh._resetPointsArrayCache();
  24939. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  24940. mesh._createGlobalSubMesh();
  24941. mesh.computeWorldMatrix(true);
  24942. }
  24943. }
  24944. };
  24945. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  24946. var vertexBuffer = this.getVertexBuffer(kind);
  24947. if (!vertexBuffer) {
  24948. return;
  24949. }
  24950. vertexBuffer.updateDirectly(data, offset);
  24951. };
  24952. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  24953. var vertexBuffer = this.getVertexBuffer(kind);
  24954. if (!vertexBuffer) {
  24955. return;
  24956. }
  24957. vertexBuffer.update(data);
  24958. if (kind === BABYLON.VertexBuffer.PositionKind) {
  24959. var extend;
  24960. var stride = vertexBuffer.getStrideSize();
  24961. this._totalVertices = data.length / stride;
  24962. if (updateExtends) {
  24963. extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  24964. }
  24965. var meshes = this._meshes;
  24966. var numOfMeshes = meshes.length;
  24967. for (var index = 0; index < numOfMeshes; index++) {
  24968. var mesh = meshes[index];
  24969. mesh._resetPointsArrayCache();
  24970. if (updateExtends) {
  24971. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  24972. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  24973. var subMesh = mesh.subMeshes[subIndex];
  24974. subMesh.refreshBoundingInfo();
  24975. }
  24976. }
  24977. }
  24978. }
  24979. };
  24980. Geometry.prototype.getTotalVertices = function () {
  24981. if (!this.isReady()) {
  24982. return 0;
  24983. }
  24984. return this._totalVertices;
  24985. };
  24986. Geometry.prototype.getVerticesData = function (kind) {
  24987. var vertexBuffer = this.getVertexBuffer(kind);
  24988. if (!vertexBuffer) {
  24989. return null;
  24990. }
  24991. return vertexBuffer.getData();
  24992. };
  24993. Geometry.prototype.getVertexBuffer = function (kind) {
  24994. if (!this.isReady()) {
  24995. return null;
  24996. }
  24997. return this._vertexBuffers[kind];
  24998. };
  24999. Geometry.prototype.getVertexBuffers = function () {
  25000. if (!this.isReady()) {
  25001. return null;
  25002. }
  25003. return this._vertexBuffers;
  25004. };
  25005. Geometry.prototype.isVerticesDataPresent = function (kind) {
  25006. if (!this._vertexBuffers) {
  25007. if (this._delayInfo) {
  25008. return this._delayInfo.indexOf(kind) !== -1;
  25009. }
  25010. return false;
  25011. }
  25012. return this._vertexBuffers[kind] !== undefined;
  25013. };
  25014. Geometry.prototype.getVerticesDataKinds = function () {
  25015. var result = [];
  25016. if (!this._vertexBuffers && this._delayInfo) {
  25017. for (var kind in this._delayInfo) {
  25018. result.push(kind);
  25019. }
  25020. }
  25021. else {
  25022. for (kind in this._vertexBuffers) {
  25023. result.push(kind);
  25024. }
  25025. }
  25026. return result;
  25027. };
  25028. Geometry.prototype.setIndices = function (indices, totalVertices) {
  25029. if (this._indexBuffer) {
  25030. this._engine._releaseBuffer(this._indexBuffer);
  25031. }
  25032. this._indices = indices;
  25033. if (this._meshes.length !== 0 && this._indices) {
  25034. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  25035. }
  25036. if (totalVertices !== undefined) {
  25037. this._totalVertices = totalVertices;
  25038. }
  25039. var meshes = this._meshes;
  25040. var numOfMeshes = meshes.length;
  25041. for (var index = 0; index < numOfMeshes; index++) {
  25042. meshes[index]._createGlobalSubMesh();
  25043. }
  25044. };
  25045. Geometry.prototype.getTotalIndices = function () {
  25046. if (!this.isReady()) {
  25047. return 0;
  25048. }
  25049. return this._indices.length;
  25050. };
  25051. Geometry.prototype.getIndices = function () {
  25052. if (!this.isReady()) {
  25053. return null;
  25054. }
  25055. return this._indices;
  25056. };
  25057. Geometry.prototype.getIndexBuffer = function () {
  25058. if (!this.isReady()) {
  25059. return null;
  25060. }
  25061. return this._indexBuffer;
  25062. };
  25063. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  25064. var meshes = this._meshes;
  25065. var index = meshes.indexOf(mesh);
  25066. if (index === -1) {
  25067. return;
  25068. }
  25069. for (var kind in this._vertexBuffers) {
  25070. this._vertexBuffers[kind].dispose();
  25071. }
  25072. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  25073. this._indexBuffer = null;
  25074. }
  25075. meshes.splice(index, 1);
  25076. mesh._geometry = null;
  25077. if (meshes.length === 0 && shouldDispose) {
  25078. this.dispose();
  25079. }
  25080. };
  25081. Geometry.prototype.applyToMesh = function (mesh) {
  25082. if (mesh._geometry === this) {
  25083. return;
  25084. }
  25085. var previousGeometry = mesh._geometry;
  25086. if (previousGeometry) {
  25087. previousGeometry.releaseForMesh(mesh);
  25088. }
  25089. var meshes = this._meshes;
  25090. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  25091. mesh._geometry = this;
  25092. this._scene.pushGeometry(this);
  25093. meshes.push(mesh);
  25094. if (this.isReady()) {
  25095. this._applyToMesh(mesh);
  25096. }
  25097. else {
  25098. mesh._boundingInfo = this._boundingInfo;
  25099. }
  25100. };
  25101. Geometry.prototype._applyToMesh = function (mesh) {
  25102. var numOfMeshes = this._meshes.length;
  25103. for (var kind in this._vertexBuffers) {
  25104. if (numOfMeshes === 1) {
  25105. this._vertexBuffers[kind].create();
  25106. }
  25107. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  25108. if (kind === BABYLON.VertexBuffer.PositionKind) {
  25109. mesh._resetPointsArrayCache();
  25110. var extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  25111. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  25112. mesh._createGlobalSubMesh();
  25113. //bounding info was just created again, world matrix should be applied again.
  25114. mesh._updateBoundingInfo();
  25115. }
  25116. }
  25117. // indexBuffer
  25118. if (numOfMeshes === 1 && this._indices) {
  25119. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  25120. }
  25121. if (this._indexBuffer) {
  25122. this._indexBuffer.references = numOfMeshes;
  25123. }
  25124. };
  25125. Geometry.prototype.load = function (scene, onLoaded) {
  25126. var _this = this;
  25127. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25128. return;
  25129. }
  25130. if (this.isReady()) {
  25131. if (onLoaded) {
  25132. onLoaded();
  25133. }
  25134. return;
  25135. }
  25136. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  25137. scene._addPendingData(this);
  25138. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  25139. _this._delayLoadingFunction(JSON.parse(data), _this);
  25140. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  25141. _this._delayInfo = [];
  25142. scene._removePendingData(_this);
  25143. var meshes = _this._meshes;
  25144. var numOfMeshes = meshes.length;
  25145. for (var index = 0; index < numOfMeshes; index++) {
  25146. _this._applyToMesh(meshes[index]);
  25147. }
  25148. if (onLoaded) {
  25149. onLoaded();
  25150. }
  25151. }, function () {
  25152. }, scene.database);
  25153. };
  25154. Geometry.prototype.isDisposed = function () {
  25155. return this._isDisposed;
  25156. };
  25157. Geometry.prototype.dispose = function () {
  25158. var meshes = this._meshes;
  25159. var numOfMeshes = meshes.length;
  25160. var index;
  25161. for (index = 0; index < numOfMeshes; index++) {
  25162. this.releaseForMesh(meshes[index]);
  25163. }
  25164. this._meshes = [];
  25165. for (var kind in this._vertexBuffers) {
  25166. this._vertexBuffers[kind].dispose();
  25167. }
  25168. this._vertexBuffers = [];
  25169. this._totalVertices = 0;
  25170. if (this._indexBuffer) {
  25171. this._engine._releaseBuffer(this._indexBuffer);
  25172. }
  25173. this._indexBuffer = null;
  25174. this._indices = [];
  25175. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  25176. this.delayLoadingFile = null;
  25177. this._delayLoadingFunction = null;
  25178. this._delayInfo = [];
  25179. this._boundingInfo = null; // todo: .dispose()
  25180. var geometries = this._scene.getGeometries();
  25181. index = geometries.indexOf(this);
  25182. if (index > -1) {
  25183. geometries.splice(index, 1);
  25184. }
  25185. this._isDisposed = true;
  25186. };
  25187. Geometry.prototype.copy = function (id) {
  25188. var vertexData = new BABYLON.VertexData();
  25189. vertexData.indices = [];
  25190. var indices = this.getIndices();
  25191. for (var index = 0; index < indices.length; index++) {
  25192. vertexData.indices.push(indices[index]);
  25193. }
  25194. var updatable = false;
  25195. var stopChecking = false;
  25196. for (var kind in this._vertexBuffers) {
  25197. // using slice() to make a copy of the array and not just reference it
  25198. vertexData.set(this.getVerticesData(kind).slice(0), kind);
  25199. if (!stopChecking) {
  25200. updatable = this.getVertexBuffer(kind).isUpdatable();
  25201. stopChecking = !updatable;
  25202. }
  25203. }
  25204. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  25205. geometry.delayLoadState = this.delayLoadState;
  25206. geometry.delayLoadingFile = this.delayLoadingFile;
  25207. geometry._delayLoadingFunction = this._delayLoadingFunction;
  25208. for (kind in this._delayInfo) {
  25209. geometry._delayInfo = geometry._delayInfo || [];
  25210. geometry._delayInfo.push(kind);
  25211. }
  25212. // Bounding info
  25213. var extend = BABYLON.Tools.ExtractMinAndMax(this.getVerticesData(BABYLON.VertexBuffer.PositionKind), 0, this.getTotalVertices());
  25214. geometry._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  25215. return geometry;
  25216. };
  25217. // Statics
  25218. Geometry.ExtractFromMesh = function (mesh, id) {
  25219. var geometry = mesh._geometry;
  25220. if (!geometry) {
  25221. return null;
  25222. }
  25223. return geometry.copy(id);
  25224. };
  25225. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  25226. // be aware Math.random() could cause collisions
  25227. Geometry.RandomId = function () {
  25228. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  25229. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  25230. return v.toString(16);
  25231. });
  25232. };
  25233. return Geometry;
  25234. })();
  25235. BABYLON.Geometry = Geometry;
  25236. /////// Primitives //////////////////////////////////////////////
  25237. var Geometry;
  25238. (function (Geometry) {
  25239. var Primitives;
  25240. (function (Primitives) {
  25241. /// Abstract class
  25242. var _Primitive = (function (_super) {
  25243. __extends(_Primitive, _super);
  25244. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  25245. this._beingRegenerated = true;
  25246. this._canBeRegenerated = canBeRegenerated;
  25247. _super.call(this, id, scene, vertexData, false, mesh); // updatable = false to be sure not to update vertices
  25248. this._beingRegenerated = false;
  25249. }
  25250. _Primitive.prototype.canBeRegenerated = function () {
  25251. return this._canBeRegenerated;
  25252. };
  25253. _Primitive.prototype.regenerate = function () {
  25254. if (!this._canBeRegenerated) {
  25255. return;
  25256. }
  25257. this._beingRegenerated = true;
  25258. this.setAllVerticesData(this._regenerateVertexData(), false);
  25259. this._beingRegenerated = false;
  25260. };
  25261. _Primitive.prototype.asNewGeometry = function (id) {
  25262. return _super.prototype.copy.call(this, id);
  25263. };
  25264. // overrides
  25265. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  25266. if (!this._beingRegenerated) {
  25267. return;
  25268. }
  25269. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  25270. };
  25271. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  25272. if (!this._beingRegenerated) {
  25273. return;
  25274. }
  25275. _super.prototype.setVerticesData.call(this, kind, data, false);
  25276. };
  25277. // to override
  25278. // protected
  25279. _Primitive.prototype._regenerateVertexData = function () {
  25280. throw new Error("Abstract method");
  25281. };
  25282. _Primitive.prototype.copy = function (id) {
  25283. throw new Error("Must be overriden in sub-classes.");
  25284. };
  25285. return _Primitive;
  25286. })(Geometry);
  25287. Primitives._Primitive = _Primitive;
  25288. var Ribbon = (function (_super) {
  25289. __extends(Ribbon, _super);
  25290. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  25291. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25292. this.pathArray = pathArray;
  25293. this.closeArray = closeArray;
  25294. this.closePath = closePath;
  25295. this.offset = offset;
  25296. this.side = side;
  25297. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25298. }
  25299. Ribbon.prototype._regenerateVertexData = function () {
  25300. return BABYLON.VertexData.CreateRibbon(this.pathArray, this.closeArray, this.closePath, this.offset, this.side);
  25301. };
  25302. Ribbon.prototype.copy = function (id) {
  25303. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  25304. };
  25305. return Ribbon;
  25306. })(_Primitive);
  25307. Primitives.Ribbon = Ribbon;
  25308. var Box = (function (_super) {
  25309. __extends(Box, _super);
  25310. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  25311. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25312. this.size = size;
  25313. this.side = side;
  25314. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25315. }
  25316. Box.prototype._regenerateVertexData = function () {
  25317. return BABYLON.VertexData.CreateBox(this.size, this.side);
  25318. };
  25319. Box.prototype.copy = function (id) {
  25320. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  25321. };
  25322. return Box;
  25323. })(_Primitive);
  25324. Primitives.Box = Box;
  25325. var Sphere = (function (_super) {
  25326. __extends(Sphere, _super);
  25327. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  25328. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25329. this.segments = segments;
  25330. this.diameter = diameter;
  25331. this.side = side;
  25332. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25333. }
  25334. Sphere.prototype._regenerateVertexData = function () {
  25335. return BABYLON.VertexData.CreateSphere(this.segments, this.diameter, this.side);
  25336. };
  25337. Sphere.prototype.copy = function (id) {
  25338. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  25339. };
  25340. return Sphere;
  25341. })(_Primitive);
  25342. Primitives.Sphere = Sphere;
  25343. var Cylinder = (function (_super) {
  25344. __extends(Cylinder, _super);
  25345. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  25346. if (subdivisions === void 0) { subdivisions = 1; }
  25347. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25348. this.height = height;
  25349. this.diameterTop = diameterTop;
  25350. this.diameterBottom = diameterBottom;
  25351. this.tessellation = tessellation;
  25352. this.subdivisions = subdivisions;
  25353. this.side = side;
  25354. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25355. }
  25356. Cylinder.prototype._regenerateVertexData = function () {
  25357. return BABYLON.VertexData.CreateCylinder(this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.side);
  25358. };
  25359. Cylinder.prototype.copy = function (id) {
  25360. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  25361. };
  25362. return Cylinder;
  25363. })(_Primitive);
  25364. Primitives.Cylinder = Cylinder;
  25365. var Torus = (function (_super) {
  25366. __extends(Torus, _super);
  25367. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  25368. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25369. this.diameter = diameter;
  25370. this.thickness = thickness;
  25371. this.tessellation = tessellation;
  25372. this.side = side;
  25373. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25374. }
  25375. Torus.prototype._regenerateVertexData = function () {
  25376. return BABYLON.VertexData.CreateTorus(this.diameter, this.thickness, this.tessellation, this.side);
  25377. };
  25378. Torus.prototype.copy = function (id) {
  25379. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  25380. };
  25381. return Torus;
  25382. })(_Primitive);
  25383. Primitives.Torus = Torus;
  25384. var Ground = (function (_super) {
  25385. __extends(Ground, _super);
  25386. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  25387. this.width = width;
  25388. this.height = height;
  25389. this.subdivisions = subdivisions;
  25390. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25391. }
  25392. Ground.prototype._regenerateVertexData = function () {
  25393. return BABYLON.VertexData.CreateGround(this.width, this.height, this.subdivisions);
  25394. };
  25395. Ground.prototype.copy = function (id) {
  25396. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  25397. };
  25398. return Ground;
  25399. })(_Primitive);
  25400. Primitives.Ground = Ground;
  25401. var TiledGround = (function (_super) {
  25402. __extends(TiledGround, _super);
  25403. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  25404. this.xmin = xmin;
  25405. this.zmin = zmin;
  25406. this.xmax = xmax;
  25407. this.zmax = zmax;
  25408. this.subdivisions = subdivisions;
  25409. this.precision = precision;
  25410. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25411. }
  25412. TiledGround.prototype._regenerateVertexData = function () {
  25413. return BABYLON.VertexData.CreateTiledGround(this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision);
  25414. };
  25415. TiledGround.prototype.copy = function (id) {
  25416. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  25417. };
  25418. return TiledGround;
  25419. })(_Primitive);
  25420. Primitives.TiledGround = TiledGround;
  25421. var Plane = (function (_super) {
  25422. __extends(Plane, _super);
  25423. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  25424. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25425. this.size = size;
  25426. this.side = side;
  25427. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25428. }
  25429. Plane.prototype._regenerateVertexData = function () {
  25430. return BABYLON.VertexData.CreatePlane(this.size, this.side);
  25431. };
  25432. Plane.prototype.copy = function (id) {
  25433. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  25434. };
  25435. return Plane;
  25436. })(_Primitive);
  25437. Primitives.Plane = Plane;
  25438. var TorusKnot = (function (_super) {
  25439. __extends(TorusKnot, _super);
  25440. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  25441. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25442. this.radius = radius;
  25443. this.tube = tube;
  25444. this.radialSegments = radialSegments;
  25445. this.tubularSegments = tubularSegments;
  25446. this.p = p;
  25447. this.q = q;
  25448. this.side = side;
  25449. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25450. }
  25451. TorusKnot.prototype._regenerateVertexData = function () {
  25452. return BABYLON.VertexData.CreateTorusKnot(this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.side);
  25453. };
  25454. TorusKnot.prototype.copy = function (id) {
  25455. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  25456. };
  25457. return TorusKnot;
  25458. })(_Primitive);
  25459. Primitives.TorusKnot = TorusKnot;
  25460. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  25461. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  25462. })(BABYLON || (BABYLON = {}));
  25463. //# sourceMappingURL=babylon.geometry.js.map
  25464. var BABYLON;
  25465. (function (BABYLON) {
  25466. var Gamepads = (function () {
  25467. function Gamepads(ongamedpadconnected) {
  25468. var _this = this;
  25469. this.babylonGamepads = [];
  25470. this.oneGamepadConnected = false;
  25471. this.isMonitoring = false;
  25472. this.gamepadEventSupported = 'GamepadEvent' in window;
  25473. this.gamepadSupportAvailable = (navigator.getGamepads || !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  25474. 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=";
  25475. this._callbackGamepadConnected = ongamedpadconnected;
  25476. if (this.gamepadSupportAvailable) {
  25477. // Checking if the gamepad connected event is supported (like in Firefox)
  25478. if (this.gamepadEventSupported) {
  25479. window.addEventListener('gamepadconnected', function (evt) {
  25480. _this._onGamepadConnected(evt);
  25481. }, false);
  25482. window.addEventListener('gamepaddisconnected', function (evt) {
  25483. _this._onGamepadDisconnected(evt);
  25484. }, false);
  25485. }
  25486. else {
  25487. this._startMonitoringGamepads();
  25488. }
  25489. if (!this.oneGamepadConnected) {
  25490. this._insertGamepadDOMInstructions();
  25491. }
  25492. }
  25493. else {
  25494. this._insertGamepadDOMNotSupported();
  25495. }
  25496. }
  25497. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  25498. Gamepads.gamepadDOMInfo = document.createElement("div");
  25499. var buttonAImage = document.createElement("img");
  25500. buttonAImage.src = this.buttonADataURL;
  25501. var spanMessage = document.createElement("span");
  25502. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  25503. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  25504. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  25505. Gamepads.gamepadDOMInfo.style.position = "absolute";
  25506. Gamepads.gamepadDOMInfo.style.width = "100%";
  25507. Gamepads.gamepadDOMInfo.style.height = "48px";
  25508. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  25509. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  25510. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  25511. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  25512. buttonAImage.style.position = "relative";
  25513. buttonAImage.style.bottom = "8px";
  25514. spanMessage.style.position = "relative";
  25515. spanMessage.style.fontSize = "32px";
  25516. spanMessage.style.bottom = "32px";
  25517. spanMessage.style.color = "green";
  25518. document.body.appendChild(Gamepads.gamepadDOMInfo);
  25519. };
  25520. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  25521. Gamepads.gamepadDOMInfo = document.createElement("div");
  25522. var spanMessage = document.createElement("span");
  25523. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  25524. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  25525. Gamepads.gamepadDOMInfo.style.position = "absolute";
  25526. Gamepads.gamepadDOMInfo.style.width = "100%";
  25527. Gamepads.gamepadDOMInfo.style.height = "40px";
  25528. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  25529. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  25530. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  25531. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  25532. spanMessage.style.position = "relative";
  25533. spanMessage.style.fontSize = "32px";
  25534. spanMessage.style.color = "red";
  25535. document.body.appendChild(Gamepads.gamepadDOMInfo);
  25536. };
  25537. Gamepads.prototype.dispose = function () {
  25538. if (Gamepads.gamepadDOMInfo) {
  25539. document.body.removeChild(Gamepads.gamepadDOMInfo);
  25540. }
  25541. };
  25542. Gamepads.prototype._onGamepadConnected = function (evt) {
  25543. var newGamepad = this._addNewGamepad(evt.gamepad);
  25544. if (this._callbackGamepadConnected)
  25545. this._callbackGamepadConnected(newGamepad);
  25546. this._startMonitoringGamepads();
  25547. };
  25548. Gamepads.prototype._addNewGamepad = function (gamepad) {
  25549. if (!this.oneGamepadConnected) {
  25550. this.oneGamepadConnected = true;
  25551. if (Gamepads.gamepadDOMInfo) {
  25552. document.body.removeChild(Gamepads.gamepadDOMInfo);
  25553. Gamepads.gamepadDOMInfo = null;
  25554. }
  25555. }
  25556. var newGamepad;
  25557. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  25558. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  25559. }
  25560. else {
  25561. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  25562. }
  25563. this.babylonGamepads.push(newGamepad);
  25564. return newGamepad;
  25565. };
  25566. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  25567. for (var i in this.babylonGamepads) {
  25568. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  25569. this.babylonGamepads.splice(i, 1);
  25570. break;
  25571. }
  25572. }
  25573. // If no gamepads are left, stop the polling loop.
  25574. if (this.babylonGamepads.length == 0) {
  25575. this._stopMonitoringGamepads();
  25576. }
  25577. };
  25578. Gamepads.prototype._startMonitoringGamepads = function () {
  25579. if (!this.isMonitoring) {
  25580. this.isMonitoring = true;
  25581. this._checkGamepadsStatus();
  25582. }
  25583. };
  25584. Gamepads.prototype._stopMonitoringGamepads = function () {
  25585. this.isMonitoring = false;
  25586. };
  25587. Gamepads.prototype._checkGamepadsStatus = function () {
  25588. var _this = this;
  25589. // updating gamepad objects
  25590. this._updateGamepadObjects();
  25591. for (var i in this.babylonGamepads) {
  25592. this.babylonGamepads[i].update();
  25593. }
  25594. if (this.isMonitoring) {
  25595. if (window.requestAnimationFrame) {
  25596. window.requestAnimationFrame(function () {
  25597. _this._checkGamepadsStatus();
  25598. });
  25599. }
  25600. else if (window.mozRequestAnimationFrame) {
  25601. window.mozRequestAnimationFrame(function () {
  25602. _this._checkGamepadsStatus();
  25603. });
  25604. }
  25605. else if (window.webkitRequestAnimationFrame) {
  25606. window.webkitRequestAnimationFrame(function () {
  25607. _this._checkGamepadsStatus();
  25608. });
  25609. }
  25610. }
  25611. };
  25612. // This function is called only on Chrome, which does not yet support
  25613. // connection/disconnection events, but requires you to monitor
  25614. // an array for changes.
  25615. Gamepads.prototype._updateGamepadObjects = function () {
  25616. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  25617. for (var i = 0; i < gamepads.length; i++) {
  25618. if (gamepads[i]) {
  25619. if (!(gamepads[i].index in this.babylonGamepads)) {
  25620. var newGamepad = this._addNewGamepad(gamepads[i]);
  25621. if (this._callbackGamepadConnected) {
  25622. this._callbackGamepadConnected(newGamepad);
  25623. }
  25624. }
  25625. else {
  25626. this.babylonGamepads[i].browserGamepad = gamepads[i];
  25627. }
  25628. }
  25629. }
  25630. };
  25631. return Gamepads;
  25632. })();
  25633. BABYLON.Gamepads = Gamepads;
  25634. var StickValues = (function () {
  25635. function StickValues(x, y) {
  25636. this.x = x;
  25637. this.y = y;
  25638. }
  25639. return StickValues;
  25640. })();
  25641. BABYLON.StickValues = StickValues;
  25642. var Gamepad = (function () {
  25643. function Gamepad(id, index, browserGamepad) {
  25644. this.id = id;
  25645. this.index = index;
  25646. this.browserGamepad = browserGamepad;
  25647. if (this.browserGamepad.axes.length >= 2) {
  25648. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  25649. }
  25650. if (this.browserGamepad.axes.length >= 4) {
  25651. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  25652. }
  25653. }
  25654. Gamepad.prototype.onleftstickchanged = function (callback) {
  25655. this._onleftstickchanged = callback;
  25656. };
  25657. Gamepad.prototype.onrightstickchanged = function (callback) {
  25658. this._onrightstickchanged = callback;
  25659. };
  25660. Object.defineProperty(Gamepad.prototype, "leftStick", {
  25661. get: function () {
  25662. return this._leftStick;
  25663. },
  25664. set: function (newValues) {
  25665. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  25666. this._onleftstickchanged(newValues);
  25667. }
  25668. this._leftStick = newValues;
  25669. },
  25670. enumerable: true,
  25671. configurable: true
  25672. });
  25673. Object.defineProperty(Gamepad.prototype, "rightStick", {
  25674. get: function () {
  25675. return this._rightStick;
  25676. },
  25677. set: function (newValues) {
  25678. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  25679. this._onrightstickchanged(newValues);
  25680. }
  25681. this._rightStick = newValues;
  25682. },
  25683. enumerable: true,
  25684. configurable: true
  25685. });
  25686. Gamepad.prototype.update = function () {
  25687. if (this._leftStick) {
  25688. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  25689. }
  25690. if (this._rightStick) {
  25691. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  25692. }
  25693. };
  25694. return Gamepad;
  25695. })();
  25696. BABYLON.Gamepad = Gamepad;
  25697. var GenericPad = (function (_super) {
  25698. __extends(GenericPad, _super);
  25699. function GenericPad(id, index, gamepad) {
  25700. _super.call(this, id, index, gamepad);
  25701. this.id = id;
  25702. this.index = index;
  25703. this.gamepad = gamepad;
  25704. this._buttons = new Array(gamepad.buttons.length);
  25705. }
  25706. GenericPad.prototype.onbuttondown = function (callback) {
  25707. this._onbuttondown = callback;
  25708. };
  25709. GenericPad.prototype.onbuttonup = function (callback) {
  25710. this._onbuttonup = callback;
  25711. };
  25712. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  25713. if (newValue !== currentValue) {
  25714. if (this._onbuttondown && newValue === 1) {
  25715. this._onbuttondown(buttonIndex);
  25716. }
  25717. if (this._onbuttonup && newValue === 0) {
  25718. this._onbuttonup(buttonIndex);
  25719. }
  25720. }
  25721. return newValue;
  25722. };
  25723. GenericPad.prototype.update = function () {
  25724. _super.prototype.update.call(this);
  25725. for (var index = 0; index < this._buttons.length; index++) {
  25726. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  25727. }
  25728. };
  25729. return GenericPad;
  25730. })(Gamepad);
  25731. BABYLON.GenericPad = GenericPad;
  25732. (function (Xbox360Button) {
  25733. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  25734. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  25735. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  25736. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  25737. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  25738. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  25739. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  25740. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  25741. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  25742. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  25743. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  25744. var Xbox360Button = BABYLON.Xbox360Button;
  25745. (function (Xbox360Dpad) {
  25746. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  25747. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  25748. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  25749. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  25750. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  25751. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  25752. var Xbox360Pad = (function (_super) {
  25753. __extends(Xbox360Pad, _super);
  25754. function Xbox360Pad() {
  25755. _super.apply(this, arguments);
  25756. this._leftTrigger = 0;
  25757. this._rightTrigger = 0;
  25758. this._buttonA = 0;
  25759. this._buttonB = 0;
  25760. this._buttonX = 0;
  25761. this._buttonY = 0;
  25762. this._buttonBack = 0;
  25763. this._buttonStart = 0;
  25764. this._buttonLB = 0;
  25765. this._buttonRB = 0;
  25766. this._buttonLeftStick = 0;
  25767. this._buttonRightStick = 0;
  25768. this._dPadUp = 0;
  25769. this._dPadDown = 0;
  25770. this._dPadLeft = 0;
  25771. this._dPadRight = 0;
  25772. }
  25773. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  25774. this._onlefttriggerchanged = callback;
  25775. };
  25776. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  25777. this._onrighttriggerchanged = callback;
  25778. };
  25779. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  25780. get: function () {
  25781. return this._leftTrigger;
  25782. },
  25783. set: function (newValue) {
  25784. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  25785. this._onlefttriggerchanged(newValue);
  25786. }
  25787. this._leftTrigger = newValue;
  25788. },
  25789. enumerable: true,
  25790. configurable: true
  25791. });
  25792. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  25793. get: function () {
  25794. return this._rightTrigger;
  25795. },
  25796. set: function (newValue) {
  25797. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  25798. this._onrighttriggerchanged(newValue);
  25799. }
  25800. this._rightTrigger = newValue;
  25801. },
  25802. enumerable: true,
  25803. configurable: true
  25804. });
  25805. Xbox360Pad.prototype.onbuttondown = function (callback) {
  25806. this._onbuttondown = callback;
  25807. };
  25808. Xbox360Pad.prototype.onbuttonup = function (callback) {
  25809. this._onbuttonup = callback;
  25810. };
  25811. Xbox360Pad.prototype.ondpaddown = function (callback) {
  25812. this._ondpaddown = callback;
  25813. };
  25814. Xbox360Pad.prototype.ondpadup = function (callback) {
  25815. this._ondpadup = callback;
  25816. };
  25817. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  25818. if (newValue !== currentValue) {
  25819. if (this._onbuttondown && newValue === 1) {
  25820. this._onbuttondown(buttonType);
  25821. }
  25822. if (this._onbuttonup && newValue === 0) {
  25823. this._onbuttonup(buttonType);
  25824. }
  25825. }
  25826. return newValue;
  25827. };
  25828. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  25829. if (newValue !== currentValue) {
  25830. if (this._ondpaddown && newValue === 1) {
  25831. this._ondpaddown(buttonType);
  25832. }
  25833. if (this._ondpadup && newValue === 0) {
  25834. this._ondpadup(buttonType);
  25835. }
  25836. }
  25837. return newValue;
  25838. };
  25839. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  25840. get: function () {
  25841. return this._buttonA;
  25842. },
  25843. set: function (value) {
  25844. this._buttonA = this._setButtonValue(value, this._buttonA, 0 /* A */);
  25845. },
  25846. enumerable: true,
  25847. configurable: true
  25848. });
  25849. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  25850. get: function () {
  25851. return this._buttonB;
  25852. },
  25853. set: function (value) {
  25854. this._buttonB = this._setButtonValue(value, this._buttonB, 1 /* B */);
  25855. },
  25856. enumerable: true,
  25857. configurable: true
  25858. });
  25859. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  25860. get: function () {
  25861. return this._buttonX;
  25862. },
  25863. set: function (value) {
  25864. this._buttonX = this._setButtonValue(value, this._buttonX, 2 /* X */);
  25865. },
  25866. enumerable: true,
  25867. configurable: true
  25868. });
  25869. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  25870. get: function () {
  25871. return this._buttonY;
  25872. },
  25873. set: function (value) {
  25874. this._buttonY = this._setButtonValue(value, this._buttonY, 3 /* Y */);
  25875. },
  25876. enumerable: true,
  25877. configurable: true
  25878. });
  25879. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  25880. get: function () {
  25881. return this._buttonStart;
  25882. },
  25883. set: function (value) {
  25884. this._buttonStart = this._setButtonValue(value, this._buttonStart, 4 /* Start */);
  25885. },
  25886. enumerable: true,
  25887. configurable: true
  25888. });
  25889. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  25890. get: function () {
  25891. return this._buttonBack;
  25892. },
  25893. set: function (value) {
  25894. this._buttonBack = this._setButtonValue(value, this._buttonBack, 5 /* Back */);
  25895. },
  25896. enumerable: true,
  25897. configurable: true
  25898. });
  25899. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  25900. get: function () {
  25901. return this._buttonLB;
  25902. },
  25903. set: function (value) {
  25904. this._buttonLB = this._setButtonValue(value, this._buttonLB, 6 /* LB */);
  25905. },
  25906. enumerable: true,
  25907. configurable: true
  25908. });
  25909. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  25910. get: function () {
  25911. return this._buttonRB;
  25912. },
  25913. set: function (value) {
  25914. this._buttonRB = this._setButtonValue(value, this._buttonRB, 7 /* RB */);
  25915. },
  25916. enumerable: true,
  25917. configurable: true
  25918. });
  25919. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  25920. get: function () {
  25921. return this._buttonLeftStick;
  25922. },
  25923. set: function (value) {
  25924. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, 8 /* LeftStick */);
  25925. },
  25926. enumerable: true,
  25927. configurable: true
  25928. });
  25929. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  25930. get: function () {
  25931. return this._buttonRightStick;
  25932. },
  25933. set: function (value) {
  25934. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, 9 /* RightStick */);
  25935. },
  25936. enumerable: true,
  25937. configurable: true
  25938. });
  25939. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  25940. get: function () {
  25941. return this._dPadUp;
  25942. },
  25943. set: function (value) {
  25944. this._dPadUp = this._setDPadValue(value, this._dPadUp, 0 /* Up */);
  25945. },
  25946. enumerable: true,
  25947. configurable: true
  25948. });
  25949. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  25950. get: function () {
  25951. return this._dPadDown;
  25952. },
  25953. set: function (value) {
  25954. this._dPadDown = this._setDPadValue(value, this._dPadDown, 1 /* Down */);
  25955. },
  25956. enumerable: true,
  25957. configurable: true
  25958. });
  25959. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  25960. get: function () {
  25961. return this._dPadLeft;
  25962. },
  25963. set: function (value) {
  25964. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, 2 /* Left */);
  25965. },
  25966. enumerable: true,
  25967. configurable: true
  25968. });
  25969. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  25970. get: function () {
  25971. return this._dPadRight;
  25972. },
  25973. set: function (value) {
  25974. this._dPadRight = this._setDPadValue(value, this._dPadRight, 3 /* Right */);
  25975. },
  25976. enumerable: true,
  25977. configurable: true
  25978. });
  25979. Xbox360Pad.prototype.update = function () {
  25980. _super.prototype.update.call(this);
  25981. this.buttonA = this.browserGamepad.buttons[0].value;
  25982. this.buttonB = this.browserGamepad.buttons[1].value;
  25983. this.buttonX = this.browserGamepad.buttons[2].value;
  25984. this.buttonY = this.browserGamepad.buttons[3].value;
  25985. this.buttonLB = this.browserGamepad.buttons[4].value;
  25986. this.buttonRB = this.browserGamepad.buttons[5].value;
  25987. this.leftTrigger = this.browserGamepad.buttons[6].value;
  25988. this.rightTrigger = this.browserGamepad.buttons[7].value;
  25989. this.buttonBack = this.browserGamepad.buttons[8].value;
  25990. this.buttonStart = this.browserGamepad.buttons[9].value;
  25991. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  25992. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  25993. this.dPadUp = this.browserGamepad.buttons[12].value;
  25994. this.dPadDown = this.browserGamepad.buttons[13].value;
  25995. this.dPadLeft = this.browserGamepad.buttons[14].value;
  25996. this.dPadRight = this.browserGamepad.buttons[15].value;
  25997. };
  25998. return Xbox360Pad;
  25999. })(Gamepad);
  26000. BABYLON.Xbox360Pad = Xbox360Pad;
  26001. })(BABYLON || (BABYLON = {}));
  26002. //# sourceMappingURL=babylon.gamepads.js.map
  26003. var BABYLON;
  26004. (function (BABYLON) {
  26005. // We're mainly based on the logic defined into the FreeCamera code
  26006. var GamepadCamera = (function (_super) {
  26007. __extends(GamepadCamera, _super);
  26008. function GamepadCamera(name, position, scene) {
  26009. var _this = this;
  26010. _super.call(this, name, position, scene);
  26011. this.angularSensibility = 200;
  26012. this.moveSensibility = 75;
  26013. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  26014. _this._onNewGameConnected(gamepad);
  26015. });
  26016. }
  26017. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  26018. // Only the first gamepad can control the camera
  26019. if (gamepad.index === 0) {
  26020. this._gamepad = gamepad;
  26021. }
  26022. };
  26023. GamepadCamera.prototype._checkInputs = function () {
  26024. if (!this._gamepad) {
  26025. return;
  26026. }
  26027. var LSValues = this._gamepad.leftStick;
  26028. var normalizedLX = LSValues.x / this.moveSensibility;
  26029. var normalizedLY = LSValues.y / this.moveSensibility;
  26030. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  26031. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  26032. var RSValues = this._gamepad.rightStick;
  26033. var normalizedRX = RSValues.x / this.angularSensibility;
  26034. var normalizedRY = RSValues.y / this.angularSensibility;
  26035. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  26036. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  26037. ;
  26038. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  26039. var speed = this._computeLocalCameraSpeed() * 50.0;
  26040. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  26041. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  26042. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  26043. };
  26044. GamepadCamera.prototype.dispose = function () {
  26045. this._gamepads.dispose();
  26046. _super.prototype.dispose.call(this);
  26047. };
  26048. return GamepadCamera;
  26049. })(BABYLON.FreeCamera);
  26050. BABYLON.GamepadCamera = GamepadCamera;
  26051. })(BABYLON || (BABYLON = {}));
  26052. //# sourceMappingURL=babylon.gamepadCamera.js.map
  26053. var BABYLON;
  26054. (function (BABYLON) {
  26055. var LinesMesh = (function (_super) {
  26056. __extends(LinesMesh, _super);
  26057. function LinesMesh(name, scene, updatable) {
  26058. if (updatable === void 0) { updatable = false; }
  26059. _super.call(this, name, scene);
  26060. this.color = new BABYLON.Color3(1, 1, 1);
  26061. this.alpha = 1;
  26062. this._indices = new Array();
  26063. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  26064. attributes: ["position"],
  26065. uniforms: ["worldViewProjection", "color"],
  26066. needAlphaBlending: true
  26067. });
  26068. }
  26069. Object.defineProperty(LinesMesh.prototype, "material", {
  26070. get: function () {
  26071. return this._colorShader;
  26072. },
  26073. enumerable: true,
  26074. configurable: true
  26075. });
  26076. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  26077. get: function () {
  26078. return false;
  26079. },
  26080. enumerable: true,
  26081. configurable: true
  26082. });
  26083. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  26084. get: function () {
  26085. return false;
  26086. },
  26087. enumerable: true,
  26088. configurable: true
  26089. });
  26090. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  26091. var engine = this.getScene().getEngine();
  26092. var indexToBind = this._geometry.getIndexBuffer();
  26093. // VBOs
  26094. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  26095. // Color
  26096. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  26097. };
  26098. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  26099. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  26100. return;
  26101. }
  26102. var engine = this.getScene().getEngine();
  26103. // Draw order
  26104. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  26105. };
  26106. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  26107. return null;
  26108. };
  26109. LinesMesh.prototype.dispose = function (doNotRecurse) {
  26110. this._colorShader.dispose();
  26111. _super.prototype.dispose.call(this, doNotRecurse);
  26112. };
  26113. return LinesMesh;
  26114. })(BABYLON.Mesh);
  26115. BABYLON.LinesMesh = LinesMesh;
  26116. })(BABYLON || (BABYLON = {}));
  26117. //# sourceMappingURL=babylon.linesMesh.js.mapvar BABYLON;
  26118. (function (BABYLON) {
  26119. var OutlineRenderer = (function () {
  26120. function OutlineRenderer(scene) {
  26121. this._scene = scene;
  26122. }
  26123. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  26124. var _this = this;
  26125. if (useOverlay === void 0) { useOverlay = false; }
  26126. var scene = this._scene;
  26127. var engine = this._scene.getEngine();
  26128. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  26129. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  26130. return;
  26131. }
  26132. var mesh = subMesh.getRenderingMesh();
  26133. var material = subMesh.getMaterial();
  26134. engine.enableEffect(this._effect);
  26135. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  26136. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  26137. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  26138. // Bones
  26139. if (mesh.useBones) {
  26140. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  26141. }
  26142. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  26143. // Alpha test
  26144. if (material && material.needAlphaTesting()) {
  26145. var alphaTexture = material.getAlphaTestTexture();
  26146. this._effect.setTexture("diffuseSampler", alphaTexture);
  26147. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  26148. }
  26149. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  26150. _this._effect.setMatrix("world", world);
  26151. });
  26152. };
  26153. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  26154. var defines = [];
  26155. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  26156. var mesh = subMesh.getMesh();
  26157. var material = subMesh.getMaterial();
  26158. // Alpha test
  26159. if (material && material.needAlphaTesting()) {
  26160. defines.push("#define ALPHATEST");
  26161. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  26162. attribs.push(BABYLON.VertexBuffer.UVKind);
  26163. defines.push("#define UV1");
  26164. }
  26165. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  26166. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  26167. defines.push("#define UV2");
  26168. }
  26169. }
  26170. // Bones
  26171. if (mesh.useBones) {
  26172. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  26173. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  26174. defines.push("#define BONES");
  26175. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  26176. }
  26177. // Instances
  26178. if (useInstances) {
  26179. defines.push("#define INSTANCES");
  26180. attribs.push("world0");
  26181. attribs.push("world1");
  26182. attribs.push("world2");
  26183. attribs.push("world3");
  26184. }
  26185. // Get correct effect
  26186. var join = defines.join("\n");
  26187. if (this._cachedDefines !== join) {
  26188. this._cachedDefines = join;
  26189. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  26190. }
  26191. return this._effect.isReady();
  26192. };
  26193. return OutlineRenderer;
  26194. })();
  26195. BABYLON.OutlineRenderer = OutlineRenderer;
  26196. })(BABYLON || (BABYLON = {}));
  26197. //# sourceMappingURL=babylon.outlineRenderer.js.mapvar BABYLON;
  26198. (function (BABYLON) {
  26199. var MeshAssetTask = (function () {
  26200. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  26201. this.name = name;
  26202. this.meshesNames = meshesNames;
  26203. this.rootUrl = rootUrl;
  26204. this.sceneFilename = sceneFilename;
  26205. this.isCompleted = false;
  26206. }
  26207. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  26208. var _this = this;
  26209. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  26210. _this.loadedMeshes = meshes;
  26211. _this.loadedParticleSystems = particleSystems;
  26212. _this.loadedSkeletons = skeletons;
  26213. _this.isCompleted = true;
  26214. if (_this.onSuccess) {
  26215. _this.onSuccess(_this);
  26216. }
  26217. onSuccess();
  26218. }, null, function () {
  26219. if (_this.onError) {
  26220. _this.onError(_this);
  26221. }
  26222. onError();
  26223. });
  26224. };
  26225. return MeshAssetTask;
  26226. })();
  26227. BABYLON.MeshAssetTask = MeshAssetTask;
  26228. var TextFileAssetTask = (function () {
  26229. function TextFileAssetTask(name, url) {
  26230. this.name = name;
  26231. this.url = url;
  26232. this.isCompleted = false;
  26233. }
  26234. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  26235. var _this = this;
  26236. BABYLON.Tools.LoadFile(this.url, function (data) {
  26237. _this.text = data;
  26238. _this.isCompleted = true;
  26239. if (_this.onSuccess) {
  26240. _this.onSuccess(_this);
  26241. }
  26242. onSuccess();
  26243. }, null, scene.database, false, function () {
  26244. if (_this.onError) {
  26245. _this.onError(_this);
  26246. }
  26247. onError();
  26248. });
  26249. };
  26250. return TextFileAssetTask;
  26251. })();
  26252. BABYLON.TextFileAssetTask = TextFileAssetTask;
  26253. var BinaryFileAssetTask = (function () {
  26254. function BinaryFileAssetTask(name, url) {
  26255. this.name = name;
  26256. this.url = url;
  26257. this.isCompleted = false;
  26258. }
  26259. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  26260. var _this = this;
  26261. BABYLON.Tools.LoadFile(this.url, function (data) {
  26262. _this.data = data;
  26263. _this.isCompleted = true;
  26264. if (_this.onSuccess) {
  26265. _this.onSuccess(_this);
  26266. }
  26267. onSuccess();
  26268. }, null, scene.database, true, function () {
  26269. if (_this.onError) {
  26270. _this.onError(_this);
  26271. }
  26272. onError();
  26273. });
  26274. };
  26275. return BinaryFileAssetTask;
  26276. })();
  26277. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  26278. var ImageAssetTask = (function () {
  26279. function ImageAssetTask(name, url) {
  26280. this.name = name;
  26281. this.url = url;
  26282. this.isCompleted = false;
  26283. }
  26284. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  26285. var _this = this;
  26286. var img = new Image();
  26287. img.onload = function () {
  26288. _this.image = img;
  26289. _this.isCompleted = true;
  26290. if (_this.onSuccess) {
  26291. _this.onSuccess(_this);
  26292. }
  26293. onSuccess();
  26294. };
  26295. img.onerror = function () {
  26296. if (_this.onError) {
  26297. _this.onError(_this);
  26298. }
  26299. onError();
  26300. };
  26301. img.src = this.url;
  26302. };
  26303. return ImageAssetTask;
  26304. })();
  26305. BABYLON.ImageAssetTask = ImageAssetTask;
  26306. var TextureAssetTask = (function () {
  26307. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  26308. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  26309. this.name = name;
  26310. this.url = url;
  26311. this.noMipmap = noMipmap;
  26312. this.invertY = invertY;
  26313. this.samplingMode = samplingMode;
  26314. this.isCompleted = false;
  26315. }
  26316. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  26317. var _this = this;
  26318. var onload = function () {
  26319. _this.isCompleted = true;
  26320. if (_this.onSuccess) {
  26321. _this.onSuccess(_this);
  26322. }
  26323. onSuccess();
  26324. };
  26325. var onerror = function () {
  26326. if (_this.onError) {
  26327. _this.onError(_this);
  26328. }
  26329. onError();
  26330. };
  26331. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onError);
  26332. };
  26333. return TextureAssetTask;
  26334. })();
  26335. BABYLON.TextureAssetTask = TextureAssetTask;
  26336. var AssetsManager = (function () {
  26337. function AssetsManager(scene) {
  26338. this._tasks = new Array();
  26339. this._waitingTasksCount = 0;
  26340. this.useDefaultLoadingScreen = true;
  26341. this._scene = scene;
  26342. }
  26343. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  26344. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  26345. this._tasks.push(task);
  26346. return task;
  26347. };
  26348. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  26349. var task = new TextFileAssetTask(taskName, url);
  26350. this._tasks.push(task);
  26351. return task;
  26352. };
  26353. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  26354. var task = new BinaryFileAssetTask(taskName, url);
  26355. this._tasks.push(task);
  26356. return task;
  26357. };
  26358. AssetsManager.prototype.addImageTask = function (taskName, url) {
  26359. var task = new ImageAssetTask(taskName, url);
  26360. this._tasks.push(task);
  26361. return task;
  26362. };
  26363. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  26364. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  26365. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  26366. this._tasks.push(task);
  26367. return task;
  26368. };
  26369. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  26370. this._waitingTasksCount--;
  26371. if (this._waitingTasksCount === 0) {
  26372. if (this.onFinish) {
  26373. this.onFinish(this._tasks);
  26374. }
  26375. this._scene.getEngine().hideLoadingUI();
  26376. }
  26377. };
  26378. AssetsManager.prototype._runTask = function (task) {
  26379. var _this = this;
  26380. task.run(this._scene, function () {
  26381. if (_this.onTaskSuccess) {
  26382. _this.onTaskSuccess(task);
  26383. }
  26384. _this._decreaseWaitingTasksCount();
  26385. }, function () {
  26386. if (_this.onTaskError) {
  26387. _this.onTaskError(task);
  26388. }
  26389. _this._decreaseWaitingTasksCount();
  26390. });
  26391. };
  26392. AssetsManager.prototype.reset = function () {
  26393. this._tasks = new Array();
  26394. return this;
  26395. };
  26396. AssetsManager.prototype.load = function () {
  26397. this._waitingTasksCount = this._tasks.length;
  26398. if (this._waitingTasksCount === 0) {
  26399. if (this.onFinish) {
  26400. this.onFinish(this._tasks);
  26401. }
  26402. return this;
  26403. }
  26404. if (this.useDefaultLoadingScreen) {
  26405. this._scene.getEngine().displayLoadingUI();
  26406. }
  26407. for (var index = 0; index < this._tasks.length; index++) {
  26408. var task = this._tasks[index];
  26409. this._runTask(task);
  26410. }
  26411. return this;
  26412. };
  26413. return AssetsManager;
  26414. })();
  26415. BABYLON.AssetsManager = AssetsManager;
  26416. })(BABYLON || (BABYLON = {}));
  26417. //# sourceMappingURL=babylon.assetsManager.js.map
  26418. var BABYLON;
  26419. (function (BABYLON) {
  26420. var VRDeviceOrientationCamera = (function (_super) {
  26421. __extends(VRDeviceOrientationCamera, _super);
  26422. function VRDeviceOrientationCamera(name, position, scene) {
  26423. _super.call(this, name, position, scene);
  26424. this._alpha = 0;
  26425. this._beta = 0;
  26426. this._gamma = 0;
  26427. }
  26428. VRDeviceOrientationCamera.prototype._onOrientationEvent = function (evt) {
  26429. this._alpha = +evt.alpha | 0;
  26430. this._beta = +evt.beta | 0;
  26431. this._gamma = +evt.gamma | 0;
  26432. if (this._gamma < 0) {
  26433. this._gamma = 90 + this._gamma;
  26434. }
  26435. else {
  26436. // Incline it in the correct angle.
  26437. this._gamma = 270 - this._gamma;
  26438. }
  26439. this.rotation.x = this._gamma / 180.0 * Math.PI;
  26440. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  26441. this.rotation.z = this._beta / 180.0 * Math.PI;
  26442. };
  26443. return VRDeviceOrientationCamera;
  26444. })(BABYLON.OculusCamera);
  26445. BABYLON.VRDeviceOrientationCamera = VRDeviceOrientationCamera;
  26446. })(BABYLON || (BABYLON = {}));
  26447. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  26448. var BABYLON;
  26449. (function (BABYLON) {
  26450. var WebVRCamera = (function (_super) {
  26451. __extends(WebVRCamera, _super);
  26452. function WebVRCamera(name, position, scene) {
  26453. _super.call(this, name, position, scene);
  26454. this._hmdDevice = null;
  26455. this._sensorDevice = null;
  26456. this._cacheState = null;
  26457. this._cacheQuaternion = new BABYLON.Quaternion();
  26458. this._cacheRotation = BABYLON.Vector3.Zero();
  26459. this._vrEnabled = false;
  26460. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  26461. }
  26462. WebVRCamera.prototype._getWebVRDevices = function (devices) {
  26463. var size = devices.length;
  26464. var i = 0;
  26465. // Reset devices.
  26466. this._sensorDevice = null;
  26467. this._hmdDevice = null;
  26468. while (i < size && this._hmdDevice === null) {
  26469. if (devices[i] instanceof HMDVRDevice) {
  26470. this._hmdDevice = devices[i];
  26471. }
  26472. i++;
  26473. }
  26474. i = 0;
  26475. while (i < size && this._sensorDevice === null) {
  26476. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  26477. this._sensorDevice = devices[i];
  26478. }
  26479. i++;
  26480. }
  26481. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  26482. };
  26483. WebVRCamera.prototype._update = function () {
  26484. if (this._vrEnabled) {
  26485. this._cacheState = this._sensorDevice.getState();
  26486. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  26487. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  26488. this.rotation.x = -this._cacheRotation.z;
  26489. this.rotation.y = -this._cacheRotation.y;
  26490. this.rotation.z = this._cacheRotation.x;
  26491. }
  26492. _super.prototype._update.call(this);
  26493. };
  26494. WebVRCamera.prototype.attachControl = function (element, noPreventDefault) {
  26495. _super.prototype.attachControl.call(this, element, noPreventDefault);
  26496. if (navigator.getVRDevices) {
  26497. navigator.getVRDevices().then(this._getWebVRDevices);
  26498. }
  26499. else if (navigator.mozGetVRDevices) {
  26500. navigator.mozGetVRDevices(this._getWebVRDevices);
  26501. }
  26502. };
  26503. WebVRCamera.prototype.detachControl = function (element) {
  26504. _super.prototype.detachControl.call(this, element);
  26505. this._vrEnabled = false;
  26506. };
  26507. return WebVRCamera;
  26508. })(BABYLON.OculusCamera);
  26509. BABYLON.WebVRCamera = WebVRCamera;
  26510. })(BABYLON || (BABYLON = {}));
  26511. //# sourceMappingURL=babylon.webVRCamera.js.map
  26512. var BABYLON;
  26513. (function (BABYLON) {
  26514. // Standard optimizations
  26515. var SceneOptimization = (function () {
  26516. function SceneOptimization(priority) {
  26517. if (priority === void 0) { priority = 0; }
  26518. this.priority = priority;
  26519. this.apply = function (scene) {
  26520. return true; // Return true if everything that can be done was applied
  26521. };
  26522. }
  26523. return SceneOptimization;
  26524. })();
  26525. BABYLON.SceneOptimization = SceneOptimization;
  26526. var TextureOptimization = (function (_super) {
  26527. __extends(TextureOptimization, _super);
  26528. function TextureOptimization(priority, maximumSize) {
  26529. var _this = this;
  26530. if (priority === void 0) { priority = 0; }
  26531. if (maximumSize === void 0) { maximumSize = 1024; }
  26532. _super.call(this, priority);
  26533. this.priority = priority;
  26534. this.maximumSize = maximumSize;
  26535. this.apply = function (scene) {
  26536. var allDone = true;
  26537. for (var index = 0; index < scene.textures.length; index++) {
  26538. var texture = scene.textures[index];
  26539. if (!texture.canRescale) {
  26540. continue;
  26541. }
  26542. var currentSize = texture.getSize();
  26543. var maxDimension = Math.max(currentSize.width, currentSize.height);
  26544. if (maxDimension > _this.maximumSize) {
  26545. texture.scale(0.5);
  26546. allDone = false;
  26547. }
  26548. }
  26549. return allDone;
  26550. };
  26551. }
  26552. return TextureOptimization;
  26553. })(SceneOptimization);
  26554. BABYLON.TextureOptimization = TextureOptimization;
  26555. var HardwareScalingOptimization = (function (_super) {
  26556. __extends(HardwareScalingOptimization, _super);
  26557. function HardwareScalingOptimization(priority, maximumScale) {
  26558. var _this = this;
  26559. if (priority === void 0) { priority = 0; }
  26560. if (maximumScale === void 0) { maximumScale = 2; }
  26561. _super.call(this, priority);
  26562. this.priority = priority;
  26563. this.maximumScale = maximumScale;
  26564. this._currentScale = 1;
  26565. this.apply = function (scene) {
  26566. _this._currentScale++;
  26567. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  26568. return _this._currentScale >= _this.maximumScale;
  26569. };
  26570. }
  26571. return HardwareScalingOptimization;
  26572. })(SceneOptimization);
  26573. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  26574. var ShadowsOptimization = (function (_super) {
  26575. __extends(ShadowsOptimization, _super);
  26576. function ShadowsOptimization() {
  26577. _super.apply(this, arguments);
  26578. this.apply = function (scene) {
  26579. scene.shadowsEnabled = false;
  26580. return true;
  26581. };
  26582. }
  26583. return ShadowsOptimization;
  26584. })(SceneOptimization);
  26585. BABYLON.ShadowsOptimization = ShadowsOptimization;
  26586. var PostProcessesOptimization = (function (_super) {
  26587. __extends(PostProcessesOptimization, _super);
  26588. function PostProcessesOptimization() {
  26589. _super.apply(this, arguments);
  26590. this.apply = function (scene) {
  26591. scene.postProcessesEnabled = false;
  26592. return true;
  26593. };
  26594. }
  26595. return PostProcessesOptimization;
  26596. })(SceneOptimization);
  26597. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  26598. var LensFlaresOptimization = (function (_super) {
  26599. __extends(LensFlaresOptimization, _super);
  26600. function LensFlaresOptimization() {
  26601. _super.apply(this, arguments);
  26602. this.apply = function (scene) {
  26603. scene.lensFlaresEnabled = false;
  26604. return true;
  26605. };
  26606. }
  26607. return LensFlaresOptimization;
  26608. })(SceneOptimization);
  26609. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  26610. var ParticlesOptimization = (function (_super) {
  26611. __extends(ParticlesOptimization, _super);
  26612. function ParticlesOptimization() {
  26613. _super.apply(this, arguments);
  26614. this.apply = function (scene) {
  26615. scene.particlesEnabled = false;
  26616. return true;
  26617. };
  26618. }
  26619. return ParticlesOptimization;
  26620. })(SceneOptimization);
  26621. BABYLON.ParticlesOptimization = ParticlesOptimization;
  26622. var RenderTargetsOptimization = (function (_super) {
  26623. __extends(RenderTargetsOptimization, _super);
  26624. function RenderTargetsOptimization() {
  26625. _super.apply(this, arguments);
  26626. this.apply = function (scene) {
  26627. scene.renderTargetsEnabled = false;
  26628. return true;
  26629. };
  26630. }
  26631. return RenderTargetsOptimization;
  26632. })(SceneOptimization);
  26633. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  26634. var MergeMeshesOptimization = (function (_super) {
  26635. __extends(MergeMeshesOptimization, _super);
  26636. function MergeMeshesOptimization() {
  26637. var _this = this;
  26638. _super.apply(this, arguments);
  26639. this._canBeMerged = function (abstractMesh) {
  26640. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  26641. return false;
  26642. }
  26643. var mesh = abstractMesh;
  26644. if (!mesh.isVisible || !mesh.isEnabled()) {
  26645. return false;
  26646. }
  26647. if (mesh.instances.length > 0) {
  26648. return false;
  26649. }
  26650. if (mesh.skeleton || mesh.hasLODLevels) {
  26651. return false;
  26652. }
  26653. return true;
  26654. };
  26655. this.apply = function (scene) {
  26656. var globalPool = scene.meshes.slice(0);
  26657. var globalLength = globalPool.length;
  26658. for (var index = 0; index < globalLength; index++) {
  26659. var currentPool = new Array();
  26660. var current = globalPool[index];
  26661. // Checks
  26662. if (!_this._canBeMerged(current)) {
  26663. continue;
  26664. }
  26665. currentPool.push(current);
  26666. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  26667. var otherMesh = globalPool[subIndex];
  26668. if (!_this._canBeMerged(otherMesh)) {
  26669. continue;
  26670. }
  26671. if (otherMesh.material !== current.material) {
  26672. continue;
  26673. }
  26674. if (otherMesh.checkCollisions !== current.checkCollisions) {
  26675. continue;
  26676. }
  26677. currentPool.push(otherMesh);
  26678. globalLength--;
  26679. globalPool.splice(subIndex, 1);
  26680. subIndex--;
  26681. }
  26682. if (currentPool.length < 2) {
  26683. continue;
  26684. }
  26685. // Merge meshes
  26686. BABYLON.Mesh.MergeMeshes(currentPool);
  26687. }
  26688. return true;
  26689. };
  26690. }
  26691. return MergeMeshesOptimization;
  26692. })(SceneOptimization);
  26693. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  26694. // Options
  26695. var SceneOptimizerOptions = (function () {
  26696. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  26697. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  26698. if (trackerDuration === void 0) { trackerDuration = 2000; }
  26699. this.targetFrameRate = targetFrameRate;
  26700. this.trackerDuration = trackerDuration;
  26701. this.optimizations = new Array();
  26702. }
  26703. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  26704. var result = new SceneOptimizerOptions(targetFrameRate);
  26705. var priority = 0;
  26706. result.optimizations.push(new MergeMeshesOptimization(priority));
  26707. result.optimizations.push(new ShadowsOptimization(priority));
  26708. result.optimizations.push(new LensFlaresOptimization(priority));
  26709. // Next priority
  26710. priority++;
  26711. result.optimizations.push(new PostProcessesOptimization(priority));
  26712. result.optimizations.push(new ParticlesOptimization(priority));
  26713. // Next priority
  26714. priority++;
  26715. result.optimizations.push(new TextureOptimization(priority, 1024));
  26716. return result;
  26717. };
  26718. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  26719. var result = new SceneOptimizerOptions(targetFrameRate);
  26720. var priority = 0;
  26721. result.optimizations.push(new MergeMeshesOptimization(priority));
  26722. result.optimizations.push(new ShadowsOptimization(priority));
  26723. result.optimizations.push(new LensFlaresOptimization(priority));
  26724. // Next priority
  26725. priority++;
  26726. result.optimizations.push(new PostProcessesOptimization(priority));
  26727. result.optimizations.push(new ParticlesOptimization(priority));
  26728. // Next priority
  26729. priority++;
  26730. result.optimizations.push(new TextureOptimization(priority, 512));
  26731. // Next priority
  26732. priority++;
  26733. result.optimizations.push(new RenderTargetsOptimization(priority));
  26734. // Next priority
  26735. priority++;
  26736. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  26737. return result;
  26738. };
  26739. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  26740. var result = new SceneOptimizerOptions(targetFrameRate);
  26741. var priority = 0;
  26742. result.optimizations.push(new MergeMeshesOptimization(priority));
  26743. result.optimizations.push(new ShadowsOptimization(priority));
  26744. result.optimizations.push(new LensFlaresOptimization(priority));
  26745. // Next priority
  26746. priority++;
  26747. result.optimizations.push(new PostProcessesOptimization(priority));
  26748. result.optimizations.push(new ParticlesOptimization(priority));
  26749. // Next priority
  26750. priority++;
  26751. result.optimizations.push(new TextureOptimization(priority, 256));
  26752. // Next priority
  26753. priority++;
  26754. result.optimizations.push(new RenderTargetsOptimization(priority));
  26755. // Next priority
  26756. priority++;
  26757. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  26758. return result;
  26759. };
  26760. return SceneOptimizerOptions;
  26761. })();
  26762. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  26763. // Scene optimizer tool
  26764. var SceneOptimizer = (function () {
  26765. function SceneOptimizer() {
  26766. }
  26767. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  26768. // TODO: add an epsilon
  26769. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  26770. if (onSuccess) {
  26771. onSuccess();
  26772. }
  26773. return;
  26774. }
  26775. // Apply current level of optimizations
  26776. var allDone = true;
  26777. var noOptimizationApplied = true;
  26778. for (var index = 0; index < options.optimizations.length; index++) {
  26779. var optimization = options.optimizations[index];
  26780. if (optimization.priority === currentPriorityLevel) {
  26781. noOptimizationApplied = false;
  26782. allDone = allDone && optimization.apply(scene);
  26783. }
  26784. }
  26785. // If no optimization was applied, this is a failure :(
  26786. if (noOptimizationApplied) {
  26787. if (onFailure) {
  26788. onFailure();
  26789. }
  26790. return;
  26791. }
  26792. // If all optimizations were done, move to next level
  26793. if (allDone) {
  26794. currentPriorityLevel++;
  26795. }
  26796. // Let's the system running for a specific amount of time before checking FPS
  26797. scene.executeWhenReady(function () {
  26798. setTimeout(function () {
  26799. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  26800. }, options.trackerDuration);
  26801. });
  26802. };
  26803. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  26804. if (!options) {
  26805. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  26806. }
  26807. // Let's the system running for a specific amount of time before checking FPS
  26808. scene.executeWhenReady(function () {
  26809. setTimeout(function () {
  26810. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  26811. }, options.trackerDuration);
  26812. });
  26813. };
  26814. return SceneOptimizer;
  26815. })();
  26816. BABYLON.SceneOptimizer = SceneOptimizer;
  26817. })(BABYLON || (BABYLON = {}));
  26818. //# sourceMappingURL=babylon.sceneOptimizer.js.mapvar BABYLON;
  26819. (function (BABYLON) {
  26820. var Internals;
  26821. (function (Internals) {
  26822. var MeshLODLevel = (function () {
  26823. function MeshLODLevel(distance, mesh) {
  26824. this.distance = distance;
  26825. this.mesh = mesh;
  26826. }
  26827. return MeshLODLevel;
  26828. })();
  26829. Internals.MeshLODLevel = MeshLODLevel;
  26830. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  26831. })(BABYLON || (BABYLON = {}));
  26832. //# sourceMappingURL=babylon.meshLODLevel.js.mapvar BABYLON;
  26833. (function (BABYLON) {
  26834. var AudioEngine = (function () {
  26835. function AudioEngine() {
  26836. this.audioContext = null;
  26837. this.canUseWebAudio = false;
  26838. this.WarnedWebAudioUnsupported = false;
  26839. try {
  26840. if (typeof AudioContext !== 'undefined') {
  26841. this.audioContext = new AudioContext();
  26842. this.canUseWebAudio = true;
  26843. }
  26844. else if (typeof webkitAudioContext !== 'undefined') {
  26845. this.audioContext = new webkitAudioContext();
  26846. this.canUseWebAudio = true;
  26847. }
  26848. }
  26849. catch (e) {
  26850. this.canUseWebAudio = false;
  26851. BABYLON.Tools.Error("Web Audio: " + e.message);
  26852. }
  26853. // create a global volume gain node
  26854. if (this.canUseWebAudio) {
  26855. this.masterGain = this.audioContext.createGain();
  26856. this.masterGain.gain.value = 1;
  26857. this.masterGain.connect(this.audioContext.destination);
  26858. }
  26859. }
  26860. AudioEngine.prototype.dispose = function () {
  26861. if (this.canUseWebAudio) {
  26862. if (this._connectedAnalyser) {
  26863. this._connectedAnalyser.stopDebugCanvas();
  26864. this._connectedAnalyser.dispose();
  26865. this.masterGain.disconnect();
  26866. this.masterGain.connect(this.audioContext.destination);
  26867. this._connectedAnalyser = null;
  26868. }
  26869. this.masterGain.gain.value = 1;
  26870. }
  26871. this.WarnedWebAudioUnsupported = false;
  26872. };
  26873. AudioEngine.prototype.getGlobalVolume = function () {
  26874. if (this.canUseWebAudio) {
  26875. return this.masterGain.gain.value;
  26876. }
  26877. else {
  26878. return -1;
  26879. }
  26880. };
  26881. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  26882. if (this.canUseWebAudio) {
  26883. this.masterGain.gain.value = newVolume;
  26884. }
  26885. };
  26886. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  26887. if (this._connectedAnalyser) {
  26888. this._connectedAnalyser.stopDebugCanvas();
  26889. }
  26890. this._connectedAnalyser = analyser;
  26891. if (this.canUseWebAudio) {
  26892. this.masterGain.disconnect();
  26893. this._connectedAnalyser.connectAudioNodes(this.masterGain, this.audioContext.destination);
  26894. }
  26895. };
  26896. return AudioEngine;
  26897. })();
  26898. BABYLON.AudioEngine = AudioEngine;
  26899. })(BABYLON || (BABYLON = {}));
  26900. //# sourceMappingURL=babylon.audioEngine.js.mapvar BABYLON;
  26901. (function (BABYLON) {
  26902. var Sound = (function () {
  26903. /**
  26904. * Create a sound and attach it to a scene
  26905. * @param name Name of your sound
  26906. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  26907. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  26908. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel
  26909. */
  26910. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  26911. var _this = this;
  26912. this.autoplay = false;
  26913. this.loop = false;
  26914. this.useCustomAttenuation = false;
  26915. this.spatialSound = false;
  26916. this.refDistance = 1;
  26917. this.rolloffFactor = 1;
  26918. this.maxDistance = 100;
  26919. this.distanceModel = "linear";
  26920. this._panningModel = "equalpower";
  26921. this._playbackRate = 1;
  26922. this._startTime = 0;
  26923. this._startOffset = 0;
  26924. this._position = BABYLON.Vector3.Zero();
  26925. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  26926. this._volume = 1;
  26927. this._isLoaded = false;
  26928. this._isReadyToPlay = false;
  26929. this.isPlaying = false;
  26930. this.isPaused = false;
  26931. this._isDirectional = false;
  26932. // Used if you'd like to create a directional sound.
  26933. // If not set, the sound will be omnidirectional
  26934. this._coneInnerAngle = 360;
  26935. this._coneOuterAngle = 360;
  26936. this._coneOuterGain = 0;
  26937. this.name = name;
  26938. this._scene = scene;
  26939. this._readyToPlayCallback = readyToPlayCallback;
  26940. // Default custom attenuation function is a linear attenuation
  26941. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  26942. if (currentDistance < maxDistance) {
  26943. return currentVolume * (1 - currentDistance / maxDistance);
  26944. }
  26945. else {
  26946. return 0;
  26947. }
  26948. };
  26949. if (options) {
  26950. this.autoplay = options.autoplay || false;
  26951. this.loop = options.loop || false;
  26952. // if volume === 0, we need another way to check this option
  26953. if (options.volume !== undefined) {
  26954. this._volume = options.volume;
  26955. }
  26956. this.spatialSound = options.spatialSound || false;
  26957. this.maxDistance = options.maxDistance || 100;
  26958. this.useCustomAttenuation = options.useCustomAttenuation || false;
  26959. this.rolloffFactor = options.rolloffFactor || 1;
  26960. this.refDistance = options.refDistance || 1;
  26961. this.distanceModel = options.distanceModel || "linear";
  26962. this._playbackRate = options.playbackRate || 1;
  26963. }
  26964. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  26965. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  26966. this._soundGain.gain.value = this._volume;
  26967. this._inputAudioNode = this._soundGain;
  26968. this._ouputAudioNode = this._soundGain;
  26969. if (this.spatialSound) {
  26970. this._createSpatialParameters();
  26971. }
  26972. this._scene.mainSoundTrack.AddSound(this);
  26973. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  26974. if (urlOrArrayBuffer) {
  26975. // If it's an URL
  26976. if (typeof (urlOrArrayBuffer) === "string") {
  26977. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) {
  26978. _this._soundLoaded(data);
  26979. }, null, null, true);
  26980. }
  26981. else {
  26982. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  26983. this._soundLoaded(urlOrArrayBuffer);
  26984. }
  26985. else {
  26986. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  26987. }
  26988. }
  26989. }
  26990. }
  26991. else {
  26992. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  26993. this._scene.mainSoundTrack.AddSound(this);
  26994. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  26995. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  26996. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  26997. }
  26998. if (this._readyToPlayCallback) {
  26999. this._readyToPlayCallback();
  27000. }
  27001. }
  27002. }
  27003. Sound.prototype.dispose = function () {
  27004. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  27005. if (this.isPlaying) {
  27006. this.stop();
  27007. }
  27008. this._isReadyToPlay = false;
  27009. if (this.soundTrackId === -1) {
  27010. this._scene.mainSoundTrack.RemoveSound(this);
  27011. }
  27012. else {
  27013. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  27014. }
  27015. if (this._soundGain) {
  27016. this._soundGain.disconnect();
  27017. this._soundGain = null;
  27018. }
  27019. if (this._soundPanner) {
  27020. this._soundPanner.disconnect();
  27021. this._soundPanner = null;
  27022. }
  27023. if (this._soundSource) {
  27024. this._soundSource.disconnect();
  27025. this._soundSource = null;
  27026. }
  27027. this._audioBuffer = null;
  27028. if (this._connectedMesh) {
  27029. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  27030. this._connectedMesh = null;
  27031. }
  27032. }
  27033. };
  27034. Sound.prototype._soundLoaded = function (audioData) {
  27035. var _this = this;
  27036. this._isLoaded = true;
  27037. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  27038. _this._audioBuffer = buffer;
  27039. _this._isReadyToPlay = true;
  27040. if (_this.autoplay) {
  27041. _this.play();
  27042. }
  27043. if (_this._readyToPlayCallback) {
  27044. _this._readyToPlayCallback();
  27045. }
  27046. }, function (error) {
  27047. BABYLON.Tools.Error("Error while decoding audio data: " + error.err);
  27048. });
  27049. };
  27050. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  27051. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27052. this._audioBuffer = audioBuffer;
  27053. this._isReadyToPlay = true;
  27054. }
  27055. };
  27056. Sound.prototype.updateOptions = function (options) {
  27057. if (options) {
  27058. this.loop = options.loop || this.loop;
  27059. this.maxDistance = options.maxDistance || this.maxDistance;
  27060. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  27061. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  27062. this.refDistance = options.refDistance || this.refDistance;
  27063. this.distanceModel = options.distanceModel || this.distanceModel;
  27064. this._playbackRate = options.playbackRate || this._playbackRate;
  27065. }
  27066. };
  27067. Sound.prototype._createSpatialParameters = function () {
  27068. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27069. if (this._scene.headphone) {
  27070. this._panningModel = "HRTF";
  27071. }
  27072. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  27073. if (this.useCustomAttenuation) {
  27074. // Tricks to disable in a way embedded Web Audio attenuation
  27075. this._soundPanner.distanceModel = "linear";
  27076. this._soundPanner.maxDistance = Number.MAX_VALUE;
  27077. this._soundPanner.refDistance = 1;
  27078. this._soundPanner.rolloffFactor = 1;
  27079. this._soundPanner.panningModel = this._panningModel;
  27080. }
  27081. else {
  27082. this._soundPanner.distanceModel = this.distanceModel;
  27083. this._soundPanner.maxDistance = this.maxDistance;
  27084. this._soundPanner.refDistance = this.refDistance;
  27085. this._soundPanner.rolloffFactor = this.rolloffFactor;
  27086. this._soundPanner.panningModel = this._panningModel;
  27087. }
  27088. this._soundPanner.connect(this._ouputAudioNode);
  27089. this._inputAudioNode = this._soundPanner;
  27090. }
  27091. };
  27092. Sound.prototype.switchPanningModelToHRTF = function () {
  27093. this._panningModel = "HRTF";
  27094. this._switchPanningModel();
  27095. };
  27096. Sound.prototype.switchPanningModelToEqualPower = function () {
  27097. this._panningModel = "equalpower";
  27098. this._switchPanningModel();
  27099. };
  27100. Sound.prototype._switchPanningModel = function () {
  27101. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  27102. this._soundPanner.panningModel = this._panningModel;
  27103. }
  27104. };
  27105. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  27106. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27107. this._ouputAudioNode.disconnect();
  27108. this._ouputAudioNode.connect(soundTrackAudioNode);
  27109. }
  27110. };
  27111. /**
  27112. * Transform this sound into a directional source
  27113. * @param coneInnerAngle Size of the inner cone in degree
  27114. * @param coneOuterAngle Size of the outer cone in degree
  27115. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  27116. */
  27117. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  27118. if (coneOuterAngle < coneInnerAngle) {
  27119. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  27120. return;
  27121. }
  27122. this._coneInnerAngle = coneInnerAngle;
  27123. this._coneOuterAngle = coneOuterAngle;
  27124. this._coneOuterGain = coneOuterGain;
  27125. this._isDirectional = true;
  27126. if (this.isPlaying && this.loop) {
  27127. this.stop();
  27128. this.play();
  27129. }
  27130. };
  27131. Sound.prototype.setPosition = function (newPosition) {
  27132. this._position = newPosition;
  27133. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  27134. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  27135. }
  27136. };
  27137. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  27138. this._localDirection = newLocalDirection;
  27139. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  27140. this._updateDirection();
  27141. }
  27142. };
  27143. Sound.prototype._updateDirection = function () {
  27144. var mat = this._connectedMesh.getWorldMatrix();
  27145. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  27146. direction.normalize();
  27147. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  27148. };
  27149. Sound.prototype.updateDistanceFromListener = function () {
  27150. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  27151. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  27152. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  27153. }
  27154. };
  27155. Sound.prototype.setAttenuationFunction = function (callback) {
  27156. this._customAttenuationFunction = callback;
  27157. };
  27158. /**
  27159. * Play the sound
  27160. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  27161. */
  27162. Sound.prototype.play = function (time) {
  27163. var _this = this;
  27164. if (this._isReadyToPlay && this._scene.audioEnabled) {
  27165. try {
  27166. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  27167. if (!this._soundSource) {
  27168. if (this.spatialSound) {
  27169. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  27170. if (this._isDirectional) {
  27171. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  27172. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  27173. this._soundPanner.coneOuterGain = this._coneOuterGain;
  27174. if (this._connectedMesh) {
  27175. this._updateDirection();
  27176. }
  27177. else {
  27178. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  27179. }
  27180. }
  27181. }
  27182. }
  27183. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  27184. this._soundSource.buffer = this._audioBuffer;
  27185. this._soundSource.connect(this._inputAudioNode);
  27186. this._soundSource.loop = this.loop;
  27187. this._soundSource.playbackRate.value = this._playbackRate;
  27188. this._startTime = startTime;
  27189. this._soundSource.onended = function () {
  27190. _this._onended();
  27191. };
  27192. this._soundSource.start(this._startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : 0);
  27193. this.isPlaying = true;
  27194. this.isPaused = false;
  27195. }
  27196. catch (ex) {
  27197. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  27198. }
  27199. }
  27200. };
  27201. Sound.prototype._onended = function () {
  27202. this.isPlaying = false;
  27203. if (this.onended) {
  27204. this.onended();
  27205. }
  27206. };
  27207. /**
  27208. * Stop the sound
  27209. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  27210. */
  27211. Sound.prototype.stop = function (time) {
  27212. if (this.isPlaying) {
  27213. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  27214. this._soundSource.stop(stopTime);
  27215. this.isPlaying = false;
  27216. }
  27217. };
  27218. Sound.prototype.pause = function () {
  27219. if (this.isPlaying) {
  27220. this.stop(0);
  27221. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  27222. this.isPaused = true;
  27223. }
  27224. };
  27225. Sound.prototype.setVolume = function (newVolume, time) {
  27226. if (BABYLON.Engine.audioEngine.canUseWebAudio && !this.spatialSound) {
  27227. if (time) {
  27228. this._soundGain.gain.linearRampToValueAtTime(this._volume, BABYLON.Engine.audioEngine.audioContext.currentTime);
  27229. this._soundGain.gain.linearRampToValueAtTime(newVolume, time);
  27230. }
  27231. else {
  27232. this._soundGain.gain.value = newVolume;
  27233. }
  27234. }
  27235. this._volume = newVolume;
  27236. };
  27237. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  27238. this._playbackRate = newPlaybackRate;
  27239. if (this.isPlaying) {
  27240. this._soundSource.playbackRate.value = this._playbackRate;
  27241. }
  27242. };
  27243. Sound.prototype.getVolume = function () {
  27244. return this._volume;
  27245. };
  27246. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  27247. var _this = this;
  27248. this._connectedMesh = meshToConnectTo;
  27249. if (!this.spatialSound) {
  27250. this._createSpatialParameters();
  27251. this.spatialSound = true;
  27252. if (this.isPlaying && this.loop) {
  27253. this.stop();
  27254. this.play();
  27255. }
  27256. }
  27257. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  27258. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  27259. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  27260. };
  27261. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  27262. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  27263. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  27264. this._updateDirection();
  27265. }
  27266. };
  27267. return Sound;
  27268. })();
  27269. BABYLON.Sound = Sound;
  27270. })(BABYLON || (BABYLON = {}));
  27271. //# sourceMappingURL=babylon.sound.js.mapvar BABYLON;
  27272. (function (BABYLON) {
  27273. var SoundTrack = (function () {
  27274. function SoundTrack(scene, options) {
  27275. this.id = -1;
  27276. this._isMainTrack = false;
  27277. this._scene = scene;
  27278. this._audioEngine = BABYLON.Engine.audioEngine;
  27279. this.soundCollection = new Array();
  27280. if (this._audioEngine.canUseWebAudio) {
  27281. this._trackGain = this._audioEngine.audioContext.createGain();
  27282. this._trackGain.connect(this._audioEngine.masterGain);
  27283. if (options) {
  27284. if (options.volume) {
  27285. this._trackGain.gain.value = options.volume;
  27286. }
  27287. if (options.mainTrack) {
  27288. this._isMainTrack = options.mainTrack;
  27289. }
  27290. }
  27291. }
  27292. if (!this._isMainTrack) {
  27293. this._scene.soundTracks.push(this);
  27294. this.id = this._scene.soundTracks.length - 1;
  27295. }
  27296. }
  27297. SoundTrack.prototype.dispose = function () {
  27298. if (this._audioEngine.canUseWebAudio) {
  27299. if (this._connectedAnalyser) {
  27300. this._connectedAnalyser.stopDebugCanvas();
  27301. }
  27302. while (this.soundCollection.length) {
  27303. this.soundCollection[0].dispose();
  27304. }
  27305. this._trackGain.disconnect();
  27306. this._trackGain = null;
  27307. }
  27308. };
  27309. SoundTrack.prototype.AddSound = function (sound) {
  27310. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27311. sound.connectToSoundTrackAudioNode(this._trackGain);
  27312. }
  27313. if (sound.soundTrackId) {
  27314. if (sound.soundTrackId === -1) {
  27315. this._scene.mainSoundTrack.RemoveSound(sound);
  27316. }
  27317. else {
  27318. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  27319. }
  27320. }
  27321. this.soundCollection.push(sound);
  27322. sound.soundTrackId = this.id;
  27323. };
  27324. SoundTrack.prototype.RemoveSound = function (sound) {
  27325. var index = this.soundCollection.indexOf(sound);
  27326. if (index !== -1) {
  27327. this.soundCollection.splice(index, 1);
  27328. }
  27329. };
  27330. SoundTrack.prototype.setVolume = function (newVolume) {
  27331. if (this._audioEngine.canUseWebAudio) {
  27332. this._trackGain.gain.value = newVolume;
  27333. }
  27334. };
  27335. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  27336. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27337. for (var i = 0; i < this.soundCollection.length; i++) {
  27338. this.soundCollection[i].switchPanningModelToHRTF();
  27339. }
  27340. }
  27341. };
  27342. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  27343. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27344. for (var i = 0; i < this.soundCollection.length; i++) {
  27345. this.soundCollection[i].switchPanningModelToEqualPower();
  27346. }
  27347. }
  27348. };
  27349. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  27350. if (this._connectedAnalyser) {
  27351. this._connectedAnalyser.stopDebugCanvas();
  27352. }
  27353. this._connectedAnalyser = analyser;
  27354. if (this._audioEngine.canUseWebAudio) {
  27355. this._trackGain.disconnect();
  27356. this._connectedAnalyser.connectAudioNodes(this._trackGain, this._audioEngine.masterGain);
  27357. }
  27358. };
  27359. return SoundTrack;
  27360. })();
  27361. BABYLON.SoundTrack = SoundTrack;
  27362. })(BABYLON || (BABYLON = {}));
  27363. //# sourceMappingURL=babylon.soundtrack.js.mapvar BABYLON;
  27364. (function (BABYLON) {
  27365. var DebugLayer = (function () {
  27366. function DebugLayer(scene) {
  27367. var _this = this;
  27368. this._transformationMatrix = BABYLON.Matrix.Identity();
  27369. this._enabled = false;
  27370. this._labelsEnabled = false;
  27371. this._displayStatistics = true;
  27372. this._displayTree = false;
  27373. this._displayLogs = false;
  27374. this._identityMatrix = BABYLON.Matrix.Identity();
  27375. this.axisRatio = 0.02;
  27376. this.accentColor = "orange";
  27377. this._scene = scene;
  27378. this._syncPositions = function () {
  27379. var engine = _this._scene.getEngine();
  27380. var canvasRect = engine.getRenderingCanvasClientRect();
  27381. if (_this._showUI) {
  27382. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  27383. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  27384. _this._statsDiv.style.width = "400px";
  27385. _this._statsDiv.style.height = "auto";
  27386. _this._statsSubsetDiv.style.maxHeight = "240px";
  27387. _this._optionsDiv.style.left = "0px";
  27388. _this._optionsDiv.style.top = "10px";
  27389. _this._optionsDiv.style.width = "200px";
  27390. _this._optionsDiv.style.height = "auto";
  27391. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  27392. _this._logDiv.style.left = "0px";
  27393. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  27394. _this._logDiv.style.width = "600px";
  27395. _this._logDiv.style.height = "160px";
  27396. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  27397. _this._treeDiv.style.top = "10px";
  27398. _this._treeDiv.style.width = "300px";
  27399. _this._treeDiv.style.height = "auto";
  27400. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  27401. }
  27402. _this._globalDiv.style.left = canvasRect.left + "px";
  27403. _this._globalDiv.style.top = canvasRect.top + "px";
  27404. _this._drawingCanvas.style.left = "0px";
  27405. _this._drawingCanvas.style.top = "0px";
  27406. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  27407. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  27408. var devicePixelRatio = window.devicePixelRatio || 1;
  27409. var context = _this._drawingContext;
  27410. var backingStoreRatio = context.webkitBackingStorePixelRatio || context.mozBackingStorePixelRatio || context.msBackingStorePixelRatio || context.oBackingStorePixelRatio || context.backingStorePixelRatio || 1;
  27411. _this._ratio = devicePixelRatio / backingStoreRatio;
  27412. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  27413. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  27414. };
  27415. this._onCanvasClick = function (evt) {
  27416. _this._clickPosition = {
  27417. x: evt.clientX * _this._ratio,
  27418. y: evt.clientY * _this._ratio
  27419. };
  27420. };
  27421. this._syncUI = function () {
  27422. if (_this._showUI) {
  27423. if (_this._displayStatistics) {
  27424. _this._displayStats();
  27425. _this._statsDiv.style.display = "";
  27426. }
  27427. else {
  27428. _this._statsDiv.style.display = "none";
  27429. }
  27430. if (_this._displayLogs) {
  27431. _this._logDiv.style.display = "";
  27432. }
  27433. else {
  27434. _this._logDiv.style.display = "none";
  27435. }
  27436. if (_this._displayTree) {
  27437. _this._treeDiv.style.display = "";
  27438. if (_this._needToRefreshMeshesTree) {
  27439. _this._needToRefreshMeshesTree = false;
  27440. _this._refreshMeshesTreeContent();
  27441. }
  27442. }
  27443. else {
  27444. _this._treeDiv.style.display = "none";
  27445. }
  27446. }
  27447. };
  27448. this._syncData = function () {
  27449. if (_this._labelsEnabled || !_this._showUI) {
  27450. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  27451. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  27452. var engine = _this._scene.getEngine();
  27453. var viewport = _this._camera.viewport;
  27454. var globalViewport = viewport.toGlobal(engine);
  27455. // Meshes
  27456. var meshes = _this._camera.getActiveMeshes();
  27457. for (var index = 0; index < meshes.length; index++) {
  27458. var mesh = meshes.data[index];
  27459. var position = mesh.getBoundingInfo().boundingSphere.center;
  27460. var projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  27461. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  27462. _this._renderAxis(projectedPosition, mesh, globalViewport);
  27463. }
  27464. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  27465. _this._renderLabel(mesh.name, projectedPosition, 12, function () {
  27466. mesh.renderOverlay = !mesh.renderOverlay;
  27467. }, function () {
  27468. return mesh.renderOverlay ? 'red' : 'black';
  27469. });
  27470. }
  27471. }
  27472. // Cameras
  27473. var cameras = _this._scene.cameras;
  27474. for (index = 0; index < cameras.length; index++) {
  27475. var camera = cameras[index];
  27476. if (camera === _this._camera) {
  27477. continue;
  27478. }
  27479. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  27480. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  27481. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  27482. _this._camera.detachControl(engine.getRenderingCanvas());
  27483. _this._camera = camera;
  27484. _this._camera.attachControl(engine.getRenderingCanvas());
  27485. }, function () {
  27486. return "purple";
  27487. });
  27488. }
  27489. }
  27490. // Lights
  27491. var lights = _this._scene.lights;
  27492. for (index = 0; index < lights.length; index++) {
  27493. var light = lights[index];
  27494. if (light.position) {
  27495. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  27496. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  27497. _this._renderLabel(light.name, projectedPosition, -20, function () {
  27498. light.setEnabled(!light.isEnabled());
  27499. }, function () {
  27500. return light.isEnabled() ? "orange" : "gray";
  27501. });
  27502. }
  27503. }
  27504. }
  27505. }
  27506. _this._clickPosition = undefined;
  27507. };
  27508. }
  27509. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  27510. while (this._treeSubsetDiv.hasChildNodes()) {
  27511. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  27512. }
  27513. // Add meshes
  27514. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  27515. sortedArray.sort(function (a, b) {
  27516. if (a.name === b.name) {
  27517. return 0;
  27518. }
  27519. return (a.name > b.name) ? 1 : -1;
  27520. });
  27521. for (var index = 0; index < sortedArray.length; index++) {
  27522. var mesh = sortedArray[index];
  27523. if (!mesh.isEnabled()) {
  27524. continue;
  27525. }
  27526. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  27527. m.isVisible = element.checked;
  27528. }, mesh);
  27529. }
  27530. };
  27531. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  27532. this._drawingContext.beginPath();
  27533. this._drawingContext.moveTo(zero.x, zero.y);
  27534. this._drawingContext.lineTo(unit.x, unit.y);
  27535. this._drawingContext.strokeStyle = color;
  27536. this._drawingContext.lineWidth = 4;
  27537. this._drawingContext.stroke();
  27538. this._drawingContext.font = "normal 14px Segoe UI";
  27539. this._drawingContext.fillStyle = color;
  27540. this._drawingContext.fillText(label, unitText.x, unitText.y);
  27541. };
  27542. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  27543. var position = mesh.getBoundingInfo().boundingSphere.center;
  27544. var worldMatrix = mesh.getWorldMatrix();
  27545. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  27546. var unit = (unprojectedVector.subtract(position)).length();
  27547. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  27548. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  27549. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  27550. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  27551. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  27552. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  27553. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  27554. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  27555. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  27556. };
  27557. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  27558. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  27559. this._drawingContext.font = "normal 12px Segoe UI";
  27560. var textMetrics = this._drawingContext.measureText(text);
  27561. var centerX = projectedPosition.x - textMetrics.width / 2;
  27562. var centerY = projectedPosition.y;
  27563. var clientRect = this._drawingCanvas.getBoundingClientRect();
  27564. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  27565. onClick();
  27566. }
  27567. this._drawingContext.beginPath();
  27568. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  27569. this._drawingContext.fillStyle = getFillStyle();
  27570. this._drawingContext.globalAlpha = 0.5;
  27571. this._drawingContext.fill();
  27572. this._drawingContext.globalAlpha = 1.0;
  27573. this._drawingContext.strokeStyle = '#FFFFFF';
  27574. this._drawingContext.lineWidth = 1;
  27575. this._drawingContext.stroke();
  27576. this._drawingContext.fillStyle = "#FFFFFF";
  27577. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  27578. this._drawingContext.beginPath();
  27579. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  27580. this._drawingContext.fill();
  27581. }
  27582. };
  27583. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  27584. if (!this._clickPosition) {
  27585. return false;
  27586. }
  27587. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  27588. return false;
  27589. }
  27590. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  27591. return false;
  27592. }
  27593. return true;
  27594. };
  27595. DebugLayer.prototype.isVisible = function () {
  27596. return this._enabled;
  27597. };
  27598. DebugLayer.prototype.hide = function () {
  27599. if (!this._enabled) {
  27600. return;
  27601. }
  27602. this._enabled = false;
  27603. var engine = this._scene.getEngine();
  27604. this._scene.unregisterBeforeRender(this._syncData);
  27605. this._scene.unregisterAfterRender(this._syncUI);
  27606. document.body.removeChild(this._globalDiv);
  27607. window.removeEventListener("resize", this._syncPositions);
  27608. this._scene.forceShowBoundingBoxes = false;
  27609. this._scene.forceWireframe = false;
  27610. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  27611. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  27612. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  27613. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  27614. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  27615. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  27616. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  27617. this._scene.shadowsEnabled = true;
  27618. this._scene.particlesEnabled = true;
  27619. this._scene.postProcessesEnabled = true;
  27620. this._scene.collisionsEnabled = true;
  27621. this._scene.lightsEnabled = true;
  27622. this._scene.texturesEnabled = true;
  27623. this._scene.lensFlaresEnabled = true;
  27624. this._scene.proceduralTexturesEnabled = true;
  27625. this._scene.renderTargetsEnabled = true;
  27626. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  27627. };
  27628. DebugLayer.prototype.show = function (showUI, camera) {
  27629. if (showUI === void 0) { showUI = true; }
  27630. if (camera === void 0) { camera = null; }
  27631. if (this._enabled) {
  27632. return;
  27633. }
  27634. if (camera) {
  27635. this._camera = camera;
  27636. }
  27637. else {
  27638. this._camera = this._scene.activeCamera;
  27639. }
  27640. this._enabled = true;
  27641. this._showUI = showUI;
  27642. var engine = this._scene.getEngine();
  27643. this._globalDiv = document.createElement("div");
  27644. document.body.appendChild(this._globalDiv);
  27645. this._generateDOMelements();
  27646. window.addEventListener("resize", this._syncPositions);
  27647. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  27648. this._syncPositions();
  27649. this._scene.registerBeforeRender(this._syncData);
  27650. this._scene.registerAfterRender(this._syncUI);
  27651. };
  27652. DebugLayer.prototype._clearLabels = function () {
  27653. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  27654. for (var index = 0; index < this._scene.meshes.length; index++) {
  27655. var mesh = this._scene.meshes[index];
  27656. mesh.renderOverlay = false;
  27657. }
  27658. };
  27659. DebugLayer.prototype._generateheader = function (root, text) {
  27660. var header = document.createElement("div");
  27661. header.innerHTML = text + "&nbsp;";
  27662. header.style.textAlign = "right";
  27663. header.style.width = "100%";
  27664. header.style.color = "white";
  27665. header.style.backgroundColor = "Black";
  27666. header.style.padding = "5px 5px 4px 0px";
  27667. header.style.marginLeft = "-5px";
  27668. header.style.fontWeight = "bold";
  27669. root.appendChild(header);
  27670. };
  27671. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  27672. var label = document.createElement("label");
  27673. label.innerHTML = title;
  27674. label.style.color = color;
  27675. root.appendChild(label);
  27676. root.appendChild(document.createElement("br"));
  27677. };
  27678. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  27679. if (tag === void 0) { tag = null; }
  27680. var label = document.createElement("label");
  27681. var boundingBoxesCheckbox = document.createElement("input");
  27682. boundingBoxesCheckbox.type = "checkbox";
  27683. boundingBoxesCheckbox.checked = initialState;
  27684. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  27685. task(evt.target, tag);
  27686. });
  27687. label.appendChild(boundingBoxesCheckbox);
  27688. var container = document.createElement("span");
  27689. var leftPart = document.createElement("span");
  27690. var rightPart = document.createElement("span");
  27691. rightPart.style.cssFloat = "right";
  27692. leftPart.innerHTML = leftTitle;
  27693. rightPart.innerHTML = rightTitle;
  27694. rightPart.style.fontSize = "12px";
  27695. rightPart.style.maxWidth = "200px";
  27696. container.appendChild(leftPart);
  27697. container.appendChild(rightPart);
  27698. label.appendChild(container);
  27699. root.appendChild(label);
  27700. root.appendChild(document.createElement("br"));
  27701. };
  27702. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  27703. if (tag === void 0) { tag = null; }
  27704. var label = document.createElement("label");
  27705. var checkBox = document.createElement("input");
  27706. checkBox.type = "checkbox";
  27707. checkBox.checked = initialState;
  27708. checkBox.addEventListener("change", function (evt) {
  27709. task(evt.target, tag);
  27710. });
  27711. label.appendChild(checkBox);
  27712. label.appendChild(document.createTextNode(title));
  27713. root.appendChild(label);
  27714. root.appendChild(document.createElement("br"));
  27715. };
  27716. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  27717. if (tag === void 0) { tag = null; }
  27718. var button = document.createElement("button");
  27719. button.innerHTML = title;
  27720. button.style.height = "24px";
  27721. button.style.color = "#444444";
  27722. button.style.border = "1px solid white";
  27723. button.className = "debugLayerButton";
  27724. button.addEventListener("click", function (evt) {
  27725. task(evt.target, tag);
  27726. });
  27727. root.appendChild(button);
  27728. root.appendChild(document.createElement("br"));
  27729. };
  27730. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  27731. if (tag === void 0) { tag = null; }
  27732. var label = document.createElement("label");
  27733. var boundingBoxesRadio = document.createElement("input");
  27734. boundingBoxesRadio.type = "radio";
  27735. boundingBoxesRadio.name = name;
  27736. boundingBoxesRadio.checked = initialState;
  27737. boundingBoxesRadio.addEventListener("change", function (evt) {
  27738. task(evt.target, tag);
  27739. });
  27740. label.appendChild(boundingBoxesRadio);
  27741. label.appendChild(document.createTextNode(title));
  27742. root.appendChild(label);
  27743. root.appendChild(document.createElement("br"));
  27744. };
  27745. DebugLayer.prototype._generateDOMelements = function () {
  27746. var _this = this;
  27747. this._globalDiv.id = "DebugLayer";
  27748. this._globalDiv.style.position = "absolute";
  27749. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  27750. this._globalDiv.style.fontSize = "14px";
  27751. this._globalDiv.style.color = "white";
  27752. // Drawing canvas
  27753. this._drawingCanvas = document.createElement("canvas");
  27754. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  27755. this._drawingCanvas.style.position = "absolute";
  27756. this._drawingCanvas.style.pointerEvents = "none";
  27757. this._drawingContext = this._drawingCanvas.getContext("2d");
  27758. this._globalDiv.appendChild(this._drawingCanvas);
  27759. if (this._showUI) {
  27760. var background = "rgba(128, 128, 128, 0.4)";
  27761. var border = "rgb(180, 180, 180) solid 1px";
  27762. // Stats
  27763. this._statsDiv = document.createElement("div");
  27764. this._statsDiv.id = "DebugLayerStats";
  27765. this._statsDiv.style.border = border;
  27766. this._statsDiv.style.position = "absolute";
  27767. this._statsDiv.style.background = background;
  27768. this._statsDiv.style.padding = "0px 0px 0px 5px";
  27769. this._generateheader(this._statsDiv, "STATISTICS");
  27770. this._statsSubsetDiv = document.createElement("div");
  27771. this._statsSubsetDiv.style.paddingTop = "5px";
  27772. this._statsSubsetDiv.style.paddingBottom = "5px";
  27773. this._statsSubsetDiv.style.overflowY = "auto";
  27774. this._statsDiv.appendChild(this._statsSubsetDiv);
  27775. // Tree
  27776. this._treeDiv = document.createElement("div");
  27777. this._treeDiv.id = "DebugLayerTree";
  27778. this._treeDiv.style.border = border;
  27779. this._treeDiv.style.position = "absolute";
  27780. this._treeDiv.style.background = background;
  27781. this._treeDiv.style.padding = "0px 0px 0px 5px";
  27782. this._treeDiv.style.display = "none";
  27783. this._generateheader(this._treeDiv, "MESHES TREE");
  27784. this._treeSubsetDiv = document.createElement("div");
  27785. this._treeSubsetDiv.style.paddingTop = "5px";
  27786. this._treeSubsetDiv.style.paddingRight = "5px";
  27787. this._treeSubsetDiv.style.overflowY = "auto";
  27788. this._treeSubsetDiv.style.maxHeight = "300px";
  27789. this._treeDiv.appendChild(this._treeSubsetDiv);
  27790. this._needToRefreshMeshesTree = true;
  27791. // Logs
  27792. this._logDiv = document.createElement("div");
  27793. this._logDiv.style.border = border;
  27794. this._logDiv.id = "DebugLayerLogs";
  27795. this._logDiv.style.position = "absolute";
  27796. this._logDiv.style.background = background;
  27797. this._logDiv.style.padding = "0px 0px 0px 5px";
  27798. this._logDiv.style.display = "none";
  27799. this._generateheader(this._logDiv, "LOGS");
  27800. this._logSubsetDiv = document.createElement("div");
  27801. this._logSubsetDiv.style.height = "127px";
  27802. this._logSubsetDiv.style.paddingTop = "5px";
  27803. this._logSubsetDiv.style.overflowY = "auto";
  27804. this._logSubsetDiv.style.fontSize = "12px";
  27805. this._logSubsetDiv.style.fontFamily = "consolas";
  27806. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  27807. this._logDiv.appendChild(this._logSubsetDiv);
  27808. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  27809. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  27810. };
  27811. // Options
  27812. this._optionsDiv = document.createElement("div");
  27813. this._optionsDiv.id = "DebugLayerOptions";
  27814. this._optionsDiv.style.border = border;
  27815. this._optionsDiv.style.position = "absolute";
  27816. this._optionsDiv.style.background = background;
  27817. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  27818. this._optionsDiv.style.overflowY = "auto";
  27819. this._generateheader(this._optionsDiv, "OPTIONS");
  27820. this._optionsSubsetDiv = document.createElement("div");
  27821. this._optionsSubsetDiv.style.paddingTop = "5px";
  27822. this._optionsSubsetDiv.style.paddingBottom = "5px";
  27823. this._optionsSubsetDiv.style.overflowY = "auto";
  27824. this._optionsSubsetDiv.style.maxHeight = "200px";
  27825. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  27826. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  27827. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) {
  27828. _this._displayStatistics = element.checked;
  27829. });
  27830. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) {
  27831. _this._displayLogs = element.checked;
  27832. });
  27833. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  27834. _this._displayTree = element.checked;
  27835. _this._needToRefreshMeshesTree = true;
  27836. });
  27837. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27838. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  27839. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) {
  27840. _this._scene.forceShowBoundingBoxes = element.checked;
  27841. });
  27842. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  27843. _this._labelsEnabled = element.checked;
  27844. if (!_this._labelsEnabled) {
  27845. _this._clearLabels();
  27846. }
  27847. });
  27848. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  27849. if (element.checked) {
  27850. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  27851. }
  27852. else {
  27853. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  27854. }
  27855. });
  27856. ;
  27857. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27858. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  27859. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  27860. if (element.checked) {
  27861. _this._scene.forceWireframe = false;
  27862. _this._scene.forcePointsCloud = false;
  27863. }
  27864. });
  27865. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  27866. if (element.checked) {
  27867. _this._scene.forceWireframe = true;
  27868. _this._scene.forcePointsCloud = false;
  27869. }
  27870. });
  27871. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  27872. if (element.checked) {
  27873. _this._scene.forceWireframe = false;
  27874. _this._scene.forcePointsCloud = true;
  27875. }
  27876. });
  27877. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27878. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  27879. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) {
  27880. BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked;
  27881. });
  27882. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) {
  27883. BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked;
  27884. });
  27885. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) {
  27886. BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked;
  27887. });
  27888. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) {
  27889. BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked;
  27890. });
  27891. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) {
  27892. BABYLON.StandardMaterial.BumpTextureEnabled = element.checked;
  27893. });
  27894. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) {
  27895. BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked;
  27896. });
  27897. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) {
  27898. BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked;
  27899. });
  27900. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) {
  27901. BABYLON.StandardMaterial.FresnelEnabled = element.checked;
  27902. });
  27903. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27904. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  27905. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) {
  27906. _this._scene.animationsEnabled = element.checked;
  27907. });
  27908. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) {
  27909. _this._scene.collisionsEnabled = element.checked;
  27910. });
  27911. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) {
  27912. _this._scene.fogEnabled = element.checked;
  27913. });
  27914. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) {
  27915. _this._scene.lensFlaresEnabled = element.checked;
  27916. });
  27917. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) {
  27918. _this._scene.lightsEnabled = element.checked;
  27919. });
  27920. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) {
  27921. _this._scene.particlesEnabled = element.checked;
  27922. });
  27923. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) {
  27924. _this._scene.postProcessesEnabled = element.checked;
  27925. });
  27926. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) {
  27927. _this._scene.proceduralTexturesEnabled = element.checked;
  27928. });
  27929. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) {
  27930. _this._scene.renderTargetsEnabled = element.checked;
  27931. });
  27932. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) {
  27933. _this._scene.shadowsEnabled = element.checked;
  27934. });
  27935. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) {
  27936. _this._scene.skeletonsEnabled = element.checked;
  27937. });
  27938. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) {
  27939. _this._scene.spritesEnabled = element.checked;
  27940. });
  27941. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) {
  27942. _this._scene.texturesEnabled = element.checked;
  27943. });
  27944. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27945. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27946. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  27947. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  27948. if (element.checked) {
  27949. _this._scene.headphone = true;
  27950. }
  27951. });
  27952. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  27953. if (element.checked) {
  27954. _this._scene.headphone = false;
  27955. }
  27956. });
  27957. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  27958. _this._scene.audioEnabled = !element.checked;
  27959. });
  27960. }
  27961. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27962. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  27963. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) {
  27964. _this._scene.dumpNextRenderTargets = true;
  27965. });
  27966. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27967. this._globalDiv.appendChild(this._statsDiv);
  27968. this._globalDiv.appendChild(this._logDiv);
  27969. this._globalDiv.appendChild(this._optionsDiv);
  27970. this._globalDiv.appendChild(this._treeDiv);
  27971. }
  27972. };
  27973. DebugLayer.prototype._displayStats = function () {
  27974. var scene = this._scene;
  27975. var engine = scene.getEngine();
  27976. var glInfo = engine.getGlInfo();
  27977. 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>";
  27978. if (this.customStatsFunction) {
  27979. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  27980. }
  27981. };
  27982. return DebugLayer;
  27983. })();
  27984. BABYLON.DebugLayer = DebugLayer;
  27985. })(BABYLON || (BABYLON = {}));
  27986. //# sourceMappingURL=babylon.debugLayer.js.map
  27987. var BABYLON;
  27988. (function (BABYLON) {
  27989. var RawTexture = (function (_super) {
  27990. __extends(RawTexture, _super);
  27991. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  27992. if (generateMipMaps === void 0) { generateMipMaps = true; }
  27993. if (invertY === void 0) { invertY = false; }
  27994. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  27995. _super.call(this, null, scene, !generateMipMaps, invertY);
  27996. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  27997. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  27998. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  27999. }
  28000. // Statics
  28001. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  28002. if (generateMipMaps === void 0) { generateMipMaps = true; }
  28003. if (invertY === void 0) { invertY = false; }
  28004. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28005. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  28006. };
  28007. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  28008. if (generateMipMaps === void 0) { generateMipMaps = true; }
  28009. if (invertY === void 0) { invertY = false; }
  28010. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28011. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  28012. };
  28013. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  28014. if (generateMipMaps === void 0) { generateMipMaps = true; }
  28015. if (invertY === void 0) { invertY = false; }
  28016. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28017. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  28018. };
  28019. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  28020. if (generateMipMaps === void 0) { generateMipMaps = true; }
  28021. if (invertY === void 0) { invertY = false; }
  28022. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28023. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  28024. };
  28025. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  28026. if (generateMipMaps === void 0) { generateMipMaps = true; }
  28027. if (invertY === void 0) { invertY = false; }
  28028. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28029. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  28030. };
  28031. return RawTexture;
  28032. })(BABYLON.Texture);
  28033. BABYLON.RawTexture = RawTexture;
  28034. })(BABYLON || (BABYLON = {}));
  28035. //# sourceMappingURL=babylon.rawTexture.js.map
  28036. var BABYLON;
  28037. (function (BABYLON) {
  28038. var IndexedVector2 = (function (_super) {
  28039. __extends(IndexedVector2, _super);
  28040. function IndexedVector2(original, index) {
  28041. _super.call(this, original.x, original.y);
  28042. this.index = index;
  28043. }
  28044. return IndexedVector2;
  28045. })(BABYLON.Vector2);
  28046. var PolygonPoints = (function () {
  28047. function PolygonPoints() {
  28048. this.elements = new Array();
  28049. }
  28050. PolygonPoints.prototype.add = function (originalPoints) {
  28051. var _this = this;
  28052. var result = new Array();
  28053. originalPoints.forEach(function (point) {
  28054. if (result.length === 0 || !(BABYLON.Tools.WithinEpsilon(point.x, result[0].x, 0.00001) && BABYLON.Tools.WithinEpsilon(point.y, result[0].y, 0.00001))) {
  28055. var newPoint = new IndexedVector2(point, _this.elements.length);
  28056. result.push(newPoint);
  28057. _this.elements.push(newPoint);
  28058. }
  28059. });
  28060. return result;
  28061. };
  28062. PolygonPoints.prototype.computeBounds = function () {
  28063. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  28064. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  28065. this.elements.forEach(function (point) {
  28066. // x
  28067. if (point.x < lmin.x) {
  28068. lmin.x = point.x;
  28069. }
  28070. else if (point.x > lmax.x) {
  28071. lmax.x = point.x;
  28072. }
  28073. // y
  28074. if (point.y < lmin.y) {
  28075. lmin.y = point.y;
  28076. }
  28077. else if (point.y > lmax.y) {
  28078. lmax.y = point.y;
  28079. }
  28080. });
  28081. return {
  28082. min: lmin,
  28083. max: lmax,
  28084. width: lmax.x - lmin.x,
  28085. height: lmax.y - lmin.y
  28086. };
  28087. };
  28088. return PolygonPoints;
  28089. })();
  28090. var Polygon = (function () {
  28091. function Polygon() {
  28092. }
  28093. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  28094. return [
  28095. new BABYLON.Vector2(xmin, ymin),
  28096. new BABYLON.Vector2(xmax, ymin),
  28097. new BABYLON.Vector2(xmax, ymax),
  28098. new BABYLON.Vector2(xmin, ymax)
  28099. ];
  28100. };
  28101. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  28102. if (cx === void 0) { cx = 0; }
  28103. if (cy === void 0) { cy = 0; }
  28104. if (numberOfSides === void 0) { numberOfSides = 32; }
  28105. var result = new Array();
  28106. var angle = 0;
  28107. var increment = (Math.PI * 2) / numberOfSides;
  28108. for (var i = 0; i < numberOfSides; i++) {
  28109. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  28110. angle -= increment;
  28111. }
  28112. return result;
  28113. };
  28114. Polygon.Parse = function (input) {
  28115. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  28116. var i, result = [];
  28117. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  28118. result.push(new poly2tri.Point(floats[i], floats[i + 1]));
  28119. }
  28120. return result;
  28121. };
  28122. Polygon.StartingAt = function (x, y) {
  28123. return BABYLON.Path2.StartingAt(x, y);
  28124. };
  28125. return Polygon;
  28126. })();
  28127. BABYLON.Polygon = Polygon;
  28128. var PolygonMeshBuilder = (function () {
  28129. function PolygonMeshBuilder(name, contours, scene) {
  28130. this._points = new PolygonPoints();
  28131. if (!("poly2tri" in window)) {
  28132. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  28133. }
  28134. this._name = name;
  28135. this._scene = scene;
  28136. var points;
  28137. if (contours instanceof BABYLON.Path2) {
  28138. points = contours.getPoints();
  28139. }
  28140. else {
  28141. points = contours;
  28142. }
  28143. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  28144. }
  28145. PolygonMeshBuilder.prototype.addHole = function (hole) {
  28146. this._swctx.addHole(this._points.add(hole));
  28147. return this;
  28148. };
  28149. PolygonMeshBuilder.prototype.build = function (updatable) {
  28150. if (updatable === void 0) { updatable = false; }
  28151. var result = new BABYLON.Mesh(this._name, this._scene);
  28152. var normals = [];
  28153. var positions = [];
  28154. var uvs = [];
  28155. var bounds = this._points.computeBounds();
  28156. this._points.elements.forEach(function (p) {
  28157. normals.push(0, 1.0, 0);
  28158. positions.push(p.x, 0, p.y);
  28159. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  28160. });
  28161. var indices = [];
  28162. this._swctx.triangulate();
  28163. this._swctx.getTriangles().forEach(function (triangle) {
  28164. triangle.getPoints().forEach(function (point) {
  28165. indices.push(point.index);
  28166. });
  28167. });
  28168. result.setVerticesData(positions, BABYLON.VertexBuffer.PositionKind, updatable);
  28169. result.setVerticesData(normals, BABYLON.VertexBuffer.NormalKind, updatable);
  28170. result.setVerticesData(uvs, BABYLON.VertexBuffer.UVKind, updatable);
  28171. result.setIndices(indices);
  28172. return result;
  28173. };
  28174. return PolygonMeshBuilder;
  28175. })();
  28176. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  28177. })(BABYLON || (BABYLON = {}));
  28178. //# sourceMappingURL=babylon.polygonMesh.js.mapvar BABYLON;
  28179. (function (BABYLON) {
  28180. var SimplificationSettings = (function () {
  28181. function SimplificationSettings(quality, distance, optimizeMesh) {
  28182. this.quality = quality;
  28183. this.distance = distance;
  28184. this.optimizeMesh = optimizeMesh;
  28185. }
  28186. return SimplificationSettings;
  28187. })();
  28188. BABYLON.SimplificationSettings = SimplificationSettings;
  28189. var SimplificationQueue = (function () {
  28190. function SimplificationQueue() {
  28191. this.running = false;
  28192. this._simplificationArray = [];
  28193. }
  28194. SimplificationQueue.prototype.addTask = function (task) {
  28195. this._simplificationArray.push(task);
  28196. };
  28197. SimplificationQueue.prototype.executeNext = function () {
  28198. var task = this._simplificationArray.pop();
  28199. if (task) {
  28200. this.running = true;
  28201. this.runSimplification(task);
  28202. }
  28203. else {
  28204. this.running = false;
  28205. }
  28206. };
  28207. SimplificationQueue.prototype.runSimplification = function (task) {
  28208. var _this = this;
  28209. if (task.parallelProcessing) {
  28210. //parallel simplifier
  28211. task.settings.forEach(function (setting) {
  28212. var simplifier = _this.getSimplifier(task);
  28213. simplifier.simplify(setting, function (newMesh) {
  28214. task.mesh.addLODLevel(setting.distance, newMesh);
  28215. newMesh.isVisible = true;
  28216. //check if it is the last
  28217. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  28218. //all done, run the success callback.
  28219. task.successCallback();
  28220. }
  28221. _this.executeNext();
  28222. });
  28223. });
  28224. }
  28225. else {
  28226. //single simplifier.
  28227. var simplifier = this.getSimplifier(task);
  28228. var runDecimation = function (setting, callback) {
  28229. simplifier.simplify(setting, function (newMesh) {
  28230. task.mesh.addLODLevel(setting.distance, newMesh);
  28231. newMesh.isVisible = true;
  28232. //run the next quality level
  28233. callback();
  28234. });
  28235. };
  28236. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  28237. runDecimation(task.settings[loop.index], function () {
  28238. loop.executeNext();
  28239. });
  28240. }, function () {
  28241. //execution ended, run the success callback.
  28242. if (task.successCallback) {
  28243. task.successCallback();
  28244. }
  28245. _this.executeNext();
  28246. });
  28247. }
  28248. };
  28249. SimplificationQueue.prototype.getSimplifier = function (task) {
  28250. switch (task.simplificationType) {
  28251. case 0 /* QUADRATIC */:
  28252. default:
  28253. return new QuadraticErrorSimplification(task.mesh);
  28254. }
  28255. };
  28256. return SimplificationQueue;
  28257. })();
  28258. BABYLON.SimplificationQueue = SimplificationQueue;
  28259. /**
  28260. * The implemented types of simplification.
  28261. * At the moment only Quadratic Error Decimation is implemented.
  28262. */
  28263. (function (SimplificationType) {
  28264. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  28265. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  28266. var SimplificationType = BABYLON.SimplificationType;
  28267. var DecimationTriangle = (function () {
  28268. function DecimationTriangle(vertices) {
  28269. this.vertices = vertices;
  28270. this.error = new Array(4);
  28271. this.deleted = false;
  28272. this.isDirty = false;
  28273. this.deletePending = false;
  28274. this.borderFactor = 0;
  28275. }
  28276. return DecimationTriangle;
  28277. })();
  28278. BABYLON.DecimationTriangle = DecimationTriangle;
  28279. var DecimationVertex = (function () {
  28280. function DecimationVertex(position, id) {
  28281. this.position = position;
  28282. this.id = id;
  28283. this.isBorder = true;
  28284. this.q = new QuadraticMatrix();
  28285. this.triangleCount = 0;
  28286. this.triangleStart = 0;
  28287. this.originalOffsets = [];
  28288. }
  28289. DecimationVertex.prototype.updatePosition = function (newPosition) {
  28290. this.position.copyFrom(newPosition);
  28291. };
  28292. return DecimationVertex;
  28293. })();
  28294. BABYLON.DecimationVertex = DecimationVertex;
  28295. var QuadraticMatrix = (function () {
  28296. function QuadraticMatrix(data) {
  28297. this.data = new Array(10);
  28298. for (var i = 0; i < 10; ++i) {
  28299. if (data && data[i]) {
  28300. this.data[i] = data[i];
  28301. }
  28302. else {
  28303. this.data[i] = 0;
  28304. }
  28305. }
  28306. }
  28307. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  28308. 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];
  28309. return det;
  28310. };
  28311. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  28312. for (var i = 0; i < 10; ++i) {
  28313. this.data[i] += matrix.data[i];
  28314. }
  28315. };
  28316. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  28317. for (var i = 0; i < 10; ++i) {
  28318. this.data[i] += data[i];
  28319. }
  28320. };
  28321. QuadraticMatrix.prototype.add = function (matrix) {
  28322. var m = new QuadraticMatrix();
  28323. for (var i = 0; i < 10; ++i) {
  28324. m.data[i] = this.data[i] + matrix.data[i];
  28325. }
  28326. return m;
  28327. };
  28328. QuadraticMatrix.FromData = function (a, b, c, d) {
  28329. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  28330. };
  28331. //returning an array to avoid garbage collection
  28332. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  28333. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  28334. };
  28335. return QuadraticMatrix;
  28336. })();
  28337. BABYLON.QuadraticMatrix = QuadraticMatrix;
  28338. var Reference = (function () {
  28339. function Reference(vertexId, triangleId) {
  28340. this.vertexId = vertexId;
  28341. this.triangleId = triangleId;
  28342. }
  28343. return Reference;
  28344. })();
  28345. BABYLON.Reference = Reference;
  28346. /**
  28347. * An implementation of the Quadratic Error simplification algorithm.
  28348. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  28349. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  28350. * @author RaananW
  28351. */
  28352. var QuadraticErrorSimplification = (function () {
  28353. function QuadraticErrorSimplification(_mesh) {
  28354. this._mesh = _mesh;
  28355. this.initialized = false;
  28356. this.syncIterations = 5000;
  28357. this.aggressiveness = 7;
  28358. this.decimationIterations = 100;
  28359. this.boundingBoxEpsilon = BABYLON.Engine.Epsilon;
  28360. }
  28361. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  28362. var _this = this;
  28363. this.initDecimatedMesh();
  28364. //iterating through the submeshes array, one after the other.
  28365. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  28366. _this.initWithMesh(loop.index, function () {
  28367. _this.runDecimation(settings, loop.index, function () {
  28368. loop.executeNext();
  28369. });
  28370. }, settings.optimizeMesh);
  28371. }, function () {
  28372. setTimeout(function () {
  28373. successCallback(_this._reconstructedMesh);
  28374. }, 0);
  28375. });
  28376. };
  28377. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  28378. var _this = this;
  28379. var gCount = 0;
  28380. triangle.vertices.forEach(function (vertex) {
  28381. var count = 0;
  28382. var vPos = vertex.position;
  28383. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  28384. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  28385. ++count;
  28386. if (bbox.maximum.y == vPos.y || vPos.y == bbox.minimum.y)
  28387. ++count;
  28388. if (bbox.maximum.z == vPos.z || vPos.z == bbox.minimum.z)
  28389. ++count;
  28390. if (count > 1) {
  28391. ++gCount;
  28392. }
  28393. ;
  28394. });
  28395. if (gCount > 1) {
  28396. console.log(triangle, gCount);
  28397. }
  28398. return gCount > 1;
  28399. };
  28400. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  28401. var _this = this;
  28402. var targetCount = ~~(this.triangles.length * settings.quality);
  28403. var deletedTriangles = 0;
  28404. var triangleCount = this.triangles.length;
  28405. var iterationFunction = function (iteration, callback) {
  28406. setTimeout(function () {
  28407. if (iteration % 5 === 0) {
  28408. _this.updateMesh(iteration === 0);
  28409. }
  28410. for (var i = 0; i < _this.triangles.length; ++i) {
  28411. _this.triangles[i].isDirty = false;
  28412. }
  28413. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  28414. var trianglesIterator = function (i) {
  28415. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  28416. var t = _this.triangles[tIdx];
  28417. if (!t)
  28418. return;
  28419. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  28420. return;
  28421. }
  28422. for (var j = 0; j < 3; ++j) {
  28423. if (t.error[j] < threshold) {
  28424. var deleted0 = [];
  28425. var deleted1 = [];
  28426. var v0 = t.vertices[j];
  28427. var v1 = t.vertices[(j + 1) % 3];
  28428. if (v0.isBorder !== v1.isBorder)
  28429. continue;
  28430. var p = BABYLON.Vector3.Zero();
  28431. var n = BABYLON.Vector3.Zero();
  28432. var uv = BABYLON.Vector2.Zero();
  28433. var color = new BABYLON.Color4(0, 0, 0, 1);
  28434. _this.calculateError(v0, v1, p, n, uv, color);
  28435. var delTr = [];
  28436. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  28437. continue;
  28438. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  28439. continue;
  28440. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  28441. continue;
  28442. var uniqueArray = [];
  28443. delTr.forEach(function (deletedT) {
  28444. if (uniqueArray.indexOf(deletedT) === -1) {
  28445. deletedT.deletePending = true;
  28446. uniqueArray.push(deletedT);
  28447. }
  28448. });
  28449. if (uniqueArray.length % 2 != 0) {
  28450. continue;
  28451. }
  28452. v0.q = v1.q.add(v0.q);
  28453. v0.updatePosition(p);
  28454. var tStart = _this.references.length;
  28455. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  28456. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  28457. var tCount = _this.references.length - tStart;
  28458. if (tCount <= v0.triangleCount) {
  28459. if (tCount) {
  28460. for (var c = 0; c < tCount; c++) {
  28461. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  28462. }
  28463. }
  28464. }
  28465. else {
  28466. v0.triangleStart = tStart;
  28467. }
  28468. v0.triangleCount = tCount;
  28469. break;
  28470. }
  28471. }
  28472. };
  28473. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () {
  28474. return (triangleCount - deletedTriangles <= targetCount);
  28475. });
  28476. }, 0);
  28477. };
  28478. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  28479. if (triangleCount - deletedTriangles <= targetCount)
  28480. loop.breakLoop();
  28481. else {
  28482. iterationFunction(loop.index, function () {
  28483. loop.executeNext();
  28484. });
  28485. }
  28486. }, function () {
  28487. setTimeout(function () {
  28488. //reconstruct this part of the mesh
  28489. _this.reconstructMesh(submeshIndex);
  28490. successCallback();
  28491. }, 0);
  28492. });
  28493. };
  28494. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  28495. var _this = this;
  28496. this.vertices = [];
  28497. this.triangles = [];
  28498. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28499. var indices = this._mesh.getIndices();
  28500. var submesh = this._mesh.subMeshes[submeshIndex];
  28501. var findInVertices = function (positionToSearch) {
  28502. if (optimizeMesh) {
  28503. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  28504. if (_this.vertices[ii].position.equals(positionToSearch)) {
  28505. return _this.vertices[ii];
  28506. }
  28507. }
  28508. }
  28509. return null;
  28510. };
  28511. var vertexReferences = [];
  28512. var vertexInit = function (i) {
  28513. var offset = i + submesh.verticesStart;
  28514. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  28515. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  28516. vertex.originalOffsets.push(offset);
  28517. if (vertex.id == _this.vertices.length) {
  28518. _this.vertices.push(vertex);
  28519. }
  28520. vertexReferences.push(vertex.id);
  28521. };
  28522. //var totalVertices = mesh.getTotalVertices();
  28523. var totalVertices = submesh.verticesCount;
  28524. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  28525. var indicesInit = function (i) {
  28526. var offset = (submesh.indexStart / 3) + i;
  28527. var pos = (offset * 3);
  28528. var i0 = indices[pos + 0];
  28529. var i1 = indices[pos + 1];
  28530. var i2 = indices[pos + 2];
  28531. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  28532. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  28533. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  28534. var triangle = new DecimationTriangle([v0, v1, v2]);
  28535. triangle.originalOffset = pos;
  28536. _this.triangles.push(triangle);
  28537. };
  28538. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  28539. _this.init(callback);
  28540. });
  28541. });
  28542. };
  28543. QuadraticErrorSimplification.prototype.init = function (callback) {
  28544. var _this = this;
  28545. var triangleInit1 = function (i) {
  28546. var t = _this.triangles[i];
  28547. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  28548. for (var j = 0; j < 3; j++) {
  28549. t.vertices[j].q.addArrayInPlace(QuadraticMatrix.DataFromNumbers(t.normal.x, t.normal.y, t.normal.z, -(BABYLON.Vector3.Dot(t.normal, t.vertices[0].position))));
  28550. }
  28551. };
  28552. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  28553. var triangleInit2 = function (i) {
  28554. var t = _this.triangles[i];
  28555. for (var j = 0; j < 3; ++j) {
  28556. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  28557. }
  28558. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  28559. };
  28560. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  28561. _this.initialized = true;
  28562. callback();
  28563. });
  28564. });
  28565. };
  28566. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  28567. var newTriangles = [];
  28568. var i;
  28569. for (i = 0; i < this.vertices.length; ++i) {
  28570. this.vertices[i].triangleCount = 0;
  28571. }
  28572. var t;
  28573. var j;
  28574. for (i = 0; i < this.triangles.length; ++i) {
  28575. if (!this.triangles[i].deleted) {
  28576. t = this.triangles[i];
  28577. for (j = 0; j < 3; ++j) {
  28578. t.vertices[j].triangleCount = 1;
  28579. }
  28580. newTriangles.push(t);
  28581. }
  28582. }
  28583. var newPositionData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || [];
  28584. var newNormalData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || [];
  28585. var newUVsData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || [];
  28586. var newColorsData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || [];
  28587. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28588. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  28589. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  28590. var vertexCount = 0;
  28591. for (i = 0; i < this.vertices.length; ++i) {
  28592. var vertex = this.vertices[i];
  28593. vertex.id = vertexCount;
  28594. if (vertex.triangleCount) {
  28595. vertex.originalOffsets.forEach(function (originalOffset) {
  28596. newPositionData.push(vertex.position.x);
  28597. newPositionData.push(vertex.position.y);
  28598. newPositionData.push(vertex.position.z);
  28599. newNormalData.push(normalData[originalOffset * 3]);
  28600. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  28601. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  28602. if (uvs && uvs.length) {
  28603. newUVsData.push(uvs[(originalOffset * 2)]);
  28604. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  28605. }
  28606. else if (colorsData && colorsData.length) {
  28607. newColorsData.push(colorsData[(originalOffset * 4)]);
  28608. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  28609. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  28610. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  28611. }
  28612. ++vertexCount;
  28613. });
  28614. }
  28615. }
  28616. var startingIndex = this._reconstructedMesh.getTotalIndices();
  28617. var startingVertex = this._reconstructedMesh.getTotalVertices();
  28618. var submeshesArray = this._reconstructedMesh.subMeshes;
  28619. this._reconstructedMesh.subMeshes = [];
  28620. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  28621. var originalIndices = this._mesh.getIndices();
  28622. for (i = 0; i < newTriangles.length; ++i) {
  28623. var t = newTriangles[i];
  28624. //now get the new referencing point for each vertex
  28625. [0, 1, 2].forEach(function (idx) {
  28626. var id = originalIndices[t.originalOffset + idx];
  28627. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  28628. if (offset < 0)
  28629. offset = 0;
  28630. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  28631. });
  28632. }
  28633. //overwriting the old vertex buffers and indices.
  28634. this._reconstructedMesh.setIndices(newIndicesArray);
  28635. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  28636. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  28637. if (newUVsData.length > 0)
  28638. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  28639. if (newColorsData.length > 0)
  28640. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  28641. //create submesh
  28642. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  28643. if (submeshIndex > 0) {
  28644. this._reconstructedMesh.subMeshes = [];
  28645. submeshesArray.forEach(function (submesh) {
  28646. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, submesh.indexStart, submesh.indexCount, submesh.getMesh());
  28647. });
  28648. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  28649. }
  28650. };
  28651. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  28652. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  28653. this._reconstructedMesh.material = this._mesh.material;
  28654. this._reconstructedMesh.parent = this._mesh.parent;
  28655. this._reconstructedMesh.isVisible = false;
  28656. };
  28657. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  28658. for (var i = 0; i < vertex1.triangleCount; ++i) {
  28659. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  28660. if (t.deleted)
  28661. continue;
  28662. var s = this.references[vertex1.triangleStart + i].vertexId;
  28663. var v1 = t.vertices[(s + 1) % 3];
  28664. var v2 = t.vertices[(s + 2) % 3];
  28665. if ((v1 === vertex2 || v2 === vertex2)) {
  28666. deletedArray[i] = true;
  28667. delTr.push(t);
  28668. continue;
  28669. }
  28670. var d1 = v1.position.subtract(point);
  28671. d1 = d1.normalize();
  28672. var d2 = v2.position.subtract(point);
  28673. d2 = d2.normalize();
  28674. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  28675. return true;
  28676. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  28677. deletedArray[i] = false;
  28678. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  28679. return true;
  28680. }
  28681. return false;
  28682. };
  28683. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  28684. var newDeleted = deletedTriangles;
  28685. for (var i = 0; i < vertex.triangleCount; ++i) {
  28686. var ref = this.references[vertex.triangleStart + i];
  28687. var t = this.triangles[ref.triangleId];
  28688. if (t.deleted)
  28689. continue;
  28690. if (deletedArray[i] && t.deletePending) {
  28691. t.deleted = true;
  28692. newDeleted++;
  28693. continue;
  28694. }
  28695. t.vertices[ref.vertexId] = origVertex;
  28696. t.isDirty = true;
  28697. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  28698. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  28699. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  28700. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  28701. this.references.push(ref);
  28702. }
  28703. return newDeleted;
  28704. };
  28705. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  28706. for (var i = 0; i < this.vertices.length; ++i) {
  28707. var vCount = [];
  28708. var vId = [];
  28709. var v = this.vertices[i];
  28710. var j;
  28711. for (j = 0; j < v.triangleCount; ++j) {
  28712. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  28713. for (var ii = 0; ii < 3; ii++) {
  28714. var ofs = 0;
  28715. var vv = triangle.vertices[ii];
  28716. while (ofs < vCount.length) {
  28717. if (vId[ofs] === vv.id)
  28718. break;
  28719. ++ofs;
  28720. }
  28721. if (ofs === vCount.length) {
  28722. vCount.push(1);
  28723. vId.push(vv.id);
  28724. }
  28725. else {
  28726. vCount[ofs]++;
  28727. }
  28728. }
  28729. }
  28730. for (j = 0; j < vCount.length; ++j) {
  28731. if (vCount[j] === 1) {
  28732. this.vertices[vId[j]].isBorder = true;
  28733. }
  28734. else {
  28735. this.vertices[vId[j]].isBorder = false;
  28736. }
  28737. }
  28738. }
  28739. };
  28740. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  28741. if (identifyBorders === void 0) { identifyBorders = false; }
  28742. var i;
  28743. if (!identifyBorders) {
  28744. var newTrianglesVector = [];
  28745. for (i = 0; i < this.triangles.length; ++i) {
  28746. if (!this.triangles[i].deleted) {
  28747. newTrianglesVector.push(this.triangles[i]);
  28748. }
  28749. }
  28750. this.triangles = newTrianglesVector;
  28751. }
  28752. for (i = 0; i < this.vertices.length; ++i) {
  28753. this.vertices[i].triangleCount = 0;
  28754. this.vertices[i].triangleStart = 0;
  28755. }
  28756. var t;
  28757. var j;
  28758. var v;
  28759. for (i = 0; i < this.triangles.length; ++i) {
  28760. t = this.triangles[i];
  28761. for (j = 0; j < 3; ++j) {
  28762. v = t.vertices[j];
  28763. v.triangleCount++;
  28764. }
  28765. }
  28766. var tStart = 0;
  28767. for (i = 0; i < this.vertices.length; ++i) {
  28768. this.vertices[i].triangleStart = tStart;
  28769. tStart += this.vertices[i].triangleCount;
  28770. this.vertices[i].triangleCount = 0;
  28771. }
  28772. var newReferences = new Array(this.triangles.length * 3);
  28773. for (i = 0; i < this.triangles.length; ++i) {
  28774. t = this.triangles[i];
  28775. for (j = 0; j < 3; ++j) {
  28776. v = t.vertices[j];
  28777. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  28778. v.triangleCount++;
  28779. }
  28780. }
  28781. this.references = newReferences;
  28782. if (identifyBorders) {
  28783. this.identifyBorder();
  28784. }
  28785. };
  28786. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  28787. var x = point.x;
  28788. var y = point.y;
  28789. var z = point.z;
  28790. 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];
  28791. };
  28792. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  28793. var q = vertex1.q.add(vertex2.q);
  28794. var border = vertex1.isBorder && vertex2.isBorder;
  28795. var error = 0;
  28796. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  28797. if (qDet !== 0 && !border) {
  28798. if (!pointResult) {
  28799. pointResult = BABYLON.Vector3.Zero();
  28800. }
  28801. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  28802. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  28803. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  28804. error = this.vertexError(q, pointResult);
  28805. }
  28806. else {
  28807. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  28808. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  28809. var error1 = this.vertexError(q, vertex1.position);
  28810. var error2 = this.vertexError(q, vertex2.position);
  28811. var error3 = this.vertexError(q, p3);
  28812. error = Math.min(error1, error2, error3);
  28813. if (error === error1) {
  28814. if (pointResult) {
  28815. pointResult.copyFrom(vertex1.position);
  28816. }
  28817. }
  28818. else if (error === error2) {
  28819. if (pointResult) {
  28820. pointResult.copyFrom(vertex2.position);
  28821. }
  28822. }
  28823. else {
  28824. if (pointResult) {
  28825. pointResult.copyFrom(p3);
  28826. }
  28827. }
  28828. }
  28829. return error;
  28830. };
  28831. return QuadraticErrorSimplification;
  28832. })();
  28833. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  28834. })(BABYLON || (BABYLON = {}));
  28835. //# sourceMappingURL=babylon.meshSimplification.js.mapvar BABYLON;
  28836. (function (BABYLON) {
  28837. var Analyser = (function () {
  28838. function Analyser(scene) {
  28839. this.SMOOTHING = 0.75;
  28840. this.FFT_SIZE = 512;
  28841. this.BARGRAPHAMPLITUDE = 256;
  28842. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  28843. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  28844. this._scene = scene;
  28845. this._audioEngine = BABYLON.Engine.audioEngine;
  28846. if (this._audioEngine.canUseWebAudio) {
  28847. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  28848. this._webAudioAnalyser.minDecibels = -140;
  28849. this._webAudioAnalyser.maxDecibels = 0;
  28850. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  28851. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  28852. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  28853. }
  28854. }
  28855. Analyser.prototype.getFrequencyBinCount = function () {
  28856. if (this._audioEngine.canUseWebAudio) {
  28857. return this._webAudioAnalyser.frequencyBinCount;
  28858. }
  28859. else {
  28860. return 0;
  28861. }
  28862. };
  28863. Analyser.prototype.getByteFrequencyData = function () {
  28864. if (this._audioEngine.canUseWebAudio) {
  28865. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  28866. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  28867. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  28868. }
  28869. return this._byteFreqs;
  28870. };
  28871. Analyser.prototype.getByteTimeDomainData = function () {
  28872. if (this._audioEngine.canUseWebAudio) {
  28873. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  28874. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  28875. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  28876. }
  28877. return this._byteTime;
  28878. };
  28879. Analyser.prototype.getFloatFrequencyData = function () {
  28880. if (this._audioEngine.canUseWebAudio) {
  28881. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  28882. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  28883. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  28884. }
  28885. return this._floatFreqs;
  28886. };
  28887. Analyser.prototype.drawDebugCanvas = function () {
  28888. var _this = this;
  28889. if (this._audioEngine.canUseWebAudio) {
  28890. if (!this._debugCanvas) {
  28891. this._debugCanvas = document.createElement("canvas");
  28892. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  28893. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  28894. this._debugCanvas.style.position = "absolute";
  28895. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  28896. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  28897. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  28898. document.body.appendChild(this._debugCanvas);
  28899. this._registerFunc = function () {
  28900. _this.drawDebugCanvas();
  28901. };
  28902. this._scene.registerBeforeRender(this._registerFunc);
  28903. }
  28904. if (this._registerFunc) {
  28905. var workingArray = this.getByteFrequencyData();
  28906. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  28907. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  28908. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  28909. var value = workingArray[i];
  28910. var percent = value / this.BARGRAPHAMPLITUDE;
  28911. var height = this.DEBUGCANVASSIZE.height * percent;
  28912. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  28913. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  28914. var hue = i / this.getFrequencyBinCount() * 360;
  28915. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  28916. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  28917. }
  28918. }
  28919. }
  28920. };
  28921. Analyser.prototype.stopDebugCanvas = function () {
  28922. if (this._debugCanvas) {
  28923. this._scene.unregisterBeforeRender(this._registerFunc);
  28924. this._registerFunc = null;
  28925. document.body.removeChild(this._debugCanvas);
  28926. this._debugCanvas = null;
  28927. this._debugCanvasContext = null;
  28928. }
  28929. };
  28930. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  28931. if (this._audioEngine.canUseWebAudio) {
  28932. inputAudioNode.connect(this._webAudioAnalyser);
  28933. this._webAudioAnalyser.connect(outputAudioNode);
  28934. }
  28935. };
  28936. Analyser.prototype.dispose = function () {
  28937. if (this._audioEngine.canUseWebAudio) {
  28938. this._webAudioAnalyser.disconnect();
  28939. }
  28940. };
  28941. return Analyser;
  28942. })();
  28943. BABYLON.Analyser = Analyser;
  28944. })(BABYLON || (BABYLON = {}));
  28945. //# sourceMappingURL=babylon.analyser.js.mapvar BABYLON;
  28946. (function (BABYLON) {
  28947. var DepthRenderer = (function () {
  28948. function DepthRenderer(scene, type) {
  28949. var _this = this;
  28950. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  28951. this._viewMatrix = BABYLON.Matrix.Zero();
  28952. this._projectionMatrix = BABYLON.Matrix.Zero();
  28953. this._transformMatrix = BABYLON.Matrix.Zero();
  28954. this._worldViewProjection = BABYLON.Matrix.Zero();
  28955. this._scene = scene;
  28956. var engine = scene.getEngine();
  28957. // Render target
  28958. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  28959. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  28960. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  28961. this._depthMap.refreshRate = 1;
  28962. this._depthMap.renderParticles = false;
  28963. this._depthMap.renderList = null;
  28964. // Custom render function
  28965. var renderSubMesh = function (subMesh) {
  28966. var mesh = subMesh.getRenderingMesh();
  28967. var scene = _this._scene;
  28968. var engine = scene.getEngine();
  28969. // Culling
  28970. engine.setState(subMesh.getMaterial().backFaceCulling);
  28971. // Managing instances
  28972. var batch = mesh._getInstancesRenderList(subMesh._id);
  28973. if (batch.mustReturn) {
  28974. return;
  28975. }
  28976. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  28977. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  28978. engine.enableEffect(_this._effect);
  28979. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  28980. var material = subMesh.getMaterial();
  28981. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  28982. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  28983. // Alpha test
  28984. if (material && material.needAlphaTesting()) {
  28985. var alphaTexture = material.getAlphaTestTexture();
  28986. _this._effect.setTexture("diffuseSampler", alphaTexture);
  28987. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  28988. }
  28989. // Bones
  28990. if (mesh.useBones) {
  28991. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  28992. }
  28993. // Draw
  28994. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  28995. }
  28996. };
  28997. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  28998. var index;
  28999. for (index = 0; index < opaqueSubMeshes.length; index++) {
  29000. renderSubMesh(opaqueSubMeshes.data[index]);
  29001. }
  29002. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  29003. renderSubMesh(alphaTestSubMeshes.data[index]);
  29004. }
  29005. };
  29006. }
  29007. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  29008. var defines = [];
  29009. var attribs = [BABYLON.VertexBuffer.PositionKind];
  29010. var mesh = subMesh.getMesh();
  29011. var scene = mesh.getScene();
  29012. var material = subMesh.getMaterial();
  29013. // Alpha test
  29014. if (material && material.needAlphaTesting()) {
  29015. defines.push("#define ALPHATEST");
  29016. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29017. attribs.push(BABYLON.VertexBuffer.UVKind);
  29018. defines.push("#define UV1");
  29019. }
  29020. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  29021. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  29022. defines.push("#define UV2");
  29023. }
  29024. }
  29025. // Bones
  29026. if (mesh.useBones) {
  29027. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  29028. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  29029. defines.push("#define BONES");
  29030. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  29031. }
  29032. // Instances
  29033. if (useInstances) {
  29034. defines.push("#define INSTANCES");
  29035. attribs.push("world0");
  29036. attribs.push("world1");
  29037. attribs.push("world2");
  29038. attribs.push("world3");
  29039. }
  29040. // Get correct effect
  29041. var join = defines.join("\n");
  29042. if (this._cachedDefines !== join) {
  29043. this._cachedDefines = join;
  29044. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  29045. }
  29046. return this._effect.isReady();
  29047. };
  29048. DepthRenderer.prototype.getDepthMap = function () {
  29049. return this._depthMap;
  29050. };
  29051. // Methods
  29052. DepthRenderer.prototype.dispose = function () {
  29053. this._depthMap.dispose();
  29054. };
  29055. return DepthRenderer;
  29056. })();
  29057. BABYLON.DepthRenderer = DepthRenderer;
  29058. })(BABYLON || (BABYLON = {}));
  29059. //# sourceMappingURL=babylon.depthRenderer.js.map
  29060. var BABYLON;
  29061. (function (BABYLON) {
  29062. var SSAORenderingPipeline = (function (_super) {
  29063. __extends(SSAORenderingPipeline, _super);
  29064. /**
  29065. * @constructor
  29066. * @param {string} name - The rendering pipeline name
  29067. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  29068. * @param {any} ratio - The size of the postprocesses. Can be a number shared between passes or an object for more precision: { ssaoRatio: 0.5, combineRatio: 1.0 }
  29069. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  29070. */
  29071. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  29072. var _this = this;
  29073. _super.call(this, scene.getEngine(), name);
  29074. // Members
  29075. /**
  29076. * The PassPostProcess id in the pipeline that contains the original scene color
  29077. * @type {string}
  29078. */
  29079. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  29080. /**
  29081. * The SSAO PostProcess id in the pipeline
  29082. * @type {string}
  29083. */
  29084. this.SSAORenderEffect = "SSAORenderEffect";
  29085. /**
  29086. * The horizontal blur PostProcess id in the pipeline
  29087. * @type {string}
  29088. */
  29089. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  29090. /**
  29091. * The vertical blur PostProcess id in the pipeline
  29092. * @type {string}
  29093. */
  29094. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  29095. /**
  29096. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  29097. * @type {string}
  29098. */
  29099. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  29100. /**
  29101. * The output strength of the SSAO post-process. Default value is 1.0.
  29102. * @type {number}
  29103. */
  29104. this.totalStrength = 1.0;
  29105. /**
  29106. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0002
  29107. * @type {number}
  29108. */
  29109. this.radius = 0.0002;
  29110. /**
  29111. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  29112. * Must not be equal to fallOff and superior to fallOff.
  29113. * Default value is 0.0075
  29114. * @type {number}
  29115. */
  29116. this.area = 0.0075;
  29117. /**
  29118. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  29119. * Must not be equal to area and inferior to area.
  29120. * Default value is 0.0002
  29121. * @type {number}
  29122. */
  29123. this.fallOff = 0.0002;
  29124. this._firstUpdate = true;
  29125. this._scene = scene;
  29126. // Set up assets
  29127. this._createRandomTexture();
  29128. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  29129. var ssaoRatio = ratio.ssaoRatio || ratio;
  29130. var combineRatio = ratio.combineRatio || ratio;
  29131. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  29132. this._createSSAOPostProcess(ssaoRatio);
  29133. this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlurH", new BABYLON.Vector2(2.0, 0.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  29134. this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlurV", new BABYLON.Vector2(0.0, 2.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  29135. this._createSSAOCombinePostProcess(combineRatio);
  29136. // Set up pipeline
  29137. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () {
  29138. return _this._originalColorPostProcess;
  29139. }, true));
  29140. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () {
  29141. return _this._ssaoPostProcess;
  29142. }, true));
  29143. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () {
  29144. return _this._blurHPostProcess;
  29145. }, true));
  29146. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () {
  29147. return _this._blurVPostProcess;
  29148. }, true));
  29149. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () {
  29150. return _this._ssaoCombinePostProcess;
  29151. }, true));
  29152. // Finish
  29153. scene.postProcessRenderPipelineManager.addPipeline(this);
  29154. if (cameras)
  29155. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  29156. }
  29157. // Public Methods
  29158. /**
  29159. * Returns the horizontal blur PostProcess
  29160. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  29161. */
  29162. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  29163. return this._blurHPostProcess;
  29164. };
  29165. /**
  29166. * Returns the vertical blur PostProcess
  29167. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  29168. */
  29169. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  29170. return this._blurVPostProcess;
  29171. };
  29172. /**
  29173. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  29174. */
  29175. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  29176. if (disableDepthRender === void 0) { disableDepthRender = false; }
  29177. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  29178. this._originalColorPostProcess = undefined;
  29179. this._ssaoPostProcess = undefined;
  29180. this._blurHPostProcess = undefined;
  29181. this._blurVPostProcess = undefined;
  29182. this._ssaoCombinePostProcess = undefined;
  29183. this._randomTexture.dispose();
  29184. if (disableDepthRender)
  29185. this._scene.disableDepthRenderer();
  29186. };
  29187. // Private Methods
  29188. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  29189. var _this = this;
  29190. var sampleSphere = [
  29191. 0.5381,
  29192. 0.1856,
  29193. -0.4319,
  29194. 0.1379,
  29195. 0.2486,
  29196. 0.4430,
  29197. 0.3371,
  29198. 0.5679,
  29199. -0.0057,
  29200. -0.6999,
  29201. -0.0451,
  29202. -0.0019,
  29203. 0.0689,
  29204. -0.1598,
  29205. -0.8547,
  29206. 0.0560,
  29207. 0.0069,
  29208. -0.1843,
  29209. -0.0146,
  29210. 0.1402,
  29211. 0.0762,
  29212. 0.0100,
  29213. -0.1924,
  29214. -0.0344,
  29215. -0.3577,
  29216. -0.5301,
  29217. -0.4358,
  29218. -0.3169,
  29219. 0.1063,
  29220. 0.0158,
  29221. 0.0103,
  29222. -0.5869,
  29223. 0.0046,
  29224. -0.0897,
  29225. -0.4940,
  29226. 0.3287,
  29227. 0.7119,
  29228. -0.0154,
  29229. -0.0918,
  29230. -0.0533,
  29231. 0.0596,
  29232. -0.5411,
  29233. 0.0352,
  29234. -0.0631,
  29235. 0.5460,
  29236. -0.4776,
  29237. 0.2847,
  29238. -0.0271
  29239. ];
  29240. var samplesFactor = 1.0 / 16.0;
  29241. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", ["sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius", "area", "fallOff"], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  29242. this._ssaoPostProcess.onApply = function (effect) {
  29243. if (_this._firstUpdate) {
  29244. effect.setArray3("sampleSphere", sampleSphere);
  29245. effect.setFloat("samplesFactor", samplesFactor);
  29246. effect.setFloat("randTextureTiles", 4.0 / ratio);
  29247. _this._firstUpdate = false;
  29248. }
  29249. effect.setFloat("totalStrength", _this.totalStrength);
  29250. effect.setFloat("radius", _this.radius);
  29251. effect.setFloat("area", _this.area);
  29252. effect.setFloat("fallOff", _this.fallOff);
  29253. effect.setTexture("textureSampler", _this._depthTexture);
  29254. effect.setTexture("randomSampler", _this._randomTexture);
  29255. };
  29256. };
  29257. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  29258. var _this = this;
  29259. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  29260. this._ssaoCombinePostProcess.onApply = function (effect) {
  29261. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  29262. };
  29263. };
  29264. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  29265. var size = 512;
  29266. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  29267. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  29268. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  29269. var context = this._randomTexture.getContext();
  29270. var rand = function (min, max) {
  29271. return Math.random() * (max - min) + min;
  29272. };
  29273. for (var x = 0; x < size; x++) {
  29274. for (var y = 0; y < size; y++) {
  29275. var randVector = BABYLON.Vector3.Zero();
  29276. randVector.x = Math.floor(rand(0.0, 1.0) * 255);
  29277. randVector.y = Math.floor(rand(0.0, 1.0) * 255);
  29278. randVector.z = Math.floor(rand(0.0, 1.0) * 255);
  29279. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  29280. context.fillRect(x, y, 1, 1);
  29281. }
  29282. }
  29283. this._randomTexture.update(false);
  29284. };
  29285. return SSAORenderingPipeline;
  29286. })(BABYLON.PostProcessRenderPipeline);
  29287. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  29288. })(BABYLON || (BABYLON = {}));
  29289. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  29290. var BABYLON;
  29291. (function (BABYLON) {
  29292. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  29293. var VolumetricLightScatteringPostProcess = (function (_super) {
  29294. __extends(VolumetricLightScatteringPostProcess, _super);
  29295. /**
  29296. * @constructor
  29297. * @param {string} name - The post-process name
  29298. * @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)
  29299. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  29300. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  29301. * @param {number} samples - The post-process quality, default 100
  29302. * @param {number} samplingMode - The post-process filtering mode
  29303. * @param {BABYLON.Engine} engine - The babylon engine
  29304. * @param {boolean} reusable - If the post-process is reusable
  29305. */
  29306. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable) {
  29307. var _this = this;
  29308. if (samples === void 0) { samples = 100; }
  29309. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  29310. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  29311. this._screenCoordinates = BABYLON.Vector2.Zero();
  29312. /**
  29313. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  29314. * @type {boolean}
  29315. */
  29316. this.useCustomMeshPosition = false;
  29317. /**
  29318. * If the post-process should inverse the light scattering direction
  29319. * @type {boolean}
  29320. */
  29321. this.invert = true;
  29322. /**
  29323. * Array containing the excluded meshes not rendered in the internal pass
  29324. */
  29325. this.excludedMeshes = new Array();
  29326. this.exposure = 0.3;
  29327. this.decay = 0.96815;
  29328. this.weight = 0.58767;
  29329. this.density = 0.926;
  29330. var scene = camera.getScene();
  29331. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(scene.getEngine());
  29332. // Configure mesh
  29333. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  29334. // Configure
  29335. this._createPass(scene, ratio.passRatio || ratio);
  29336. this.onApply = function (effect) {
  29337. _this._updateMeshScreenCoordinates(scene);
  29338. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  29339. effect.setFloat("exposure", _this.exposure);
  29340. effect.setFloat("decay", _this.decay);
  29341. effect.setFloat("weight", _this.weight);
  29342. effect.setFloat("density", _this.density);
  29343. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  29344. };
  29345. }
  29346. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  29347. var mesh = subMesh.getMesh();
  29348. var defines = [];
  29349. var attribs = [BABYLON.VertexBuffer.PositionKind];
  29350. var material = subMesh.getMaterial();
  29351. var needUV = false;
  29352. // Render this.mesh as default
  29353. if (mesh === this.mesh) {
  29354. defines.push("#define BASIC_RENDER");
  29355. defines.push("#define NEED_UV");
  29356. needUV = true;
  29357. }
  29358. // Alpha test
  29359. if (material) {
  29360. if (material.needAlphaTesting() || mesh === this.mesh)
  29361. defines.push("#define ALPHATEST");
  29362. if (material.opacityTexture !== undefined) {
  29363. defines.push("#define OPACITY");
  29364. if (material.opacityTexture.getAlphaFromRGB)
  29365. defines.push("#define OPACITYRGB");
  29366. if (!needUV)
  29367. defines.push("#define NEED_UV");
  29368. }
  29369. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29370. attribs.push(BABYLON.VertexBuffer.UVKind);
  29371. defines.push("#define UV1");
  29372. }
  29373. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  29374. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  29375. defines.push("#define UV2");
  29376. }
  29377. }
  29378. // Bones
  29379. if (mesh.useBones) {
  29380. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  29381. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  29382. defines.push("#define BONES");
  29383. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  29384. }
  29385. // Instances
  29386. if (useInstances) {
  29387. defines.push("#define INSTANCES");
  29388. attribs.push("world0");
  29389. attribs.push("world1");
  29390. attribs.push("world2");
  29391. attribs.push("world3");
  29392. }
  29393. // Get correct effect
  29394. var join = defines.join("\n");
  29395. if (this._cachedDefines !== join) {
  29396. this._cachedDefines = join;
  29397. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "opacityLevel"], ["diffuseSampler", "opacitySampler"], join);
  29398. }
  29399. return this._volumetricLightScatteringPass.isReady();
  29400. };
  29401. /**
  29402. * Sets the new light position for light scattering effect
  29403. * @param {BABYLON.Vector3} The new custom light position
  29404. */
  29405. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  29406. this._customMeshPosition = position;
  29407. };
  29408. /**
  29409. * Returns the light position for light scattering effect
  29410. * @return {BABYLON.Vector3} The custom light position
  29411. */
  29412. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  29413. return this._customMeshPosition;
  29414. };
  29415. /**
  29416. * Disposes the internal assets and detaches the post-process from the camera
  29417. */
  29418. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  29419. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  29420. if (rttIndex !== -1) {
  29421. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  29422. }
  29423. this._volumetricLightScatteringRTT.dispose();
  29424. _super.prototype.dispose.call(this, camera);
  29425. };
  29426. /**
  29427. * Returns the render target texture used by the post-process
  29428. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  29429. */
  29430. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  29431. return this._volumetricLightScatteringRTT;
  29432. };
  29433. // Private methods
  29434. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  29435. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  29436. return true;
  29437. }
  29438. return false;
  29439. };
  29440. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  29441. var _this = this;
  29442. var engine = scene.getEngine();
  29443. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  29444. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  29445. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  29446. this._volumetricLightScatteringRTT.renderList = null;
  29447. this._volumetricLightScatteringRTT.renderParticles = false;
  29448. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  29449. // Custom render function for submeshes
  29450. var renderSubMesh = function (subMesh) {
  29451. var mesh = subMesh.getRenderingMesh();
  29452. if (_this._meshExcluded(mesh)) {
  29453. return;
  29454. }
  29455. var scene = mesh.getScene();
  29456. var engine = scene.getEngine();
  29457. // Culling
  29458. engine.setState(subMesh.getMaterial().backFaceCulling);
  29459. // Managing instances
  29460. var batch = mesh._getInstancesRenderList(subMesh._id);
  29461. if (batch.mustReturn) {
  29462. return;
  29463. }
  29464. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  29465. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  29466. engine.enableEffect(_this._volumetricLightScatteringPass);
  29467. mesh._bind(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode);
  29468. var material = subMesh.getMaterial();
  29469. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  29470. // Alpha test
  29471. if (material && (mesh === _this.mesh || material.needAlphaTesting() || material.opacityTexture !== undefined)) {
  29472. var alphaTexture = material.getAlphaTestTexture();
  29473. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  29474. if (alphaTexture) {
  29475. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  29476. }
  29477. if (material.opacityTexture !== undefined) {
  29478. _this._volumetricLightScatteringPass.setTexture("opacitySampler", material.opacityTexture);
  29479. _this._volumetricLightScatteringPass.setFloat("opacityLevel", material.opacityTexture.level);
  29480. }
  29481. }
  29482. // Bones
  29483. if (mesh.useBones) {
  29484. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  29485. }
  29486. // Draw
  29487. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._volumetricLightScatteringPass.setMatrix("world", world); });
  29488. }
  29489. };
  29490. // Render target texture callbacks
  29491. var savedSceneClearColor;
  29492. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  29493. this._volumetricLightScatteringRTT.onBeforeRender = function () {
  29494. savedSceneClearColor = scene.clearColor;
  29495. scene.clearColor = sceneClearColor;
  29496. };
  29497. this._volumetricLightScatteringRTT.onAfterRender = function () {
  29498. scene.clearColor = savedSceneClearColor;
  29499. };
  29500. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  29501. var engine = scene.getEngine();
  29502. var index;
  29503. for (index = 0; index < opaqueSubMeshes.length; index++) {
  29504. renderSubMesh(opaqueSubMeshes.data[index]);
  29505. }
  29506. engine.setAlphaTesting(true);
  29507. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  29508. renderSubMesh(alphaTestSubMeshes.data[index]);
  29509. }
  29510. engine.setAlphaTesting(false);
  29511. if (transparentSubMeshes.length) {
  29512. for (index = 0; index < transparentSubMeshes.length; index++) {
  29513. var submesh = transparentSubMeshes.data[index];
  29514. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  29515. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  29516. }
  29517. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  29518. sortedArray.sort(function (a, b) {
  29519. // Alpha index first
  29520. if (a._alphaIndex > b._alphaIndex) {
  29521. return 1;
  29522. }
  29523. if (a._alphaIndex < b._alphaIndex) {
  29524. return -1;
  29525. }
  29526. // Then distance to camera
  29527. if (a._distanceToCamera < b._distanceToCamera) {
  29528. return 1;
  29529. }
  29530. if (a._distanceToCamera > b._distanceToCamera) {
  29531. return -1;
  29532. }
  29533. return 0;
  29534. });
  29535. // Render sub meshes
  29536. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  29537. for (index = 0; index < sortedArray.length; index++) {
  29538. renderSubMesh(sortedArray[index]);
  29539. }
  29540. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  29541. }
  29542. };
  29543. };
  29544. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  29545. var transform = scene.getTransformMatrix();
  29546. var pos = BABYLON.Vector3.Project(this.useCustomMeshPosition ? this._customMeshPosition : this.mesh.position, BABYLON.Matrix.Identity(), transform, this._viewPort);
  29547. this._screenCoordinates.x = pos.x / this._viewPort.width;
  29548. this._screenCoordinates.y = pos.y / this._viewPort.height;
  29549. if (this.invert)
  29550. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  29551. };
  29552. // Static methods
  29553. /**
  29554. * Creates a default mesh for the Volumeric Light Scattering post-process
  29555. * @param {string} The mesh name
  29556. * @param {BABYLON.Scene} The scene where to create the mesh
  29557. * @return {BABYLON.Mesh} the default mesh
  29558. */
  29559. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  29560. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  29561. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  29562. mesh.material = new BABYLON.StandardMaterial(name + "Material", scene);
  29563. return mesh;
  29564. };
  29565. return VolumetricLightScatteringPostProcess;
  29566. })(BABYLON.PostProcess);
  29567. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  29568. })(BABYLON || (BABYLON = {}));
  29569. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  29570. var BABYLON;
  29571. (function (BABYLON) {
  29572. var LensRenderingPipeline = (function (_super) {
  29573. __extends(LensRenderingPipeline, _super);
  29574. /**
  29575. * @constructor
  29576. * @param {string} name - The rendering pipeline name
  29577. * @param {object} parameters - An object containing all parameters (see below)
  29578. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  29579. * @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)
  29580. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  29581. Effect parameters are as follow:
  29582. {
  29583. chromatic_aberration: number; // from 0 to x (1 for realism)
  29584. edge_blur: number; // from 0 to x (1 for realism)
  29585. distortion: number; // from 0 to x (1 for realism)
  29586. grain_amount: number; // from 0 to 1
  29587. grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  29588. dof_focus_depth: number; // depth-of-field: focus depth; unset to disable
  29589. dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  29590. dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  29591. dof_gain: boolean; // depth-of-field: depthOfField gain (default: 1)
  29592. dof_threshold: boolean; // depth-of-field: depthOfField threshold (default: 1)
  29593. blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  29594. }
  29595. Note: if an effect parameter is unset, effect is disabled
  29596. */
  29597. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  29598. var _this = this;
  29599. if (ratio === void 0) { ratio = 1.0; }
  29600. _super.call(this, scene.getEngine(), name);
  29601. // Lens effects can be of the following:
  29602. // - chromatic aberration (slight shift of RGB colors)
  29603. // - blur on the edge of the lens
  29604. // - lens distortion
  29605. // - depth-of-field 'bokeh' effect (shapes appearing in blured areas, stronger highlights)
  29606. // - grain/dust-on-lens effect
  29607. // Two additional texture samplers are needed:
  29608. // - depth map (for depth-of-field)
  29609. // - grain texture
  29610. /**
  29611. * The chromatic aberration PostProcess id in the pipeline
  29612. * @type {string}
  29613. */
  29614. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  29615. /**
  29616. * The depth-of-field PostProcess id in the pipeline
  29617. * @type {string}
  29618. */
  29619. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  29620. this._scene = scene;
  29621. // Fetch texture samplers
  29622. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  29623. if (parameters.grain_texture) {
  29624. this._grainTexture = parameters.grain_texture;
  29625. }
  29626. else {
  29627. this._createGrainTexture();
  29628. }
  29629. // save parameters
  29630. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  29631. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  29632. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  29633. this._distortion = parameters.distortion ? parameters.distortion : 0;
  29634. this._highlightsGain = parameters.dof_gain ? parameters.dof_gain : 1;
  29635. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  29636. this._dofDepth = parameters.dof_focus_depth !== undefined ? parameters.dof_focus_depth : -1;
  29637. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  29638. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  29639. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  29640. // Create effects
  29641. this._createChromaticAberrationPostProcess(ratio);
  29642. this._createDepthOfFieldPostProcess(ratio);
  29643. // Set up pipeline
  29644. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () {
  29645. return _this._chromaticAberrationPostProcess;
  29646. }, true));
  29647. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () {
  29648. return _this._depthOfFieldPostProcess;
  29649. }, true));
  29650. // Finish
  29651. scene.postProcessRenderPipelineManager.addPipeline(this);
  29652. if (cameras) {
  29653. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  29654. }
  29655. }
  29656. // public methods
  29657. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) {
  29658. this._edgeBlur = amount;
  29659. };
  29660. LensRenderingPipeline.prototype.disableEdgeBlur = function () {
  29661. this._edgeBlur = 0;
  29662. };
  29663. LensRenderingPipeline.prototype.setGrainAmount = function (amount) {
  29664. this._grainAmount = amount;
  29665. };
  29666. LensRenderingPipeline.prototype.disableGrain = function () {
  29667. this._grainAmount = 0;
  29668. };
  29669. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) {
  29670. this._chromaticAberration = amount;
  29671. };
  29672. LensRenderingPipeline.prototype.disableChromaticAberration = function () {
  29673. this._chromaticAberration = 0;
  29674. };
  29675. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) {
  29676. this._distortion = amount;
  29677. };
  29678. LensRenderingPipeline.prototype.disableEdgeDistortion = function () {
  29679. this._distortion = 0;
  29680. };
  29681. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  29682. this._highlightsGain = amount;
  29683. };
  29684. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  29685. this._highlightsThreshold = amount;
  29686. };
  29687. LensRenderingPipeline.prototype.setFocusDepth = function (amount) {
  29688. this._dofDepth = amount;
  29689. };
  29690. LensRenderingPipeline.prototype.disableDepthOfField = function () {
  29691. this._dofDepth = -1;
  29692. };
  29693. LensRenderingPipeline.prototype.setAperture = function (amount) {
  29694. this._dofAperture = amount;
  29695. };
  29696. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  29697. this._dofPentagon = true;
  29698. };
  29699. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  29700. this._dofPentagon = false;
  29701. };
  29702. LensRenderingPipeline.prototype.enableNoiseBlur = function () {
  29703. this._blurNoise = true;
  29704. };
  29705. LensRenderingPipeline.prototype.disableNoiseBlur = function () {
  29706. this._blurNoise = false;
  29707. };
  29708. /**
  29709. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  29710. */
  29711. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  29712. if (disableDepthRender === void 0) { disableDepthRender = false; }
  29713. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  29714. this._chromaticAberrationPostProcess = undefined;
  29715. this._depthOfFieldPostProcess = undefined;
  29716. this._grainTexture.dispose();
  29717. if (disableDepthRender)
  29718. this._scene.disableDepthRenderer();
  29719. };
  29720. // colors shifting and distortion
  29721. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  29722. var _this = this;
  29723. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], [], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  29724. this._chromaticAberrationPostProcess.onApply = function (effect) {
  29725. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  29726. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  29727. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  29728. };
  29729. };
  29730. // colors shifting and distortion
  29731. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  29732. var _this = this;
  29733. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  29734. "gain",
  29735. "threshold",
  29736. "focus_depth",
  29737. "aperture",
  29738. "pentagon",
  29739. "maxZ",
  29740. "edge_blur",
  29741. "chromatic_aberration",
  29742. "distortion",
  29743. "blur_noise",
  29744. "grain_amount",
  29745. "screen_width",
  29746. "screen_height"
  29747. ], ["depthSampler", "grainSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  29748. this._depthOfFieldPostProcess.onApply = function (effect) {
  29749. effect.setBool('pentagon', _this._dofPentagon);
  29750. effect.setBool('blur_noise', _this._blurNoise);
  29751. effect.setFloat('maxZ', _this._scene.activeCamera.maxZ);
  29752. effect.setFloat('grain_amount', _this._grainAmount);
  29753. effect.setTexture("depthSampler", _this._depthTexture);
  29754. effect.setTexture("grainSampler", _this._grainTexture);
  29755. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  29756. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  29757. effect.setFloat('distortion', _this._distortion);
  29758. effect.setFloat('focus_depth', _this._dofDepth);
  29759. effect.setFloat('aperture', _this._dofAperture);
  29760. effect.setFloat('gain', _this._highlightsGain);
  29761. effect.setFloat('threshold', _this._highlightsThreshold);
  29762. effect.setFloat('edge_blur', _this._edgeBlur);
  29763. };
  29764. };
  29765. // creates a black and white random noise texture, 512x512
  29766. LensRenderingPipeline.prototype._createGrainTexture = function () {
  29767. var size = 512;
  29768. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  29769. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  29770. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  29771. var context = this._grainTexture.getContext();
  29772. var rand = function (min, max) {
  29773. return Math.random() * (max - min) + min;
  29774. };
  29775. var value;
  29776. for (var x = 0; x < size; x++) {
  29777. for (var y = 0; y < size; y++) {
  29778. value = Math.floor(rand(0.42, 0.58) * 255);
  29779. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  29780. context.fillRect(x, y, 1, 1);
  29781. }
  29782. }
  29783. this._grainTexture.update(false);
  29784. };
  29785. return LensRenderingPipeline;
  29786. })(BABYLON.PostProcessRenderPipeline);
  29787. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  29788. })(BABYLON || (BABYLON = {}));
  29789. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map//
  29790. // This post-process allows the modification of rendered colors by using
  29791. // a 'look-up table' (LUT). This effect is also called Color Grading.
  29792. //
  29793. // The object needs to be provided an url to a texture containing the color
  29794. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  29795. // Use an image editing software to tweak the LUT to match your needs.
  29796. //
  29797. // For an example of a color LUT, see here:
  29798. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  29799. // For explanations on color grading, see here:
  29800. // http://udn.epicgames.com/Three/ColorGrading.html
  29801. //
  29802. var BABYLON;
  29803. (function (BABYLON) {
  29804. var ColorCorrectionPostProcess = (function (_super) {
  29805. __extends(ColorCorrectionPostProcess, _super);
  29806. function ColorCorrectionPostProcess(name, colorTableUrl, ratio, camera, samplingMode, engine, reusable) {
  29807. var _this = this;
  29808. _super.call(this, name, 'colorCorrection', null, ['colorTable'], ratio, camera, samplingMode, engine, reusable);
  29809. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  29810. this._colorTableTexture.anisotropicFilteringLevel = 1;
  29811. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  29812. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  29813. this.onApply = function (effect) {
  29814. effect.setTexture("colorTable", _this._colorTableTexture);
  29815. };
  29816. }
  29817. return ColorCorrectionPostProcess;
  29818. })(BABYLON.PostProcess);
  29819. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  29820. })(BABYLON || (BABYLON = {}));
  29821. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.mapvar BABYLON;
  29822. (function (BABYLON) {
  29823. var SmartCollection = (function () {
  29824. function SmartCollection(capacity) {
  29825. if (capacity === void 0) { capacity = 10; }
  29826. this.count = 0;
  29827. this._initialCapacity = capacity;
  29828. this.items = {};
  29829. this._keys = new Array(this._initialCapacity);
  29830. }
  29831. SmartCollection.prototype.add = function (key, item) {
  29832. if (this.items[key] != undefined) {
  29833. return -1;
  29834. }
  29835. this.items[key] = item;
  29836. //literal keys are always strings, but we keep source type of key in _keys array
  29837. this._keys[this.count++] = key;
  29838. if (this.count > this._keys.length) {
  29839. this._keys.length *= 2;
  29840. }
  29841. return this.count;
  29842. };
  29843. SmartCollection.prototype.remove = function (key) {
  29844. if (this.items[key] == undefined) {
  29845. return -1;
  29846. }
  29847. return this.removeItemOfIndex(this.indexOf(key));
  29848. };
  29849. SmartCollection.prototype.removeItemOfIndex = function (index) {
  29850. if (index < this.count && index > -1) {
  29851. delete this.items[this._keys[index]];
  29852. while (index < this.count) {
  29853. this._keys[index] = this._keys[index + 1];
  29854. index++;
  29855. }
  29856. }
  29857. else {
  29858. return -1;
  29859. }
  29860. return --this.count;
  29861. };
  29862. SmartCollection.prototype.indexOf = function (key) {
  29863. for (var i = 0; i !== this.count; i++) {
  29864. if (this._keys[i] === key) {
  29865. return i;
  29866. }
  29867. }
  29868. return -1;
  29869. };
  29870. SmartCollection.prototype.item = function (key) {
  29871. return this.items[key];
  29872. };
  29873. SmartCollection.prototype.getAllKeys = function () {
  29874. if (this.count > 0) {
  29875. var keys = new Array(this.count);
  29876. for (var i = 0; i < this.count; i++) {
  29877. keys[i] = this._keys[i];
  29878. }
  29879. return keys;
  29880. }
  29881. else {
  29882. return undefined;
  29883. }
  29884. };
  29885. SmartCollection.prototype.getKeyByIndex = function (index) {
  29886. if (index < this.count && index > -1) {
  29887. return this._keys[index];
  29888. }
  29889. else {
  29890. return undefined;
  29891. }
  29892. };
  29893. SmartCollection.prototype.getItemByIndex = function (index) {
  29894. if (index < this.count && index > -1) {
  29895. return this.items[this._keys[index]];
  29896. }
  29897. else {
  29898. return undefined;
  29899. }
  29900. };
  29901. SmartCollection.prototype.empty = function () {
  29902. if (this.count > 0) {
  29903. this.count = 0;
  29904. this.items = {};
  29905. this._keys = new Array(this._initialCapacity);
  29906. }
  29907. };
  29908. return SmartCollection;
  29909. })();
  29910. BABYLON.SmartCollection = SmartCollection;
  29911. })(BABYLON || (BABYLON = {}));
  29912. //# sourceMappingURL=babylon.smartCollection.js.map